Reputation: 572
I have a method which saves the object into the file. The object gets modified and saved multiple times. The problem is that when I'm trying to save object for the second time into the same file, I'm getting the UnautorizedAccessException. Here is the code:
public void Save(string path)
{
string fileName = String.Format("{0}\\{1}", path, DataFileName);
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, this);
File.SetAttributes(fileName, FileAttributes.Hidden);
}
}
What's the most interesting, is that if I comment the line
File.SetAttributes(fileName, FileAttributes.Hidden);
problem disappears. How comes? And how can I solve this problem?
Upvotes: 2
Views: 272
Reputation: 63966
MSDN says this about FileMode.Create
:
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess.Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.
Which is exactly what you are seeing. So the solution seems to be either use a different mode, or as suggested in the comments, unhide -> save -> hide.
Upvotes: 4