【发布时间】:2011-06-25 17:14:12
【问题描述】:
我可以使用 os.path.exists() 通过 Python 检查文件是否存在。 C#中的等价函数是什么?
【问题讨论】:
我可以使用 os.path.exists() 通过 Python 检查文件是否存在。 C#中的等价函数是什么?
【问题讨论】:
System.IO.File 和 System.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:,所以你需要知道使用什么作为驱动器的根目录。
【讨论】:
您的意思当然是 .NET,而不是 C# :)
【讨论】:
System.IO.File.Exists(@"c:\path\to\your\file.ext");
【讨论】: