Unable to write AppedText in file

Viewed 169

I need create a file and need to write the every exception in a file. i am using bellow code to do that.

File.Create(filePath);
File.AppendText("Exception Detail Start-------------------------------------------");
File.AppendText("Stack Trace :" + ex.StackTrace );
File.AppendText("Error :" + ex.Message );
File.AppendText("Exception Detail End-------------------------------------------");

But I'm getting the below error:

Additional information: Access to the path 'C:\Program Files (x86)\IIS Express\Exception Detail Start-------------------------------------------' is denied`
3 Answers

File.AppendText takes a file path and returns a StreamWriter. So in your case you are passing the exception message as the file path, and hence the file is not found (it is looking file a file in the current directory named "Exception Detail Start-------------------------------------------").

In your case you might want to use File.AppendAllText.

Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.

Or File.AppendAllLines.

Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.

Example:

File.AppendAllLines(filePath, new string[] { 
    "Exception Detail Start-------------------------------------------",
    "Stack Trace :" + ex.StackTrace, 
    "Error :" + ex.Message, 
    "Exception Detail End-------------------------------------------" 
});

You don't write to the file you created.

FileStream writer = File.Create(filePath);
writer.AppendText("Exception Detail Start-------------------------------------------");
writer.AppendText("Stack Trace :" + ex.StackTrace );
writer.AppendText("Error :" + ex.Message );
writer.AppendText("Exception Detail End-------------------------------------------");

This should work.

Your C\program files (x86) path usually requires administrative right to write files. Try starting your application as administrator. (Alternatively start visual studio as administrator and run your project)

If it successfully writes to the file when run as administrator maybe consider choosing a folder that requires no administrative priviledges or add priviledges to a chosen folder for your program.

Related