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;
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM