[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

FileSystemWatcher Events

Posted on 2009-03-30
3
Medium Priority
?
306 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 2000 total points
ID: 24026258
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
ID: 24034639
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
ID: 31564684
Thanks a lot for your help.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Integration Management Part 2
Screencast - Getting to Know the Pipeline
Suggested Courses

873 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