• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C#判断本地文件是否处于打开状态

OC/C/C++ 水墨上仙 2420次浏览

C#判断本地文件是否处于打开状态
对于应用程序,有时候可能需要判断某个文件是否已经被打开,也就是指是否被某个流连接着。这在对文件的读写比较频繁的程序中尤为重要,因为一个文件同一时刻只能有一个流连接的。下面的代码也许能有所帮助。
来源:http://blog.csdn.net/yysyangyangyangshan/article/details/8364388

 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();
            Console.WriteLine("文件被关闭");
            result = FileStatus.FileIsOpen(testFilePath);
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }


喜欢 (0)
加载中……