FileSystemWatcher OnChanged : What Changed ??

T

TD

I'm watching a folder for new files. When the files arrive, I want to
wait until it is done being written to and then move it.

Every time I move a file into the test folder, it triggers 3 calls to
the OnChanged handler.

I can't tell what is changing between the 2nd and 3rd call to know
whether it is safe to move the file yet? If I was certain it was
always 3, I could go then but I'm not sure that it will always be 3
calls.

I've Console.Writeline'd everything that I can think of but noting
appears to be changing.

Any ideas? I've included the necessary code blocks



** WATCH THE FOLDER ***

FileSystemWatcher watcher = new FileSystemWatcher();

watcher.Path = "c:\\temp\\xml";

watcher.IncludeSubdirectories = false;
watcher.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.FileName |
NotifyFilters.DirectoryName |
NotifyFilters.Size;

// Only watch xml files.
watcher.Filter = "*.xml";



watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);

// Begin watching.
watcher.EnableRaisingEvents = true;

// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');




private static void OnChanged(object source, FileSystemEventArgs e)
{

FileInfo fi = new FileInfo(e.FullPath);

if(fi.LastWriteTime >= DateTime.Now)
{
Console.WriteLine("still writing");
}
else
{

Console.WriteLine("done writing");


// MOVE THE FILE
// can't leave like this because of multiple calls
fi.MoveTo("c:\\temp\\xml_to");


}

}
 
R

Ricky Lee

Do you have antivirus installed on your system? File system operations might
raise more than one event. (See the Note in the FileSystemWatcher reference
on msdn website,
http://msdn.microsoft.com/library/d.../frlrfSystemIOFileSystemWatcherClassTopic.asp).

For your purpose you can try the following workaround:

private static void OnChanged(object sender, FileSystemEventArgs e)
{
FileInfo fi = new FileInfo(e.FullPath);
if(fi.LastWriteTime >= DateTime.Now)
{
Console.WriteLine("still writing");
}
else
{
Console.WriteLine("done writing");
// MOVE THE FILE
// ** Check first whether the file still exists
// ** if exists, move the file
// ** else ignore the operation
if(File.Exists(fi.FullName))
{
fi.MoveTo("c:\\temp\\xml_to");
}
}
}

Hope it helps.

-- Ricky Lee
============================================
^ o^ "When all doors are closed, God will open Windows" ^o^
============================================
 

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

Top