C# delete a folder and all files and folders within that folder

断了今生、忘了曾经 提交于 2019-12-18 10:13:19

问题


I'm trying to delete a folder and all files and folders within that folder, I'm using the code below and I get the error Folder is not empty, any suggestions on what I can do?

try
{
  var dir = new DirectoryInfo(@FolderPath);
  dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
  dir.Delete();
  dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i].Index);
}
catch (IOException ex)
{
  MessageBox.Show(ex.Message);
}

回答1:


dir.Delete(true); // true => recursive delete



回答2:


Read the Manual:

Directory.Delete Method (String, Boolean)

Directory.Delete(folderPath, true);



回答3:


Try:

System.IO.Directory.Delete(path,true)

This will recursively delete all files and folders underneath "path" assuming you have the permissions to do so.




回答4:


Err, what about just calling Directory.Delete(path, true); ?




回答5:


The Directory.Delete method has a recursive boolean parameter, it should do what you need




回答6:


You should use:

dir.Delete(true);

for recursively deleting the contents of that folder too. See MSDN DirectoryInfo.Delete() overloads.




回答7:


Try this.

namespace EraseJunkFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\somedirectory\");
            foreach (DirectoryInfo dir in yourRootDir.GetDirectories())
                    DeleteDirectory(dir.FullName, true);
        }
        public static void DeleteDirectory(string directoryName, bool checkDirectiryExist)
        {
            if (Directory.Exists(directoryName))
                Directory.Delete(directoryName, true);
            else if (checkDirectiryExist)
                throw new SystemException("Directory you want to delete is not exist");
        }
    }
}



回答8:


public void Empty(System.IO.DirectoryInfo directory)
{
    try
    {
        logger.DebugFormat("Empty directory {0}", directory.FullName);
        foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete();
        foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
    }
    catch (Exception ex)
    {
        ex.Data.Add("directory", Convert.ToString(directory.FullName, CultureInfo.InvariantCulture));

        throw new Exception(string.Format(CultureInfo.InvariantCulture,"Method:{0}", ex.TargetSite), ex);
    }
}



回答9:


Try This:

foreach (string files in Directory.GetFiles(SourcePath))
{
   FileInfo fileInfo = new FileInfo(files);
   fileInfo.Delete(); //delete the files first. 
}
Directory.Delete(SourcePath);// delete the directory as it is empty now.


来源:https://stackoverflow.com/questions/2222718/c-sharp-delete-a-folder-and-all-files-and-folders-within-that-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!