When trying to read some user settings from C:\ProgramData in my .NET app, I was getting an Access Denied exception, even though I was only attempting to read the configuration file, not write anything:
System.UnauthorizedAccessException: Access to the path ‘C:\ProgramData\YourApp\1.0.0.0\settings.xml’ is denied.
Even though I was only reading the file, and not writing anything, it still wanted elevation before it let me read it. It turns out that I need to signify my intent not to write anything when I open the stream. This code generated the exception (the “Using” statement actually threw the exception):
Using f As New FileStream(MySettingsFilePath, FileMode.Open) Dim formatter As New Formatters.Binary.BinaryFormatter MySettings = formatter.Deserialize(f) f.Close() End Using
However, by changing the “FileStream” to a “StreamReader”, I signify my intent to read and not write, so the code runs without an issue (there are two changes):
Using f As New StreamReader(MySettingsFilePath) Dim formatter As New Formatters.Binary.BinaryFormatter MySettings = formatter.Deserialize(f.BaseStream) f.Close() End Using