1、判断文件夹是否存在
//Directory类的Exists方法
bool a1 = Directory.Exists("C:\\Program Files");
Console.WriteLine(a1);
//DirectoryInfo类的Exists属性
DirectoryInfo a2 = new DirectoryInfo("C:\\Program Files");
if(a2.Exists)
{
Console.WriteLine("此文件夹存在");
}
else
{
Console.WriteLine("此文件夹不存在");
}
2、创建文件夹
//Directory类的CreateDirectory方法
Directory.CreateDirectory("d:\\新建文件夹");
//DirectoryInfo类的Create方法
DirectoryInfo x1 = new DirectoryInfo("d:\\新建文件夹");
x1.Create();
3、移动文件夹
//Directory类的Move方法
Directory.Move("c:\\新建文件夹(1)", "c:\\新建文件夹(2)");
//DirectoryInfo类的MoveTo方法
DirectoryInfo x1 = new DirectoryInfo("c:\\新建文件夹(1)");
x1.MoveTo("c:\\新建文件夹(2)");
4、删除文件夹
//Directory类的Delete方法
Directory.Delete("d:\\新建文件夹");
//DirectoryInfo类的Delete方法
DirectoryInfo x1 = new DirectoryInfo("d:\\新建文件夹");
x1.Delete();
5、遍历文件夹
// 引用一个目录。
DirectoryInfo di = new DirectoryInfo("d:\\");
// 获取对该目录中每个目录的引用。
DirectoryInfo[] diArr = di.GetDirectories();
// 显示目录的名称。
foreach (DirectoryInfo dri in diArr)
Console.WriteLine(dri.Name);
6、条件遍历文件夹
string path = @"d:\";
string searchPattern = "d*";
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo[] directories =di.GetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
FileInfo[] files =di.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);
Console.WriteLine("在{0}目录中,以字母\"d\"开头的文件有:", path);
foreach (DirectoryInfo dir in directories)
{
Console.WriteLine("{0,-25} {1,25}", dir.FullName, dir.LastWriteTime);
}
Console.WriteLine();
Console.WriteLine("在{0}目录中,以字母\"d\" 开头的文件: ", path);
foreach (FileInfo file in files)
{
Console.WriteLine("{0,-25} {1,25}", file.Name, file.LastWriteTime);
}