private void DeleteDirByName(string rootPath, string name)
{
string dirName = rootPath;
if(rootPath.EndsWith("//")||rootPath.EndsWith("/"))
{
rootPath = rootPath.Substring(0,rootPath.Length-1);
}
int indexSplit = rootPath.LastIndexOf('//');
if(indexSplit<0)
{
indexSplit = rootPath.LastIndexOf('/');
}
if(indexSplit>0)
{
dirName = rootPath.Substring(indexSplit + 1);
}
if (dirName.ToLower() == name.ToLower())
{
this.SetFileAttributes(rootPath);
Directory.Delete(rootPath, true);
this.textBox3.Text += rootPath + Environment.NewLine;
}
else
{
string[] subDirs = Directory.GetDirectories(rootPath);
foreach (string subDir in subDirs)
{
this.DeleteDirByName(subDir, name);
}
}
}
private void SetFileAttributes(string path)
{
string[] files = Directory.GetFiles(path);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
}
string[] subDirs = Directory.GetDirectories(path);
foreach (string subDir in subDirs)
{
this.SetFileAttributes(subDir);
}
}
递归删除指定名称文件夹
本文介绍了一个用于递归删除特定名称文件夹及其内容的C#方法。该方法首先检查当前目录是否匹配指定名称,如果匹配则进行删除操作;如果不匹配,则继续搜索子目录并递归调用自身。此外,还提供了一个辅助方法用于设置文件属性为正常,以便能够成功删除。
5794

被折叠的 条评论
为什么被折叠?



