且构网

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

更好地检查路径是文件还是目录?

更新时间:2023-11-29 19:24:46

p>从如何判断路径是否文件或目录

// 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:

if (attr.HasFlag(FileAttributes.Directory))
    MessageBox.Show("Its a directory");
else
    MessageBox.Show("Its a file");