none
如何判断异常是“文件被占用”? RRS feed

  • 问题

  • 我使用new FileStream去打开一个文件,如果该文件正在被其他程序占用,我需要捕获这个异常并提示用户

    现在问题是,发生异常的时候,如果准确判断就是“文件被占用”这种类型?

    难道我要用字符串比较的方法吗?那这样不同语言的Windows就无法通用了啊!

    而如果不判断的话,又无法保证异常是“文件被占用”这种类型(例如还有可能是文件损坏、文件不存在等等)



    da jia hao!

    2020年10月13日 9:51

答案

  • Hi liubin,

    你可以尝试用winapi来准确的检测异常是否文件被占用。

    下面是具体的代码。

     [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern SafeFileHandle CreateFile(string lpFileName,
        FileSystemRights dwDesiredAccess, FileShare dwShareMode, IntPtr
        securityAttrs, FileMode dwCreationDisposition, FileOptions
        dwFlagsAndAttributes, IntPtr hTemplateFile);
            const int ERROR_SHARING_VIOLATION = 32;
            static void Main(string[] args)
            {
                FileStream file = null;
                FileStream file1 = null;
                string fileName = "D:\\Data.txt";
                try
                {
                    file = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite); //file is opened
                                                                                      //you use the file here
                    file1 = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    SafeFileHandle fileHandle =
                  CreateFile(fileName, FileSystemRights.Modify,
                        FileShare.Write, IntPtr.Zero,
                        FileMode.OpenOrCreate, FileOptions.None, IntPtr.Zero);
    
                    if (fileHandle.IsInvalid)
                    {
                        if (Marshal.GetLastWin32Error() ==ERROR_SHARING_VIOLATION)
                        {
                            Console.WriteLine("File is in use");
                        }
                    }
                    fileHandle.Close();
                }

    根据下面的链接,你可以找到当数字为32时,对应的异常是‘The process cannot access the file because it is being used by another process.’.

    System Error Codes (0-499)

    希望对你有所帮助。

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • 已标记为答案 liubin 2020年10月20日 8:00
    2020年10月14日 2:14
    版主