简体   繁体   中英

C# Deleting Directories

I'm working with the .NET Compact Framework 3.5 and want to delete some specific folders and their subfolders. When I run the app it gives IO exception . I've tried to use Directory.Delete(path) method but it didn't work.

How can I solve this problem?

Here is my code :

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Reset_Client
{
  static class Program
  {
      static void Main(){
         myfunc();
         MessageBox.Show("Cihaz resetlendi!");
      }

      public static void myfunc()
      {
          string mainPath = @"\Storage Card\deneme";

          try
          {
              DeleteDirectory(mainPath + "CRM");
              DeleteDirectory(mainPath + "BHTS");
              DeleteDirectory(mainPath + "IMAGES");
              DeleteDirectory(mainPath + "STYLES");
              DeleteDirectory(mainPath + "TABLES");
              DeleteDirectory(mainPath + "LOG");

              File.Delete(mainPath + "Agentry.ini");
              File.Delete(mainPath + "Agentry.app");
              File.Delete(mainPath + "Agentry.usr");
          }
          catch (IOException e)
          {
              myfunc();
          }
      }

      public static void DeleteDirectory(string target_dir)
      {
          FileInfo fileInfo = new FileInfo(target_dir);
          FileAttributes attributes = fileInfo.Attributes;

          if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
          {
              // set the attributes to nonreadonly
              fileInfo.Attributes &= ~FileAttributes.ReadOnly;
          }

          string[] files = Directory.GetFiles(target_dir);
          string[] dirs = Directory.GetDirectories(target_dir);

          foreach (string file in files)
          {
              File.Delete(file);
          }

          foreach (string dir in dirs)
          {
              DeleteDirectory(dir);
          }

          Directory.Delete(target_dir, false);
      }
   }
}

Why not delete the directory recursively:

Directory.Delete(path, true);

See here .

Also, see here as it may be similar to what you are encountering.

Try this..

var dir = new DirectoryInfo(@FolderPath);
dir.Delete(true);

您没有告诉您正在获得哪种IO异常,您是否在路径中缺少反斜杠()?

mainPath + "CRM" becomes "\Storage Card\denemeCRM" and not "\Storage Card\deneme\CRM"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM