I have a website which reads settings from an xml config file (I’m using a .config extension). I open the file like so:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (Stream fs = new FileStream(filename, FileMode.Open))
{
configSettings = xmlSerializer.Deserialize(fs) as MyConfigSettings;
}
I only need read access to the file, but for some reason I’m getting a System.UnauthorizedAccessException unless I give write permissions on the file. This is something I don’t wan’t to do, and it’s only required for the code to read the file.
Why does this happen, and what should I change to stop this happening?
The FileStream constructor you are using opens the file with both read and write permissions. See the Remarks section of the documentation:
You need to use the three argument constructor with FileAccess.Read as the third argument.
Like this: