0

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);
    }
}
1
  • 2
    Try not writing to the root !! Commented Apr 8, 2018 at 17:08

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried to create in other folder . It worked . thank
-1

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 ??

2 Comments

I add it in manifest but doesn't worked . I am learning c#.net so i am beginner at it and i don't know a lot of code in dot net
I wish i could invite you on skype but i don't know if it is the right thing to do .... Also i cannot explain it all here as it may become huge..However, you cannot even reply to SO chat because you have vere few reputation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.