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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With