C#删除目录 [英] C# Deleting Directories

查看:130
本文介绍了C#删除目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.NET Compact Framework 3.5,并希望删除一些特定的文件夹及其子文件夹。当我运行应用程序时,它会提供 IO异常 。我试图使用 Directory.Delete(路径) 方法,但它没有工作。

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.

我如何解决这个问题?

这是我的代码:

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

请参阅 here

另外,请参阅 here ,因为它可能与您遇到的相似。

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

这篇关于C#删除目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆