C#如何判断文件处于打开状态
来源:互联网 发布:象棋ai算法 编辑:程序博客网 时间:2024/05/14 13:55
对于应用程序,有时候可能需要判断某个文件是否已经被打开,也就是指是否被某个流连接着。这在对文件的读写比较频繁的程序中尤为重要,因为一个文件同一时刻只能有一个流连接的。下面的代码也许能有所帮助。
- 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;
- }
- }
测试:
- 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();
-
结果:
代码下载:http://download.csdn.net/detail/yysyangyangyangshan/4914142
- C#如何判断文件处于打开状态
- C#如何判断文件处于打开状态
- C# winform中判断文件是否处于打开状态
- C#判断文件打开、占用的状态
- 如何判断手机是否处于漫游状态?
- 请问如何判断一个窗口是否处于隐藏状态?
- Linux系统下如何判断apache是否处于监听状态?
- C#判断文件是否打开
- C#判断文件是否打开
- C#判断文件是否打开
- Android 如何判断手机处于电源充电状态还是USB连接状态?
- 如何随时处于就绪状态?
- 如何随时处于就绪状态?
- eclipse打开后处于无响应状态
- eclipse打开后处于无响应状态
- 判断Cookies是否处于开启状态
- 判断Cookies是否处于开启状态
- 判断Cookies是否处于开启状态
- jscalendar-1.0 日期选择框显示问题
- 老友记全10集看完了,2个月的时光一晃而过!
- 职业指导师给面试菜鸟们的49条一句话指南
- 在Android编译并使用FFMPEG
- HDU--杭电--1716--排列2--深度优先搜索--此类中的基础题,也是水题
- C#如何判断文件处于打开状态
- android4.1CTS测试
- DNS域名解析全过程
- VB.net学习笔记(四)数据类型-值类型
- 杭电1598-find the most comfortable road
- 再谈英语认识
- The Hound of the Baskervilles——6、Morn Mystery
- 什么是 initrd.img
- Ubuntu 13.04 Language Support没有中文支持