【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);

/// 
/// 文件是否被打开
/// 
/// 
/// 
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; 
}

 

你可能感兴趣的:(C#操作文件)