C# 在c中删除文件夹和子文件夹#
我有一个文件夹,其中包含子文件夹和具有只读属性的文件(文件和文件夹)。我想删除此文件夹及其子文件夹和文件 我写了这段代码:C# 在c中删除文件夹和子文件夹#,c#,C#,我有一个文件夹,其中包含子文件夹和具有只读属性的文件(文件和文件夹)。我想删除此文件夹及其子文件夹和文件 我写了这段代码: static void Main(string[] args) { DirectoryInfo mm = new DirectoryInfo(@"c:\ex"); string aa = Convert.ToString(mm); string[] allFileNames = System.IO.Directory
static void Main(string[] args)
{
DirectoryInfo mm = new DirectoryInfo(@"c:\ex");
string aa = Convert.ToString(mm);
string[] allFileNames =
System.IO.Directory.GetFiles(aa,
"*.*",
System.IO.SearchOption.AllDirectories);
string[] alldirNames =
System.IO.Directory.GetDirectories(aa,
"*",
System.IO.SearchOption.AllDirectories);
foreach (string filename in allFileNames)
{
FileAttributes attr = File.GetAttributes(filename);
File.SetAttributes(filename, attr & ~FileAttributes.ReadOnly);
}
foreach (string dirname in alldirNames)
{
FileAttributes attr = File.GetAttributes(dirname);
File.SetAttributes(dirname, attr & ~FileAttributes.ReadOnly);
Directory.Delete(dirname , true);
}
FileInfo[] list = mm.GetFiles();
foreach (FileInfo k in list)
{
k.Delete();
}
mm.Delete();
Console.ReadKey();
}
现在的问题是,每当我运行程序时,它都会给我以下错误:
找不到路径“c:\ex\xx\bb”的一部分
这个错误意味着什么
Directory.Delete(path, true);
前面的答案可能有效,但我相信在只读文件中会出现问题。但为了确保删除和删除任何只读属性,执行此过程的最佳方法必须是使用一种方法来简化操作,例如,在使用 DirectoryInfo.ToString() 并使用 DirectoryInfo.GetFiles(aa 您没有使用框架在DirectoryInfo类中提供的资源。请参阅以下内容:
为什么要将
DirectoryInfo
转换为字符串?您可以直接使用。这可能意味着您试图删除某个文件或某个文件目录中没有文件的文件。我建议您做几件事。例如..list您应该检查list.Count>0是否也会在mm.Del上引发错误ete..还有谷歌如何使用DirectoryInfo
还有一件更重要的事情,你是否使用了调试器来逐步调试代码..?如果是,请报告哪一行出错..看看这个链接以及如何设置文件属性,我投了赞成票。请不要给新手投反对票。我只能恢复一次。Direcory.Delete(path,true)将出错它的目录。Delete(path,true);这将搜索根目录和我必须使用System.IO.SearchOption.AllDirectories的第一级子文件夹,以包括它现在工作的所有子目录
void DirectoryDelete(string strOriginalPath)
{
DirectoryInfo diOriginalPath = new DirectoryInfo(strOriginalPath);
if (diOriginalPath.Attributes.HasFlag(FileAttributes.ReadOnly))
diOriginalPath.Attributes &= ~FileAttributes.ReadOnly;
string[] lstFileList = Directory.GetFiles(strOriginalPath);
string[] lstdirectoryList = Directory.GetDirectories(strOriginalPath);
if (lstdirectoryList.Length > 0)
{
// foreach on the subdirs to the call method recursively
foreach (string strSubDir in lstdirectoryList)
DirectoryDelete(strSubDir);
}
if (lstFileList.Length > 0)
{
// foreach in FileList to be delete files
foreach (FileInfo fiFileInDir in lstFileList.Select(strArquivo => new FileInfo(strArquivo)))
{
// removes the ReadOnly attribute
if (fiFileInDir.IsReadOnly)
fiFileInDir.Attributes &= ~FileAttributes.ReadOnly;
// Deleting file
fiFileInDir.Delete();
}
}
diOriginalPath.Delete();
}
EmptyFolder(new DirectoryInfo(@"C:\your Path"))
Directory.Delete(@"C:\your Path");
private void EmptyFolder(DirectoryInfo directoryInfo)
{
foreach (FileInfo file in directoryInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
{
EmptyFolder(subfolder);
}
}