I have come across this issue quite a few times and this issue will be seen more often during deployment in QA/Production machine.
Its not unusual to see the below piece of code
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
XmlReader reader = XmlReader.Create(fs);
XmlSerializer serializer = new XmlSerializer(typeof(T));
Object o = serializer.Deserialize(reader);
}
Many times this will go unnoticed but if you look closely FileStream is using a constructor with FilePath and FileMode alone. System.IO.FileStream implementation of this constructor is
public FileStream(string path, FileMode mode) : this(path, mode, (mode == FileMode.Append) ? FileAccess.Write : FileAccess.ReadWrite, FileShare.Read, 0×1000, FileOptions.None, Path.GetFileName(path), false)
{
}
Default constructor asks for ReadWrite access, so now you see why your application is hosed in production, most of the developers use their system as admin user so of course they have the write access to the requested file. This is not to blame developers who run as admin because I can totally understand the pain.
By default, FileStream needs ReadWrite access that’s why System.UnauthorizedAccessException is thrown because on a production machine, User account under which asp.net worker process runs or a windows service or for that matter any process will not have the write access to a file by default.
Make sure, you ask for what you need. If your application needs only Read access to a file, make sure to specify that in your FileStream constructor. Don’t be GREEDY
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
May be I would rather see a Read access by default in System.IO.FileStream implementation rather than ReadWrite.

frankieg says:
thanx dude, you rock
[Reply]
Sai says:
I am getting the error even after I give explicitly FileAccess.Read in the FileStream constructor. Could you throw some more light on this again?
Thanks
[Reply]
prashant Reply:
August 12th, 2009 at 6:38 pm
@Sai, Did you verify the ACL for the account under which your process is running? Most likely the user account trying to access the file doesn’t have access at all.
[Reply]
Michael Mortensen says:
The missing link; thanks mate!
[Reply]
Souvick Mukherjee says:
Thanks… it saved my day.
[Reply]
Souvick Mukherjee says:
Thanks man.. it saved my day.
[Reply]
sc says:
Great ip
[Reply]
Jonny says:
Thanks so much, I was going mad trying to resolve this!
[Reply]