如何删除文件、主文件夹和子文件夹

4

我在删除目录中的文件、主文件夹和子文件夹时遇到了问题。我希望在工作完成后删除所有文件、主文件夹和子文件夹。我正在使用以下代码:

        private void bgAtoZ_DoWork(object sender, DoWorkEventArgs e)
        {
           string Path1 = (string)(Application.StartupPath + "\\TEMP\\a-z\\test" + "\\" +name);
           StreamReader reader1 = File.OpenText(Path1);
           string str = reader1.ReadToEnd();
           reader1.Close();
           reader1.Dispose();
           File.Delete(Path1);
         }

如果有人可以帮助我,那对我来说会很好。提前感谢。

2
我遇到了一个问题 - 那是什么问题? - Mitch Wheat
你在这段代码中遇到了什么错误吗? - Sai Kalyan Kumar Akshinthala
不,它只删除文件夹中的文件,而不是文件夹和子文件夹。 - G Arshiya
你为什么要读取所有的文件? - Emond
写入另一个目录 - G Arshiya
那你为什么不使用Directory.Move()呢?http://msdn.microsoft.com/en-us/library/system.io.directory.move.aspx - Emond
5个回答

12

4
我会选择一个:
Directory.Delete(Path1, true)

这将删除包含文件和文件夹的目录。


3

Directory.Delete(@"c:\test", true); 可以实现此操作


1
 new System.IO.DirectoryInfo("C:\Temp").Delete(true);

 //Or

 System.IO.Directory.Delete("C:\Temp", true);

0
using System.IO; 
private void EmptyFolder(DirectoryInfo directoryInfo)
{
  foreach (FileInfo file in directoryInfo.GetFiles())
  {
    file.Delete();
  }
  foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
  {
    EmptyFolder(subfolder);
  }
}

使用代码:

EmptyFolder(new DirectoryInfo(@"C:\yourPath"))  

摘自这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接