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

前端 未结 8 1937
情歌与酒
情歌与酒 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: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;
    }
    

提交回复
热议问题