C#检测是否文件是否被其他进程占用

来源:互联网 发布:阿里云 io hang 编辑:程序博客网 时间:2024/05/22 10:48

在程序中,我们经常遇到读写文件的情况,而这个时候该文件可能被其他程序占用,那么怎么判断文件是否被占用,从而友好的提示用户呢?

这里提供一个简单的办法,他就是尝试着去读该文件,如果失败,则说明文件被占用:

public static bool IsFileOpen(string filePath)        {            bool result = false;            System.IO.FileStream fs=null;            try            {                fs = File.OpenWrite(filePath);                fs.Close();            }            catch (Exception ex)            {                result = true;            }            return result;//true 打开 false 没有打开        }
原文地址:http://blog.csdn.net/dannywj1371/article/details/7869433