How to make FileSystemWatcher Wait for Completion

N

NBB

I have a FileSystemWatcher set and working with the OnFileCreated
event. Only thing is, it launches too quickly!

I'm copying MP3 files into a directory (the directory that the FSW
monitors) and seeing as how the files being copied are somewhat large,
the OnFileCreated event doesn't wait until the actual copying
procedure is finished. Therefore, the stuff I have set to happen at
the OnFileCreated event doesn't run, because the file is completely
written.

Is there a way to force the OnFileCreated event to delay for a set
time before it executes?


BTW-This email address is no longer in service, so please reply here
in the boards.

Thanks!
 
K

Kikoz

You can wait til the whole thing will be loaded by trying
to open the file every let's say 3 seconds.

Here is one method I have that serves exactly the same
porpose (in win app, though, but it should work just fine
in asp.net as well):

public static void WaitToLoad(string fileName,int
milliseconds)
{
DateTime dtStart = DateTime.Now;
TimeSpan ts = new TimeSpan(0);
while(true)
{
try
{
ts = DateTime.Now.Subtract
(dtStart);
FileStream fs = new FileStream
(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
fs.Close();
return;
}
catch(FileNotFoundException)
{
throw;
}
catch(IOException exc)
{
if(ts.Milliseconds > milliseconds)
throw new FileNotLoaded
(fileName,milliseconds,exc);
Thread.Sleep(1000);
continue;
}
}
}

Enjoy :)
 
N

NBB

Thanks, Kikoz!

I liked your idea with the try...catch idea using a non-shared
FileStream to check for access to the specified file. It lead me to
some research in the SDK regarding functionality of a try...catch
block that I never knew.

Evidently, you can label the sections of a try...catch block, just
like in an "On Error GoTo x" event call. I don't think the SDK
explicitly says you can add labels to try...catch blocks, but I tried
it, and it works like a charm.

Thanks for the inspiration! You saved the day!

VB Example Code Follows:
===============================

Try
Conversion:
Dim fs As New FileStream(e.FullPath,FileMode.Open,FileAccess.Read,FileShare.None)
fs.Close()
Console.WriteLine("File Created: " & e.Name)
Thread.Sleep(2000)
Process.Start("some.exe", "arguments")
Catch ex As System.IO.IOException
Console.WriteLine("There was an IOException error. Retrying in 2
seconds...")
Thread.Sleep(2000)
GoTo Conversion
Finally
Console.WriteLine("Process Completed.")
End Try

===============================
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top