C#中相当于Python的os.path.exists()的是什么?

2 投票
3 回答
1134 浏览
提问于 2025-04-16 11:39

我可以用 Python 的 os.path.exists() 来检查一个文件是否存在。那么在 C# 里,有什么类似的函数呢?

3 个回答

2
System.IO.File.Exists(@"c:\path\to\your\file.ext");

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

3

你肯定是想说.NET,而不是C#吧 :)

可以试试这个 System.IO.File.Exists

3

在编程中,System.IO.FileSystem.IO.Directory 都有一个叫 Exists 的功能。

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

还有一个额外的小提示:为了让你的代码在不同平台上都能用,比如Windows和Mac,你可以使用 System.IO.Path.Combine("c:", "directory", "file.txt"); 这个方法。它会自动把目录的各个部分连接起来,使用 System.IO.Path.DirectorySeparatorChar 来处理不同系统的路径分隔符。当然,只有Windows有C:这个盘符,所以你需要知道在其他系统上应该用什么作为根目录。

撰写回答