THs
THs

Reputation: 19

System.UnauthorizedAccessException: Cant seem to fic it

I keep getting this error. Can somebody help pls? im trying to create a new file, but it says i dont have acces to the path

this is the part that gets the error

        String Newfilepath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
        string Newfilepath2 = Newfilepath + @"\Apple";



        using (StreamWriter sw = File.CreateText(Newfilepath2));

Upvotes: 0

Views: 54

Answers (2)

TheGeneral
TheGeneral

Reputation: 81543

Its always best to consult the documentation when you get an exception they usually explicitly tell you what to expect

FileInfo.CreateText Method

Creates a StreamWriter that writes a new text file.

Exceptions

  • UnauthorizedAccessException The file name is a directory.

  • IOException The disk is read-only.

  • SecurityException The caller does not have the required permission.

If that doesn't shed any light on the situation. Have a look at your path is that the file name you want?

I assume you want something liek this

String Newfilepath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string Newfilepath2 = Newfilepath + @"\Apple.txt";

or

string Newfilepath2 = Newfilepath + @"\Apple\somefile.txt";

Upvotes: 2

Ahmed Aljaff
Ahmed Aljaff

Reputation: 189

System.UnauthorizedAccessException means:

your application or idea does not have write permissions for the specific folder, and this is a normal behavior for windows special folders.

Try different folder like User Documents or
Run Visual Studio as Administrator

Upvotes: 0

Related Questions