Check if a file/directory exists: is there a better way?

前端 未结 8 1922
情歌与酒
情歌与酒 2020-12-09 07:41

I find myself doing this a lot just to ensure the filename is not in use. Is there a better way?

Directory.Exists(name) || File.Exists(name)
相关标签:
8条回答
  • 2020-12-09 08:10

    I think that's the only way. I generally have a "FileManager" class which have static methods encapsulating I/O methods including the ones you indicated and then use that "FileManager" across all the applications as a library.

    0 讨论(0)
  • 2020-12-09 08:13

    Note that the fact that you are using Exists() to check for file or directory name in use is subject to race conditions.

    At any point after your Exists() test has passed, something could have created a file with that name before your code reaches the point where you create a file, for example.

    (I'm assuming it is an exceptional condition for the file to already exist).

    It is more reliable to simply to open the file, specifying an appropriate FileShare parameter.

    Example:

    using System;
    using System.IO;
    
    static class FileNameInUse
    {
        static void Main(string[] args)
        {
            string path = args[0];
            using (var stream = File.Open(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            {
                // Write to file
            }
        }
    }
    

    So simply handling the IOException on failure may result in simpler code less prone to race conditions, because now:

    • If something else has already created the file, FileMode.CreateNew will cause an IOException to be thrown
    • If your open and create succeeds, because of FileShare.None, no other process can access the file until you close it.

    Unfortunately, it is not possible to check whether a file is currently in use, and not throw an exception, without some ugly P/Invoke:

        bool IsFileInUse(string fileName)
        {
                IntPtr hFile = Win32.CreateFile(fileName, Win32.FILE_READ_DATA, 0, IntPtr.Zero, Win32.OPEN_EXISTING, Win32.FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
                if (hFile.ToInt32() == Win32.INVALID_HANDLE_VALUE)
                    return true;
    
                Win32.CloseHandle(hFile);
                return false;
        }
    
        class Win32
        {
            const uint FILE_READ_DATA = 0x0001;
            const uint FILE_SHARE_NONE = 0x00000000;
            const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;
            const uint OPEN_EXISTING = 3;
            const int INVALID_HANDLE_VALUE = -1;
    
            [DllImport("kernel32.dll", SetLastError=true)]
            internal static extern IntPtr CreateFile(string lpFileName,
                                                   uint dwDesiredAccess,
                                                   uint dwShareMode,
                                                   IntPtr lpSecurityAttributes,
                                                   uint dwCreationDisposition,
                                                   uint dwFlagsAndAttributes,
                                                   IntPtr hTemplateFile);
    
            [DllImport("kernel32.dll")]
            internal static extern bool CloseHandle(IntPtr hObject);
        }
    

    And this fast check is also prone to race conditions, unless you return the file handle from it, and pass that to the relevant FileStream constructor.

    0 讨论(0)
提交回复
热议问题