path filter
The directory to monitor, in standard or Universal Thetypeoffilestowatch.Forexample,”*.txt”watches for
Naming Convention (UNC) notation. changes to all text files.
Thetypeoffilestowatch.Forexample,”*.txt”watches for changes to all text files.
A common mistake a lot of people starting out with FileSystemWatcher does is not taking into account That the FileWatchereventisraisedassoonasthefileiscreated.However,itmaytakesometimeforthefiletobefinished.
Example:
Take a file size of 1 GB for example . The file apr ask created by another program (Explorer.exe copying it from somewhere) but it will take minutes to finish that process. The event is raised that creation time and you need to wait for the file to be ready to be copied.
Thisisamethodforcheckingifthefileisready.
publicstaticboolIsFileReady(StringsFilename)
{
//Ifthefilecanbeopenedforexclusiveaccessitmeansthatthefile
//isnolongerlockedbyanotherprocess.
try
{
using(FileStreaminputStream=File.Open(sFilename,FileMode.Open,FileAccess.Read, FileShare.None))
{
if(inputStream.Length>0)
{
returntrue;
}
else
{
returnfalse;
}
}
}
catch(Exception)
{
returnfalse;
}
}
The following example creates a FileSystemWatcherto watch the directory specified at run time. The component is settowatchforchangesinLastWriteandLastAccesstime,thecreation,deletion,orrenamingoftextfilesinthe directory. If a file is changed, created, or deleted, the path to the file prints to the console. When a file is renamed, the old and new paths print to the console.
UsetheSystem.DiagnosticsandSystem.IOnamespacesforthisexample.
FileSystemWatcherwatcher;
privatevoidwatch()
{
//CreateanewFileSystemWatcherandsetitsproperties.
watcher=newFileSystemWatcher();
watcher.Path=path;
/*WatchforchangesinLastAccessandLastWritetimes,and therenamingoffilesordirectories.*/
watcher.NotifyFilter=NotifyFilters.LastAccess|NotifyFilters.LastWrite
|NotifyFilters.FileName|NotifyFilters.DirectoryName;
//Onlywatchtextfiles.
watcher.Filter=”*.txt*”;
//Addeventhandler.
watcher.Changed+=newFileSystemEventHandler(OnChanged);
//Beginwatching.
watcher.EnableRaisingEvents=true;
}
//Definetheeventhandler.
privatevoidOnChanged(objectsource,FileSystemEventArgse)
{
//Copiesfiletoanotherdirectoryoranotheraction.
Console.WriteLine(“File:”+ e.FullPath+””+e.ChangeType);
}
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter120:YieldKeyword 20/05/2024
- Chapter119:LockStatement 19/05/2024
- Chapter118:Makingavariablethreadsafe 18/05/2024