C# 向下遍历删除子目录和子文件 及 向上遍历空的父目录
2012-11-14 14:44
399 查看
本示例效果如下:
根据指定的文件夹路径如E:\\a\\b\\d
向下遍历删除其下的子文件及子目录
删除其本身
向上遍历删除其空的父目录
using System.IO;
protected void Button1_Click(object sender, EventArgs e)
{
string dir = "E:\\a\\b\\d";
//string dir = "E:\\a";
string pdir = Directory.GetParent(dir).FullName;
DeleteFolder(dir);
DeletePEmptyFolder(pdir);
}
public void DeleteFolder(string dir)
{
if (Directory.Exists(dir))
{
foreach (string d in Directory.GetFileSystemEntries(dir))
{
if (File.Exists(d))
{
FileInfo fi = new FileInfo(d);
if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
fi.Attributes = FileAttributes.Normal;
File.Delete(d);//直接删除其中的文件
}
else
DeleteFolder(d);//递归删除子文件夹
}
Directory.Delete(dir);//删除已空文件夹
}
}
public void DeletePEmptyFolder(string dir)
{
if (Directory.GetDirectories(dir).Length == 0)
{
string pdir = Directory.GetParent(dir).FullName;
if (Directory.Exists(dir))
Directory.Delete(dir);
DeletePEmptyFolder(pdir);
}
}
根据指定的文件夹路径如E:\\a\\b\\d
向下遍历删除其下的子文件及子目录
删除其本身
向上遍历删除其空的父目录
using System.IO;
protected void Button1_Click(object sender, EventArgs e)
{
string dir = "E:\\a\\b\\d";
//string dir = "E:\\a";
string pdir = Directory.GetParent(dir).FullName;
DeleteFolder(dir);
DeletePEmptyFolder(pdir);
}
public void DeleteFolder(string dir)
{
if (Directory.Exists(dir))
{
foreach (string d in Directory.GetFileSystemEntries(dir))
{
if (File.Exists(d))
{
FileInfo fi = new FileInfo(d);
if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
fi.Attributes = FileAttributes.Normal;
File.Delete(d);//直接删除其中的文件
}
else
DeleteFolder(d);//递归删除子文件夹
}
Directory.Delete(dir);//删除已空文件夹
}
}
public void DeletePEmptyFolder(string dir)
{
if (Directory.GetDirectories(dir).Length == 0)
{
string pdir = Directory.GetParent(dir).FullName;
if (Directory.Exists(dir))
Directory.Delete(dir);
DeletePEmptyFolder(pdir);
}
}
相关文章推荐
- C# 向下遍历删除子目录和子文件 及 向上遍历空的父目录
- C# 向下遍历删除子目录和子文件 及 向上遍历空的父目录
- C# 非递归遍历所有子目录与子文件
- C#删除整个目录及子目录的方法
- C# 趣味小程序(4)——遍历特定目录及其子目录
- bat 遍历某个目录删除子目录下的所有日志文件
- 续:C# 趣味小程序(4)——遍历特定目录及其子目录 (应用实例,压缩指定目录下的所有文件)
- c#里有遍历目录及子目录以树的形式展现
- C# 遍历读取某个目录文件夹下的不同类型子文件和其子文件夹(里面可能又有许多文件)
- C# 趣味小程序(4)——遍历特定目录及其子目录
- C#.NET中遍历指定目录下的文件(及所有子目录及子目录里更深层目录里的文件)
- C# winfrom遍历指定目录下的所有文件,并删除指定文件
- C#遍历某目录及其子目录下所有文件的一个例子
- C#.NET中遍历指定目录下的文件(及所有子目录及子目录里更深层目录里的文件)
- 遍历指定目录下所有子目录和子文件的函数
- 遍历目录,并删除里面的子目录
- C# 删除、遍历指定目录下的所有指定文件、文件夹
- C#FTP操作类含下载上传删除获取目录文件及子目录列表等等
- C#遍历目录下的所有子目录和文件
- Android遍历特定目录下所有文件,包含子目录的, 并删除最新创建的