FileSystemWatcher problem!

  • Thread starter Thread starter VI
  • Start date Start date
V

VI

Hi all,
I have a problem with the fsw object, and maybe someone experienced with
the fsw can help me out.
First I want to a share a snippet of the code with you:

private void fsw1_Changed(object sender, FileSystemEventArgs e)
{
if (FSWConfiguration.EnableSendEmail)
{
try
{
Utilities.SendMail(
FSWConfiguration.FromWho,
FSWConfiguration.SendToEmail,
FSWConfiguration.Subject,
"", e.FullPath);
}
catch (Exception ex)
{
if (FSWConfiguration.EnableErrorLogEmail)
{
EventLog.WriteEntry("FSW", ex.ToString(),
EventLogEntryType.Error);
Utilities.LogError(ex);
}
}
finally
{
EventLog.WriteEntry("FSW", "Moving file created to" +
fsw1.Path.ToString() + e.Name.ToString() + fsw1.Path.ToString() +
"\\backup\\" + e.Name.ToString());
try
{
string source = e.FullPath;
string destination = fsw1.Path.ToString() + "backup\\" +
e.Name.ToString();
Directory.Move(source,destination);
}
catch (Exception ex)
{
EventLog.WriteEntry("FSW", "Error while trying to move file
" + e.Name + " to \backup directory. Error:" + ex.ToString(),
EventLogEntryType.Error);
}
}
}
else
{
EventLog.WriteEntry("FSW", "debugging. triggered changed event for
file " + e.FullPath.ToString());
}
}

What this piece of code should do :) is the following:
When a file has ended been written to, based on the NotifyFilter of the
fsw1 object, it should be mailed to a recipient and
then move to a folder \backup.
What it does is, make a mail 2-3-4 times mail it ok but it does not move the
file 'cause it says it is used by another process.

So my 2 questions are:
1) Why does the event fire more than once?
2) Why does it lock the file and does not let me move it?

Cheers,

Vassilis I.
 
The event could be firing multiple times if you've somehow registered it
multiple times. Check to see what filenames are being passed through. What
file watch event is the method associated with?

With regards to the access problem; could be:

1. The event has fired but the operation that caused the event is still in
progress (see what event is being monitored above).

2. If the file can be accessed at the start of the handler then it may be
that the Utilities.SendMail is not closing the file. Try opening the file
exlusively at the start of the event (and then closing it).

3. Is some other process accessing the file.

It may help to use member variables for the monitorFolder and
monitorBackupFolder (reduces amount of code in the statements) as in:

File.Move(
Path.Combine(this.monitorFolder, e.Name),
Path.Combine(this.monitorBackupFolder, e.Name));

HTH

- Andy
 

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

Back
Top