首先说明仅仅通过字符串来判断它是指文件还是文件夹,是不严谨的,无法完美的实现。有三种方法可以不完美或者有条件实现判断。
方法一:最简单的方法,判断给定的字符串有没有扩展名。有扩展名的就是文件,没有扩展名的就是目录。
string path=@"C:\windows";
if(System.IO.Path.HasExtension(path)){
MessageBox.Show("这是一个文件夹");
}
else{
MessageBox.Show("这是一个文件");
}
问题显而易见,有些文件夹中间可能有“.”,有些文件可能没有扩展名。
方法二:用File.GetAttributes获取文件的属性
string myFile=@"C:\windows";
if ((File.GetAttributes(myFile) & FileAttributes.Directory))==FileAttributes.Directory){
MessageBox.Show("这是一个文件夹");
}
else{
MessageBox.Show("这是一个文件");
}
这个方法需要字符串代表的文件或文件夹真实存在,如果它不存在,就没有办法判断了。
方法三:用Directory.Exists和File.Exists
string myFile=@"C:\windows";
if (Directory.Exists(sPath)){
MessageBox.Show("这是一个文件夹");
}
If (File.Exists(sPath)){
MessageBox.Show("这是一个文件");
}
这种方法的原理和方法二近似,都需要文件或者文件夹存在。
个人认为第二种方法比较好,用这样的方法还可以判断文件或文件夹的其他属性。具体详情请参见:
https://docs.microsoft.com/zh-cn/dotnet/api/system.io.file.getattribute
https://docs.microsoft.com/zh-cn/dotnet/api/system.io.fileattributes