C#判断文件是否被其他程序打开的几种方法

方法一

直接使用流判断

        public static bool isFileLocked(string pathName)
        {
            try
            {
                if (!File.Exists(pathName))
                {
                    return false;
                }

                using (var fs = new FileStream(pathName, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    fs.Close();
                }
            }
            catch
            {
                return true;
            }
            return false;
        }

方法二

调用dll的一些方法

    public class FileStatus
    {
        [DllImport("kernel32.dll")]
        private static extern IntPtr _lopen(string pathName, int readWrite);

        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr hObject);

        private const int OF_READWRITE = 2;
        private const int OF_SHARE_DENY_NONE = 0x480;
        private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);

        public static bool FileIsOpen(string pathName)
        {
            if (!File.Exists(pathName))
            {
                return false;
            }

            IntPtr handle = _lopen(pathName, OF_READWRITE | OF_SHARE_DENY_NONE);
            if (handle == HFILE_ERROR)
            {
                return true;
            }

            CloseHandle(handle);
            return false;
        }
    }
posted @ 2020-06-28 19:18  醉曦  阅读(2454)  评论(0编辑  收藏  举报