How To Use: System.IO.FileSystemWatcher to monitor the files
Today I will talk about the "
System.IO.FileSystemWatcher". It allows you to be notified when a file or directory (folder) has been created, renamed, changed or deleted. You can even sit and wait for such an activity to take place. Ok, Let me show you how to use this class.
1. Create a new FileSystemWatcher.
System.IO.FileSystemWatcher fswXmlFileWatcher = new System.IO.FileSystemWatcher();
this.fswXmlFileWatcher.EnableRaisingEvents = true;
this.fswXmlFileWatcher.Path = @"C:\Test"
//in here I only handle the file created event.
this.fswXmlFileWatcher.Created += new System.IO.FileSystemEventHandler(this.fswXmlFileWatcher_Created);
2. Write Code to handle File Created Event.
private void fswXmlFileWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
{
lock(this)
{
string filePath = e.FullPath;
//incase the file is huge, it need some time to write the whole. so we wait untill the file is accessable by .Net
while (File.GetAttributes(filePath) == FileAttributes.Offline)
{
Thread.Sleep(500);
}
//Ok. We start a new thread to process the file
ImportHelper ih = new ImportHelper(filePath);
Thread th = new Thread(new ThreadStart(ih.ImportXmlFile));
th.Start();
}
}
3. what is in the ImportHelper Class.
public class ImportHelper
{
private string _filePath;
private long _fileSize;
private FileInfo _fileInfo;
public ImportHelper(string filePath)
{
this._filePath = filePath;
this._fileSize = 0;
this._fileInfo = new FileInfo(this._filePath);
}
//we need to this method. same reason. cause the file size is huge.
private bool TestFile()
{
long size = this._fileInfo.Length;
if( this._fileSize == size )
{
return true;
}
else
{
this._fileSize = size;
return false;
}
}
public void ImportXmlFile()
{
while( !this.TestFile() )
{
Thread.Sleep(2000);
}
//It is ok now. The file is ready for us to process.
//Write your own function to process the file.
ProcessMyFile(this._filePath)
}
}
1/30/2008 1:37:00 AM
Published by
FengLiN
Category
C Sharp(C#)
Views (424)