Tuesday, 1 November 2011

Remove directory which contains read-only file in C#.net


using System.IO;

public bool DeleteDirectory(string dirPath)
{
if (Directory.Exists(dirPath))
      {
            try
            {
                ClearAttributes(dirPath);
                Directory.Delete(dirPath, true);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message);
                return false;
            }
}
        return true;
}


public void ClearAttributes(string currentDir)
{
if (Directory.Exists(currentDir))
      {
            string[] subDirs = Directory.GetDirectories(currentDir);
            foreach (string dir in subDirs)
                ClearAttributes(dir);

            string[] files = files = Directory.GetFiles(currentDir);
            foreach (string file in files)
                File.SetAttributes(file, FileAttributes.Normal);
      }
}

No comments:

Post a Comment