Reputation: 1633
I'm trying to create a new folder in my documents and add an error log text file to it however I get an UnauthrizedAccessException
. How can I give access to create this folder and write to it?
My code is as follows for creating my error log
string currentContent = String.Empty;
string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
message += "-----------------------------------------------------------";
message += Environment.NewLine;
message += string.Format($"Message: {errorText} {ex.Message}");
message += Environment.NewLine;
message += string.Format($"On Line: {currentLine} Test name {methodName}");
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\ErrorLog\ErrorLogAutomatedTesting.txt";
if (File.Exists(filePath))
{
currentContent = File.ReadAllText(filePath);
}
else
System.IO.Directory.CreateDirectory(filePath);
Thread.Sleep(2000);
File.WriteAllText(filePath, message + currentContent);
Upvotes: 0
Views: 38
Reputation: 11533
You are creating a directory with the filename ErrorLogAutomatedTesting.txt
. So it won't be a file, rather a directory. This is because the filePath
variable contains the name of the file too. So try without it:
var dir = System.IO.Path.GetDirectoryName(filePath);
System.IO.Directory.CreateDirectory(dir);
Upvotes: 1