Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random UnauthorizedAccessException while reading a file in %temp%

Tags:

.net

exception

I have a process that writes a file in a temp directory. The file is being written without shared read access, so that if someone attempts to read this file while it is being written, an IOException will be thrown, which is fine.

In some rare cases, I seem to be getting UnauthorizedAccessException while attempting to read this file. I'm fairly certain (from the logs) that the file is not being written to, but I can't see any other reason I wouldn't have access to it.

Also, the process runs from a Visual Studio extension, which means it has the same permissions as the parent process (Visual Studio itself).

Here's how I attempt to open the file:

new FileStream(cacheFileName, FileMode.Open, FileAccess.Read, FileShare.Read);

Sometimes, this line throws an UnauthorizedAccessException. Any ideas why?

like image 885
Igal Tabachnik Avatar asked Oct 22 '22 01:10

Igal Tabachnik


1 Answers

It is definitely not a sharing problem, that generates a sharing violation error and that's reported with a IOException.

There are only two decent explanations for UnauthorizedAccessException. One is the logical one, the file got created with a custom ACL that simply denies access. In which case you'll need to know a lot more about the process that created the file and whack it over the head so it stops doing this. Controlling the user account that's used by that process might be important.

The second explanation is associated with the vagaries of having many processes creating files and directories in the TEMP directory. It is really rather important that files created there are transactional and that you allow the system to generate file names, thus ensuring there's never a name collision. Having a process create a file and allowing another to open it is asking for trouble. You'll get UnauthorizedAccessException when the TEMP directory contains a directory with the same name of the file you are trying to open.

Debugging this problem is tricky if this happens infrequently and the file(s) quickly disappear again. You can enable auditing to log failed attempts at opening the file.

like image 137
Hans Passant Avatar answered Oct 25 '22 18:10

Hans Passant