C#删除目录

时间:2014-01-03 08:33:53

标签: c# .net directory compact-framework

我正在使用.NET Compact Framework 3.5并希望删除一些特定文件夹及其子文件夹。当我运行应用程序时,它会IO exception。我试过使用Directory.Delete(path)方法,但它没有用。

我该如何解决这个问题?

这是我的代码:

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);
      }
   }
}

3 个答案:

答案 0 :(得分:1)

为什么不以递归方式删除目录:

Directory.Delete(path, true);

请参阅here

另请参阅here,因为它可能与您遇到的情况类似。

答案 1 :(得分:0)

试试这个..

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

答案 2 :(得分:0)

你不知道你得到了什么样的IO exception,你错过了你的路径中的反斜杠()吗?

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