我有一个文件夹,其中包含子文件夹和具有只读属性(文件和文件夹)的文件。我想删除包含子文件夹和文件的文件夹。
我写了这段代码:
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'的一部分。
这个错误是什么意思?
答案 0 :(得分:12)
Directory.Delete(path, true);
答案 1 :(得分:0)
上一个答案可能有效,但我相信它会在ReadOnly文件中出现问题。但是为了确保删除和删除任何属性ReadOnly,执行此过程的最佳方法是必须使用方法来促进您的工作方式,而不是使用对象的正确属性,例如,使用时
DirectoryInfo.ToString()
并使用
DirectoryInfo.GetFiles(aa ...
您没有使用Framework在DirectoryInfo类中提供的资源。见下文:
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();
}
答案 2 :(得分:0)
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);
}
}