更新时间:2023-11-29 19:24:52
来自 如何判断路径是文件还是目录:
// get the file attributes for file or directory
FileAttributes attr = File.GetAttributes(@"c:Temp");
//detect whether its a directory or file
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
MessageBox.Show("Its a directory");
else
MessageBox.Show("Its a file");
根据下面的评论,如果您使用的是 .NET 4.0 或更高版本(并且最大性能并不重要),您可以以更简洁的方式编写代码:
Per the comments below, if you are on .NET 4.0 or later (and maximum performance is not critical) you can write the code in a cleaner way:
// get the file attributes for file or directory
FileAttributes attr = File.GetAttributes(@"c:Temp");
if (attr.HasFlag(FileAttributes.Directory))
MessageBox.Show("Its a directory");
else
MessageBox.Show("Its a file");