using System.IO;
//filesystemwatcherobject。
私有文件系统维护者;
私有新文本(字符串新文本;
publicvoidupdatewatchtext (字符串新文本) )。
{
lblWatch.Text=newText;
}
公共表单1 () )。
{
初始化组件(;
this.watcher=newfilesystemwatcher (;
this.watcher.deleted=newfilesystemeventhandler (watcher _ deleted );
this.watcher.renamed=newrenamedeventhandler (watcher _ renamed );
this.watcher.changed=newfilesystemeventhandler (watcher _ changed );
this.watcher.created=newfilesystemeventhandler (watcher _ created );
}
void watcher _ created (对象发送器,文件系统事件) )。
{
//thrownewnotimplementedexception (;
特里
{
streamwriter SW=new streamwriter (c :log.txt ',true );
SW.writeline (' file : {0} created ',e.FullPath );
sw.Close (;
this.begininvoke (newupdatewatchtextdelegate (updatewatchtext )、' Wrotecreateeventtolog ' );
}
catch(ioexception ) )。
{
this.begininvoke (newupdatewatchtextdelegate (updatewatchtext )、' ErrorWritingtolog ' );
}
}
void watcher _ changed (对象发送器,文件系统事件) )。
{
//thrownewnotimplementedexception (;
特里
{
streamwriter SW=new streamwriter (c :log.txt ',true );
SW.writeline('file:{0}{1},e.FullPath,e.ChangeType.ToString ) );
sw.Close (;
this.begininvoke (newupdatewatchtextdelegate (updatewatchtext )、' Wrotechangeeventtolog ' );
}
Catch
){
this .BeginInvoke( new UpdateWatchTextDelegate(UpdateWatchText), " Error Writing to log " );
}
}
void watcher_Renamed( object sender, RenamedEventArgs e)
{
// throw new NotImplementedException();
try
{
StreamWriter sw = new StreamWriter( " c:\Log.txt " , true );
sw.WriteLine( " File renamed from {0} to {1} " , e.OldName, e.FullPath);
sw.Close();
this .BeginInvoke( new UpdateWatchTextDelegate(UpdateWatchText), " Wrote renamed event to log " );
}
catch (IOException)
{
this .BeginInvoke( new UpdateWatchTextDelegate(UpdateWatchText), " Error Writing to log " );
}
}
void watcher_Deleted( object sender, FileSystemEventArgs e)
{
// throw new NotImplementedException();
try
{
StreamWriter sw = new StreamWriter( " c:\Log.txt " , true );
sw.WriteLine( " File: {0} Deleted " , e.FullPath);
sw.Close();
this .BeginInvoke( new UpdateWatchTextDelegate(UpdateWatchText), " Wrote delete event to log " );
}
catch (IOException)
{
this .BeginInvoke( new UpdateWatchTextDelegate(UpdateWatchText), " Error Writing to log " );
}
}
private void cmdBrowse_Click( object sender, EventArgs e)
{
if (FileDialog.ShowDialog() != DialogResult.Cancel)
{
txtLocation.Text = FileDialog.FileName;
cmdWatch.Enabled = true ;
}
}
private void cmdWatch_Click( object sender, EventArgs e)
{
watcher.Path = Path.GetDirectoryName(txtLocation.Text); // 监控路径(文件夹)
watcher.Filter = " *.* " ; // 如果filter为文件名称则表示监控该文件,如果为*.txt则表示要监控指定目录当中的所有.txt文件
watcher.NotifyFilter = NotifyFilters.LastWrite |
NotifyFilters.FileName |
NotifyFilters.Size;
lblWatch.Text = " Watching " + txtLocation.Text;
// begin watching.
watcher.EnableRaisingEvents = true ;
}