serkan_demir
serkan_demir

Reputation: 11

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

Upvotes: 0

Views: 614

Answers (3)

artokai
artokai

Reputation: 405

You are not telling what kind of IO exception you are getting, Are you missing a backslash () in your path?

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

Upvotes: 0

acarlon
acarlon

Reputation: 17274

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.

Upvotes: 1

Sunny
Sunny

Reputation: 219

Try this..

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

Upvotes: 0

Related Questions