UnauthorizedAccessException “Access to the path is denied” from File.ReadAllBytes in LOCALAPPDATA

点点圈 提交于 2019-12-05 06:16:00

The question is too broad, but I want to point out that there are other reasons for access denied exception besides you listed. For example, consider this simple program:

public class Program {
    static string _target = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "test", "test.txt");
    static void Main(string[] args) {
        File.Create(_target).Dispose();
        ProcessFile();

        // below throws access denied
        if (File.Exists(_target))
            Console.WriteLine(File.ReadAllText(_target));
        Console.ReadKey();
    }

    static void ProcessFile() {
        // open and abandon handle
        var fs = new FileStream(_target, FileMode.Open, FileAccess.Read, FileShare.Delete);
        // delete
        File.Delete(_target);
    }        
}  

Here we create new file under %LOCALAPPDATA%, and open it with FileShare.Delete, but not closing. FileShare.Delete allows subsequent deletion of the file, but file will not be actually deleted until all handles to it are closed.

Then we proceed with File.Delete, which does not actually delete file but marks it for deletion, because we still have open file handle to it.

Now, File.Exists returns true for such file, but trying to access it throws "Access denied" exception as you described.

Whether this specific situation is relevant to your case is hard to tell, but it might be.

My point mainly is: you should expect such exceptions (and also "file already in use" kind of exceptions) and handle them by retrying. They can happen for various reasons outside of your control.

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