我们都知道filesystemwatcher有个Created 的event, 一般情况下我们直接handle created event就可以直接access 那个文件了, 可是当碰到大文件时就有问题了, 因为文件还在copying. 所以不能对文件做任何operation. 那怎么办呢? 这是我很久以前给朋友写的一个小程序,可以解决这个问题.

1. Create a new FileSystemWatcher.
1System.IO.FileSystemWatcher fswXmlFileWatcher = new System.IO.FileSystemWatcher();
2this.fswXmlFileWatcher.EnableRaisingEvents = true
3this.fswXmlFileWatcher.Path = @"C:\Test"
4//in here I only handle the file created event.
5this.fswXmlFileWatcher.Created += new System.IO.FileSystemEventHandler(this.fswXmlFileWatcher_Created);



2. Write Code to handle File Created Event.
 1private 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 file
12ImportHelper ih = new ImportHelper(filePath);
13Thread th = new Thread(new ThreadStart(ih.ImportXmlFile));
14th.Start();
15}

16}
 
17

3. what is in the ImportHelper Class.
 1public 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}

13
14//we need to this method. same reason. cause the file size is huge.
15private bool TestFile()
16{
17long size = this._fileInfo.Length;
18ifthis._fileSize == size )
19{
20return true;
21}

22else
23{
24this._fileSize = size;
25return false;
26}

27}

28
29public 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

posted on 2008-06-14 13:10  -=FengLiN=-  阅读(837)  评论(2)    收藏  举报