Cra*_*rge 1 c# file-io file filepath
我试图确定给定的路径是指向文件还是目录.目前我的逻辑很简单,涉及以下检查
if (sourcePath.Contains(".")) // then treat this path as a file
Run Code Online (Sandbox Code Playgroud)
上面的问题是文件夹名称也可以包含句点.我希望能够确定给定的路径是文件的路径,而不必尝试实例化文件流类型并尝试访问它或类似的东西.
有没有办法做到这一点?
提前致谢
Dar*_*rov 10
您可以使用File.Exists方法:
如果path描述目录,则此方法返回false
所以:
if (File.Exists(sourcePath))
{
// then treat this path as a file
}
Run Code Online (Sandbox Code Playgroud)
还有Directory.Exists方法和文档中给出了以下示例:
if(File.Exists(path))
{
// This path is a file
ProcessFile(path);
}
else if(Directory.Exists(path))
{
// This path is a directory
ProcessDirectory(path);
}
else
{
Console.WriteLine("{0} is not a valid file or directory.", path);
}
Run Code Online (Sandbox Code Playgroud)