如何判断一个文件是否正在被使用

这段时间在做文件操作方面的工作.虽然看似简单,实际却很烦琐,容易出现问题,加之测试也不是很方便.

有时要向文件写入东西,在打开文件前不单要判断文件是否存在,还要判断文件是否被别人使用.代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 
 5 public class FileUseTest
 6 {
 7     public static void Main()
 8     {
 9         FileUseTest fut = new FileUseTest();
10         if(fut.IsUsed("c:\\1.doc"))
11         {
12             Console.WriteLine("文件已经被打开!");
13         }
14         
15         Console.Read();
16         
17     }
18     
19     public bool IsUsed(String fileName)
20     {
21         bool result = false;
22         
23         try
24         {
25             FileStream fs = File.OpenWrite(fileName);
26             fs.Close();
27         }
28         catch
29         {
30             result = true;
31         }
32         
33         return result;
34     }
35 }

 

如果文件已经被使用(如打开),则返回true.

经测试,word,excel文档都能判断成功,但txt文件则不能使用此方法.

posted @ 2009-07-20 14:23  小冰  阅读(2548)  评论(0编辑  收藏  举报