[英]C#'s equivalent to Python's os.path.exists()?
I can use os.path.exists() to check if the file exists or not with Python. 我可以使用os.path.exists()来检查文件是否存在。 What's the equivalent function in C#?
C#中的等效功能是什么?
Surely you mean .NET, not C# :) 当然你的意思是.NET,而不是C#:)
Try System.IO.File.Exists . 试试System.IO.File.Exists 。
Both System.IO.File
and System.IO.Directory
has Exists
. 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");
And for an additional bonus: Note that for cross platform compatibility you should use for example System.IO.Path.Combine("c:", "directory", "file.txt");
还有额外的好处:请注意,对于跨平台兼容性,您应该使用例如
System.IO.Path.Combine("c:", "directory", "file.txt");
. 。 This will automatically join the parts of the directory using
System.IO.Path.DirectorySeparatorChar
. 这将使用
System.IO.Path.DirectorySeparatorChar
自动加入目录的各个部分。 Of course only Windows has C:, so you need to know what to use as the root of the drive. 当然只有Windows有C:,所以你需要知道什么作为驱动器的根。
System.IO.File.Exists(@"c:\path\to\your\file.ext");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.