【问题标题】:C#'s equivalent to Python's os.path.exists()?C# 相当于 Python 的 os.path.exists()?
【发布时间】:2011-06-25 17:14:12
【问题描述】:

我可以使用 os.path.exists() 通过 Python 检查文件是否存在。 C#中的等价函数是什么?

【问题讨论】:

标签: c# python exists


【解决方案1】:

System.IO.FileSystem.IO.Directory 都有 Exists

bool dirExists = System.IO.Directory.Exists(@"C:\directory\");
bool fileExists = System.IO.File.Exists(@"C:\directory\file.txt");

还有一个额外的好处:请注意,为了实现跨平台兼容性,您应该使用例如System.IO.Path.Combine("c:", "directory", "file.txt");。这将使用System.IO.Path.DirectorySeparatorChar 自动加入目录的各个部分。当然只有 Windows 有 C:,所以你需要知道使用什么作为驱动器的根目录。

【讨论】:

    【解决方案2】:

    您的意思当然是 .NET,而不是 C# :)

    试试System.IO.File.Exists

    【讨论】:

      【解决方案3】:
      System.IO.File.Exists(@"c:\path\to\your\file.ext");
      

      【讨论】:

        猜你喜欢
        • 2020-09-28
        • 2010-12-21
        • 2011-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多