Reputation: 21
I'm trying to create a basic logging system to log each call of a class into a file named log.csv
. I have a string called logPath
which contains ..\\..\\log.csv
and another string called logData
which holds the information that I want to write to the log file.
The code I have so far:
if (!File.Exists(logPath))
{
File.Create(logPath);
StreamWriter writeLog = new StreamWriter(logPath, true);
writeLog.WriteLine(logData);
writeLog.Close();
}
else if (File.Exists(logPath))
{
StreamWriter writeLog = new StreamWriter(logPath, true);
writeLog.WriteLine(logData);
writeLog.Close();
}
However, when I run the code and the log file doesn't exist, the program crashes but still creates the file log.csv
, however the data in logData
isn't written to the file. When I run the program again, because the file exists it has no problem writing each call of the class. When the program crashes at file creation it throws an IOException
, claiming that the file is being used by another process.
Upvotes: 1
Views: 77
Reputation: 6882
Remove the following line (this creates the file and keeps it open, and the next line you are trying to create it again and crashes cuz it has been created and the file is still open):
File.Create(logPath);
That's why you received the message indicating the fact that the file is in use by another process, when in fact it your own process caused by File.Create
Intact all you need is to replace your entire code with the following (it creates the file if it doesn't exist)
using(var writeLog = new StreamWriter(logPath, true))
{
WriteLog.WriteLine(logData);
writeLog.Close();
}
Upvotes: 2
Reputation: 6957
Since you are appending and the StreamWriter already creates the file if it doesn't exist you can simplify your code as below:
using (StreamWriter writeLog = new StreamWriter(logPath, true))
{
writeLog.WriteLine(logData);
writeLog.Close();
}
Upvotes: 1