This is the code I wrote for that. See if it is of any use for you.
/// <summary>
/// Makes sure that the file is fully saved by trying to open it for
ReadWrite.
/// Generates exception if fails to do this within given period of
time.
/// </summary>
/// <param name="fi">FileInfo of the file to watch</param>
/// <param name="toSeconds">timeout in seconds</param>
/// <exception cref="System.Exception">Timeout: file is locked by
the writing process for more than specified time</exception>
static public void WaitForFullySaved (FileInfo fi, int toSeconds)
{
int timeout;
FileStream fs;
timeout = toSeconds * 1000;
while (timeout > 0)
try
{
fs = fi.Open (FileMode.Open, FileAccess.ReadWrite);
fs.Close ();
break;
}
catch (IOException)
{
System.Threading.Thread.Sleep (500);
timeout -= 500;
}
if (timeout <= 0)
throw (new Exception (String.Format (
"File {1} is locked by the writing process for more than
{2} seconds",
fi.Name, toSeconds)));
}
Eliyahu
"McFly Racing" <No****@Microsoft.com> wrote in message
news:ue**************@TK2MSFTNGP09.phx.gbl...
I have a file being copied to my server from another server on the
network. My program needs to work with this file when it is received on my server.
The problem I have is that when I go to process the file it may still be
being written to the disk and thus I cannot get a valid handle on it to
perform the necessary operations I need to do.
The code I inherited uses a sleep on the thread that the code is running
in. I am looking for a more elegant solution that does not put the thread to
sleep for some static amount of time. Any suggestions would be greatly
appreciated. Thank you.