#region 检测文件状态及操作方式选择
[DllImport("kernel32.dll")]
private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
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="FileNames">要检测的文件</param>
/// <returns>true可用,false在用或只读</returns>
public static bool CheckFilesState(string fileName)
{
if (!File.Exists(fileName))
return true;//文件不存在
if ((File.GetAttributes(fileName) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
return false; //文件只读
IntPtr vHandle = _lopen(fileName, OF_READWRITE | OF_SHARE_DENY_NONE);
if (vHandle == HFILE_ERROR)
return false; //文件被占用
C# WinForm 检测文件是否被占用
最新推荐文章于 2025-01-17 10:04:45 发布