C#,判断是文件还是文件夹。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#,判断是文件还是文件夹。相关的知识,希望对你有一定的参考价值。

已知一个有效的完整路径,判断他是文件还是文件夹,求指教

楼上的胡说,文件也可能没有扩展名,目录也可以有小数点
判断是文件还是文件夹
if(File.Exists(path))
// 是文件
else if(Directory.Exists(path))
// 是文件夹
else
// 都不是
参考技术A DirectoryInfo dir = new DirectoryInfo(srcPath);
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录
foreach (FileSystemInfo i in fileinfo)

if (i is DirectoryInfo) //判断是否文件夹

DirectoryInfo subdir = new DirectoryInfo(i.FullName);
subdir.Delete(true); //删除子目录和文件

else

File.Delete(i.FullName); //删除指定文件

参考技术B 使用File和 Directory 两个类进行操作,可以研究一下

1、判断文件:
File.Exists(FilePath + @"\" + FileName)
FilePath :路径名 FileName :文件名
返回bool 类型的值

2、判断文件夹
Directory.Exists(FilePath)
FilePath :路径名
返回bool类型的值
参考技术C

File.GetAttributes

有基于类型的定义 

ReadOnly = 1,
Hidden = 2,
System = 4,
        Directory = 16,
Archive = 32,

Device = 64,
Normal = 128,
Temporary = 256,
SparseFile = 512,
ReparsePoint = 1024,
Compressed = 2048,
Offline = 4096,
NotContentIndexed = 8192,
Encrypted = 16384

参考技术D if (!Directory.Exists(HttpContext.Current.Server.MapPath(dirPath)))

Directory.CreateDirectory(HttpContext.Current.Server.MapPath(dirPath));

判断文件夹是否存在 不存在就创建

以上是关于C#,判断是文件还是文件夹。的主要内容,如果未能解决你的问题,请参考以下文章

C# 泛型是引用类型还是值类型,是根据啥判断?

C#怎么判断一个文件的编码格式是UTF-8 without BOM的啊

C#文件相同性判断

C#根据文件流判断文件类型

如何确定文件是c#中的二进制文件还是文本文件? [复制]

C# 判断文件格式的一些总结