Reputation: 75
I tried to create a file with File.Create
but I get an error. I can't fix that. I searched for this problem and found this code and I copied it to Visual Studio but it still has this error :
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
Additional information: Access to the path 'C:\aaa.txt' is denied.
My code:
string path = "C:\\aaa.txt";
if (File.Exists(path))
{
Console.WriteLine("file exist");
}
else
{
using (FileStream fs = File.Create(path))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
fs.Write(info, 0, info.Length);
}
}
Upvotes: 0
Views: 1655
Reputation: 21711
Stop trying to create files at the root of drive C:; standard users are forbidden from that, and it's a bad idea even for administrators. If this is a user's file put it in the user's folder:
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "aaa.txt");
If it's not a user file look through the Environment.SpecialFolder
values to find the folder to put it in.
Upvotes: 3
Reputation: 5738
I hope you understand the error but in simple words it means that you don't have the permission to modify/write to the path.
So,why not just run your app as administrator ?..
Create an application manifest file(Right click project > Add > New Item > Application Manifest file) and add this :
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
One last thing, if you really want to create a simple text file,why not just use one line code such as File.WriteAllTexr
??
Upvotes: -1