Hey;

I am developing a console game in C#. I wanted to create a file called "accounts.bin" to hold players accounts information.

So when I try to create or access the file the program halts and throws an exception called "UnauthroizedAccessException". I tried to put the file into the "C:\" directory, then "C:\ProgramFiles(x86)\" directory but nothing changed.

Here below is my AccountsFile class, I just implemented the constructors. How can I grant the application with the needed authorization ? Is there anything wrong with the code, because this is the first time I am working with File IO.

public class AccountsFile
{
#region Fields
string _fileName;
int _numberOfAccounts;

#endregion

#region Properties
public string FileName { get; set; }
public int NumberOfAccounts { get; set; }
public DateTime LastModifiedDate { get; set; }

#endregion

#region Constructors
public AccountsFile()
{
NumberOfAccounts = 0;
BinaryWriter file = new BinaryWriter(File.Create(FileName));
file.Write(NumberOfAccounts);
}

public AccountsFile(string iFileName)
{
FileName = iFileName;
try
{
}
catch (Exception ex)
{
BinaryWriter file = new BinaryWriter(File.Create(FileName));
file.Write(0);
}
}
#endregion
}
2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Momerath

Okay, I placed the file to the desktop. That solved my problem.

Just FYI, in Windows Vista/7 it is no longer recommended that files be placed in the directory with the executable (this is a safety feature to prevent malicious code from overwriting your exe files). The proper place is in the Users directory. Either //Users/Public or //Users/<username> depending on if the file is shared among all users or is specific to the particular user.