public class FileUtil
{
[DllImport("kernel32.dll")]
private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hHandle);
private const int OF_READWRITE = 2;
private const int OF_SHARE_DENY_NONE = 0x40;
private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
/// <summary>
/// 查看文件是否被占用
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
public static bool IsOccupied(string filePath)
{
IntPtr vHandle = _lopen(filePath, OF_READWRITE | OF_SHARE_DENY_NONE);
if(vHandle == HFILE_ERROR)
{
return true;
}
CloseHandle(vHandle);
return false;
}
}