C# 判断文件是否在使用的状态
引用:using System.Runtime.InteropServices;
类下面加入:
[DllImport("kernel32.dll")]
public static extern IntPtr _lopen(string lpPathName, int iReadWrite);
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);
以下为调用用到的Function:
public static bool Check_Fileused(string fileName)
{
bool inUse = true;
const int OF_READWRITE = 2;
const int OF_SHARE_DENY_NONE = 0x40;
IntPtr HFILE_ERROR = new IntPtr(-1);
if (!File.Exists(fileName))
{
inUse = false;
}
IntPtr vHandle = _lopen(fileName, OF_READWRITE | OF_SHARE_DENY_NONE);
if (vHandle == HFILE_ERROR)
{
inUse = false;
}
else
{
inUse = true;
}
CloseHandle(vHandle);
return inUse;
}