Solved

FileSystemWatcher Events

Posted on 2009-03-30
3
276 Views
Last Modified: 2012-05-06
We have a simple Windows Service that we wrote in C# that is supposed to watch a folder and run a batch file when a new file arrives. We have a report that is generated by our legacy system that is supposed to be emailed. The system locks the file when it starts writing to it and only unlocks it once it finsihes. Microsoft has the following in docs:
The OnCreated event is raised as soon as a file is created. If a file is being copied or transferred into a watched directory, the OnCreated event will be raised immediately, followed by one or more OnChanged events.

I think when legacy system has the file locked, the service tries to react to OnCreated and get stuck because at that time the file is locked. We only want the service to run the batch file when file is unlocked hence completed.

How can this situation be handled?
0
Comment
Question by:zakali
3 Comments
 
LVL 2

Accepted Solution

by:
m_Kristian earned 500 total points
Comment Utility
Depending on how complex the behavior of the legacy system is, this may be more or less simple to resolve. If the file is being written in one go - the system opens the file with write access and writes everything to the stream before closing it - then it should be relatively simple to do what you want.

You could use the Changed event of the FileSystemWatcher. I presume that when the legacy system starts working on generating the report, you will first get a Created event for the file and then not until the file has been fully written, you will get the Changed event (Scenario A) announcing that the file size grew. If the legacy system is opening and closing the file several times while working on it, this will definitely not work.

Alternatively, when the file is created you could place it in a list internally in your service application and then have a timer which checks the last write time of the file at intervals, until you think it is safe to determine that the legacy system is done writing to it (Scenario B). This will of course mean that there is a delay between the time when the legacy system is done with the file and the time when your service runs the batch file. The maximum delay would be the period of time which you decide must pass before it is safe to process the file + the timer interval.

//

// Scenario A: Use Changed event of the FileSystemWatcher

//

void folderWatcher_Changed(object sender, FileSystemEventArgs e)

{

    if (e.ChangeType == WatcherChangeTypes.Changed)

    {

        RunBatchFile(e.FullPath);

    }

}
 

//

// Scenario B: Use internal list

//

void folderWatcher_Created(object sender, FileSystemEventArgs e)

{

    lock (this.syncRoot)

    {

        this.pendingFileList.Add(e.FullPath);

    }

}
 

void timer_Tick(object sender, EventArgs e)

{

    lock (this.syncRoot)

    {

        foreach (string file in this.pendingFileList)

        {

            if (DateTime.Now.Subtract(File.GetLastWriteTime(file)) > TimeSpan.FromMinutes(2))

            {

                RunBatchFile(file);

            }

        }

    }

}

Open in new window

0
 
LVL 6

Expert Comment

by:Cebik
Comment Utility
Add Check file locked after fileChanged...
After third (last) fileChanged event file should be unlocked..
if not.. add: System.Threading.Thread.Sleep(100);
before check file locked state..

http://www.codeguru.com/csharp/csharp/cs_network/article.php/c6043
(there is no methode to check file locked state)

http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_23680030.html
(methode to check file locked state)

public bool isLocked(string s) 

{

  if (!File.Exists(s)) return false;

  try 

  { 

     FileStream f = File.Open(s, FileMode.Open, FileAccess.ReadWrite);

     f.Close(); 

  }

  catch

  {

     return true; 

  }

  return false;

}

Open in new window

0
 

Author Closing Comment

by:zakali
Comment Utility
Thanks a lot for your help.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
VBSCRIPT in Page Load C# ASP.NET 6 51
.NET Error 7 40
asp.net bundle 8 32
Check my code out(2) 1 24
Article by: Ivo
Anonymous Types in C# by Ivo Stoykov Anonymous Types are useful when  we do not need to follow usual work-flow -- creating object of some type, assign some read-only values and then doing something with them. Instead we can encapsulate this read…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now