C#如何判断文件处于打开状态

二似柒TA770
2013-10-09 · TA获得超过4758个赞
知道小有建树答主
回答量:1024
采纳率:0%
帮助的人:2402万
展开全部
对于应用程序,有时候可能需要判断某个文件是否已经被打开,也就是指是否被某个流连接着。这在对文件的读写比较频繁的程序中尤为重要,因为一个文件同一时刻只能有一个流连接的。下面的代码也许能有所帮助。 [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(); } }结果:
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式