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

前端 未结 8 1921
情歌与酒
情歌与酒 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 07:53

    Sure :)

    internal static bool FileOrDirectoryExists(string name)
    {
       return (Directory.Exists(name) || File.Exists(name));
    }
    
    0 讨论(0)
  • 2020-12-09 07:55
    bool FileOrDirectoryExists(string path)
    {
        try
        {
            File.GetAttributes(_source);
        }
        catch (FileNotFoundException)
        {
            return false;
        }
        return true;
    }
    
    0 讨论(0)
  • 2020-12-09 07:57

    How about checking whether FileAttributes == -1?

    public static bool PathExists(this string path) {
        DirectoryInfo dirInfo = null;
        try { dirInfo = new DirectoryInfo(path.TrimEnd(Path.DirectorySeparatorChar)); }
        catch { }
        if (dirInfo == null || dirInfo.Attributes == (FileAttributes)(-1))
            return false;
        return true;
    }
    
    0 讨论(0)
  • 2020-12-09 08:00

    Another way to check if file exist.

    FileInfo file = new FileInfo("file.txt");
    
    if (file.Exists)
    {
        // TO DO
    }
    
    0 讨论(0)
  • 2020-12-09 08:08

    You can use following function:

    [DllImport("shlwapi", EntryPoint = "PathFileExists", CharSet = CharSet.Unicode)]
    public static extern bool PathExists(string path);
    
    0 讨论(0)
  • 2020-12-09 08:09

    My way of checking this is using the FileSystemInfo, here is my code:

    FileSystemInfo info = 
      File.GetAttributes(data.Path).HasFlag(FileAttributes.Directory) ? 
        new DirectoryInfo(data.Path) : (FileSystemInfo)new FileInfo(data.Path);
    
    return info.Exists;
    
    0 讨论(0)
提交回复
热议问题