我们都知道
filesystemwatcher有个Created 的event, 一般情况下我们直接handle created event就可以直接access 那个文件了, 可是当碰到大文件时就有问题了, 因为文件还在copying. 所以不能对文件做任何operation. 那怎么办呢? 这是我很久以前给朋友写的一个小程序,可以解决这个问题.
1. Create a new FileSystemWatcher.
1
System.IO.FileSystemWatcher fswXmlFileWatcher
=
new
System.IO.FileSystemWatcher();
2
this
.fswXmlFileWatcher.EnableRaisingEvents
=
true
;
3
this
.fswXmlFileWatcher.Path
=
@"
C:\Test
"
4
//
in here I only handle the file created event.
5
this
.fswXmlFileWatcher.Created
+=
new
System.IO.FileSystemEventHandler(
this
.fswXmlFileWatcher_Created);
2. Write Code to handle File Created Event.
1
private
void
fswXmlFileWatcher_Created(
object
sender, System.IO.FileSystemEventArgs e)
2
{ 3lock(this) 4{ 5string filePath = e.FullPath; 6//incase the file is huge, it need some time to write the whole. so we wait untill the file is accessable by .Net 7while (File.GetAttributes(filePath) == FileAttributes.Offline) 8{ 9Thread.Sleep(500);10}11//Ok. We start a new thread to process the file12ImportHelper ih = new ImportHelper(filePath);13Thread th = new Thread(new ThreadStart(ih.ImportXmlFile));14th.Start();15}16}
17
3. what is in the ImportHelper Class.
1
public
class
ImportHelper
2
{ 3private string _filePath; 4private long _fileSize; 5private FileInfo _fileInfo; 6 7public ImportHelper(string filePath) 8{ 9this._filePath = filePath;10this._fileSize = 0;11this._fileInfo = new FileInfo(this._filePath);12}1314//we need to this method. same reason. cause the file size is huge.15private bool TestFile()16{17long size = this._fileInfo.Length;18if( this._fileSize == size )19{20return true;21}22else23{24this._fileSize = size;25return false;26}27}2829public void ImportXmlFile()30{31while( !this.TestFile() )32{33Thread.Sleep(2000);34}35//It is ok now. The file is ready for us to process.36//Write your own function to process the file.37ProcessMyFile(this._filePath)38}39}
40
转载于:https://www.cnblogs.com/isc00028/archive/2008/06/14/1221074.html
相关资源:数据结构—成绩单生成器