0

I copied some directories/files with a procedure on C#. Now, I'd like to remove the main directory.

So this is the basic code:

dir.Delete(true);

but I reckon a UnauthorizedAccessException (access to directories.acrodata, which is a file, denied).

Why? How can I force it?

markzzz
  • 45,272
  • 113
  • 282
  • 475

5 Answers5

6

You probably either 1) limited security privileges there and are unable to delete a file or 2) have a handle to a file or directory still open (in use) which is preventing you from deleting.

Directory.Delete(string);

http://msdn.microsoft.com/en-us/library/62t64db3.aspx

UnauthorizedAccessException

The caller does not have the required permission.

bland
  • 1,948
  • 1
  • 15
  • 22
  • Depends on how you copied. For instance, always put your streams in a Using so that they automatically close and dispose afterwards: using (FileStream fs = new FileStream(@"C:\temp\test.txt", FileMode.OpenOrCreate)) { /* ... */ } – bland Apr 19 '13 at 14:27
  • Also, as Pavel Vladov and smhnkmr noted careful of ReadOnly attributes. – bland Apr 19 '13 at 14:30
1

First you should dispose any handles you have to a file from the ones you want to delete. Then you can use the following code to ensure that read only files get deleted, too:

public static void DeleteDirectory(string target_dir)
{
    string[] files = Directory.GetFiles(target_dir);
    string[] dirs = Directory.GetDirectories(target_dir);

    foreach (string file in files)
    {
        File.SetAttributes(file, FileAttributes.Normal);
        File.Delete(file);
    }

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

    Directory.Delete(target_dir, false);
}

Source and more info in this Stackoverflow topic.

Community
  • 1
  • 1
Pavel Vladov
  • 4,407
  • 2
  • 32
  • 39
  • Well, I have an empty folder, which is read-only. How can I remove that attributes from a directory? – markzzz Apr 20 '13 at 10:55
  • Try using the Attributes property of the DirectoryInfo class, for example: `DirectoryInfo di = new DirectoryInfo(dirName); di.Attributes = FileAttributes.Normal;` – Pavel Vladov Apr 21 '13 at 07:18
0

The Directory you are trying to delete may be ReadOnly. So setting the ReadOnly attribute to false and deleting the same would work.

e.g:

var di = new DirectoryInfo("SomeFolder");
di.Attributes &= ~FileAttributes.ReadOnly;
Mohan
  • 5,860
  • 6
  • 27
  • 34
0

I guessing that after your copy operation, you failed to properly close Streams meaning that you're still holding a handle to the file as described by @bland.

Make sure that you dispose your IDisposable's in a timely fashion and this problem may well go away.

spender
  • 112,247
  • 30
  • 221
  • 334
0

Have you tried just using

Directory.Delete(folderName, true);

that should recursively delete?

Flair
  • 2,123
  • 1
  • 24
  • 39
greenshell
  • 21
  • 4