讀寫頻繁的程序經常需要確認:這個檔案是不是已經被別的流佔用了?由於同一個檔案在同一時刻只能被一個流連接,若不先判斷就大膽寫入,很容易拋出 IO 異常。下面這個小工具類藉助 Win32 API 完成了這件事。
思路是嘗試以「讀寫 + 不阻止共享」的方式打開檔案:如果打開失敗並返回 HFILE_ERROR,說明檔案已被他人佔用;若成功,立刻關閉句柄,表示檔案當前空閒。
public class FileStatus
{
[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);
public static int FileIsOpen(string fileFullName)
{
if (!File.Exists(fileFullName))
{
return -1;
}
IntPtr handle = _lopen(fileFullName, OF_READWRITE | OF_SHARE_DENY_NONE);
if (handle == HFILE_ERROR)
{
return 1;
}
CloseHandle(handle);
return 0;
}
}
返回值約定為:-1 檔案不存在,0 檔案空閒,1 檔案已被佔用。
class Program
{
static void Main(string[] args)
{
string testFilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"testOpen.txt";
FileStream fs = new FileStream(testFilePath, FileMode.OpenOrCreate, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
br.Read();
Console.WriteLine("檔案被打開");
int result = FileStatus.FileIsOpen(testFilePath);
Console.WriteLine(result);
br.Close();
Console.WriteLine("檔案被關閉");
result = FileStatus.FileIsOpen(testFilePath);
Console.WriteLine(result);
Console.ReadLine();
}
}
先以 FileStream 保持檔案開啟,此時 FileIsOpen 回傳 1;關閉 reader 後再呼叫,回傳 0。需要留意的是這種探測方式存在時間窗口,僅適合作為「預先提示」而非強制鎖定機制。