#Sample of the Day 检查文件是否被使用

今天在网上看到了有 Sample of the Day 这样的栏目,其实每天看一个代码示例,也花费不了多少时间,如果能坚持下来,应该会有收获。

今天看了一下 [Sample of Mar 12th] Check whether a file is in use or not,代码如下:

 1 /// <summary> 
2 /// This function checks whether the file is in use or not.
3 /// </summary>
4 /// <param name="filename">File Name</param>
5 /// <returns>Return True if file in use else false</returns>
6 public static bool IsFileInUse(string filename)
7 {
8 bool locked = false;
9 FileStream fs = null;
10 try
11 {
12 fs =
13 File.Open(filename, FileMode.OpenOrCreate,
14 FileAccess.ReadWrite, FileShare.None);
15 }
16 catch (IOException )
17 {
18 locked = true;
19 }
20 finally
21 {
22 if (fs != null)
23 {
24 fs.Close();
25 }
26 }
27 return locked;
28 }

经常会遇到类似的需要判断文件是否在用的问题,这里给出的方案应该是比较容易使用的。

一开始我有一点疑问,就是如果文件不存在的情况下,那么这个方法可能并不合适。后来,下载完整代码示例,发现示例中在调用 FileInUse.IsFileInUse(fileName) 之前,已经使用 File.Exist 验证过文件是否存在这样问题。

而现有的 FileInUse.IsFileInUse(fileName) 方法,其实更符合每个方法只处理一件事情的原则。

另外一个疑问,是关于 FileInUse.IsFileInUse(fileName) 方法中的异常处理的,我注意到 File.Open() 可能引发的异常除了 Exception.IOException 之外(包括 IO 异常的子类),还有一些 Exception.SystemException 类的异常(包括其子类异常,比如 System.ArgumentException 和 System.ArgumentNullException 等),主要是因为传递的参数(文件路径)有问题。而示例程序中只处理了 System.IOException,这里是否有漏洞呢?

后来再查看 File.Exist(string path) 的返回值,发现关于文件路径为空、或者是文件路径不合法的问题都已经处理过了,方法会返回 false,而且这个方法不会返回异常。

true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. This method also returns false if path is null, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path.

最后,还注意到这里使用了 try ... catch ... 来组织代码的结构,与常用的 if ... else ... 不太一样(忘记在哪里看到过,最好不要使用 try ... catch ... 来组织代码);仔细想想,如果使用 if ... else ... 结构,那么这段代码会更加的复杂。

这一小段程序写的,还真是滴水不漏啊。

posted on 2012-03-19 11:41  zhaorui  阅读(304)  评论(0编辑  收藏  举报

导航