且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查路径是文件还是目录的更好方法?

更新时间: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+ 更新

根据下面的评论,如果您使用的是 .NET 4.0 或更高版本(并且最大性能并不重要),您可以以更简洁的方式编写代码:

Update for .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");