Access to the path is denied when trying to delete a certain directory [duplicate]

妖精的绣舞 提交于 2020-01-06 01:30:28

问题


The code

Here's a grossly simplified pseudo-code version of some C# code that I'm debugging.

// 1) Lots of files and directories are copied

// 2) Some unnecessary files are deleted

// 3) Try to delete an unnecessary directory
string stubbornFolder = @"C:\...\Stubborn"; // This folder was created during step 1 above.
Directory.Delete(stubbornFolder);

The problem

When it hits Directory.Delete, the following exception is thrown.

System.IO.IOException: Access to the path 'C:\...\Stubborn' is denied.

Notes

  • Deleting the directory "C:...\test" also works as expected. test and Stubborn both appear to have the same security settings. Both directories are completely empty.

  • If I manually delete then re-create Stubborn using Windows Explorer (and skip over the copying code using a debugger), the deletion works as expected.

    • Manual deletion works even when done while the application is running.
  • Peeking at the access control types like suggested in this question seemed to indicate that all rules were set to Allow.

  • The unnecessary file deletion works as expected.

  • Running the executable as an admin vs. not as an admin doesn't make any difference.

  • There doesn't appear to be any applications that are using Stubborn as their working directory.

Help!

Any ideas on what might be causing this?


回答1:


There may be some sort of attribute preventing you from deleting the folder. You might try setting the attributes to normal first:

System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(@"C:\...\Stubborn");
setAttributesNormal(directory);



void setAttributesNormal(System.IO.DirectoryInfo directory){
    foreach (string subDirectoryPath in directory.GetDirectories()){
        var directoryInfo = new DirectoryInfo(subDirectoryPath);
        foreach (string filePath in directoryInfo.GetFiles()) {
            var file = new FileInfo(filePath);
            file.Attributes = FileAttributes.Normal;
        }
    }
}


来源:https://stackoverflow.com/questions/34549319/access-to-the-path-is-denied-when-trying-to-delete-a-certain-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!