【C#】判断一个文件是否被打开

 

[DllImport("kernel32.dll")]
public static extern IntPtr _lopen(string lpPathName, int iReadWrite);

[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);
public const int OF_READWRITE = 2;
public const int OF_SHARE_DENY_NONE = 0x40;
public static readonly IntPtr HFILE_ERROR = new IntPtr(-1);

/// <summary>
/// 文件是否被打开
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool IsFileOpen(string path)
{
    if (!File.Exists(path))
    {
        return false;
    }
    IntPtr vHandle = _lopen(path, OF_READWRITE | OF_SHARE_DENY_NONE);//windows Api上面有定义扩展方法
    if (vHandle == HFILE_ERROR)
    {
        return true; 
    }
    CloseHandle(vHandle);
    return false; 
}

 

相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页