Reputation: 2273
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?
Upvotes: 2
Views: 1857
Reputation: 2273
I resolved the issue using a StreamReader instead:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (StreamReader reader = new StreamReader(filename))
{
configSettings= (MyConfigSettings)xmlSerializer.Deserialize(reader);
}
Upvotes: 2
Reputation: 29914
The FileStream constructor you are using opens the file with both read and write permissions. See the Remarks section of the documentation:
For constructors without a FileAccess parameter, if the mode parameter is set to Append, Write is the default access. Otherwise, the access is set to ReadWrite.
You need to use the three argument constructor with FileAccess.Read as the third argument.
Like this:
using (Stream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
Upvotes: 10