-
当我们需要判断一个路径是否为文件夹时,如果只是File.Exists和Directory.Exists进行判断只能判断对应路径的文件或者目录是否存在,不能精确地进行判断。
-
我们可以使用File.GetAttributes方法来判断一个路径的得文件或者目录的属性,包括是否为隐藏文件,只读,系统文件等属性。
以下代码只能判断目标路径是是否为文件夹:
public static bool IsDirectory(string path)
{
try
{
//获取指定路径的文件属性,这些属性是 FileAttributes 枚举值的组合
FileAttributes attr = File.GetAttributes(path);
//将路径的属性 attr 与 FileAttributes.Directory 进行按位与操作。如果 attr 包含 FileAttributes.Directory 标志位,则结果会是 FileAttributes.Directory
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}