對於應用程序,有時候可能需要判斷某個文件是否已經被打開,也就是指是否被某個流連接著。這在對文件的讀寫比較頻繁的程序中尤為重要,因為一個文件同一時刻只能有一個流連接的。下面的代碼也許能有所幫助。 [csharp] 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; } } 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; } }測試: [csharp] 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(); } } 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(); } }結果: