Text in file is not appended - C#
I've decided to add a logging mechanism to my application so I can catch any errors or exceptions that are thrown. I've noticed that when an entry to the log is created it is not added to the log, it seems to overwrite everything that is in the file so there is only ever one entry.
I have a feeling it's something simple that I'm missing but I don't really use the System.IO namespace very often.
Creating/Checking for the log file:
public static void SetWorkingDirectory(string path)
{
_workingDirectory = path + "\\ErrorLog.txt";
if(!File.Exists(_workingDirectory))
{
File.Create(_workingDirectory);
}
pathSet = true;
}
Adding to the log:
public static bool Add(string message)
{
StringBuilder str = new StringBuilder();
str.Append(System.DateTime.Now);
开发者_如何学Go str.Append(" ");
str.Append(message);
str.Append(" \n");
using (StreamWriter writer = new StreamWriter(_workingDirectory))
{
writer.Write(str.ToString());
}
return true;
}
The log itself:
Try using this constructor and passing true for the second argument so it opens the file in append mode.
...
using(writer = new StreamWriter(_workingDirectory, true))
...
Just use the overload of StreamWriter that takes a bool to determine if it should append.
using (var writer = new StreamWriter(_workingDirectory, true)
{
...
}
That StreamWriter
constructor you are using, overwrites the file. There is an overload which will append:
using (StreamWriter writer = new StreamWriter(_workingDirectory, true))
It is all in the docs.
Also, unless this for learning, use one of the many available logging frameworks instead. Logging can be hard to get right.
Many programming hours have been spent solving this problem before. I recommend using a logging package such as log4net instead to save yourself time debugging code that is intended to let you instrument the code you are writing.
As driis has stated above, when performing logging its best to use one of the ready made logging frameworks, as without an extreme amount of effort they will be able to do it more efficiently and cleaner than you will. My favourite in .NET is to use the prepackaged System.Diagnostics tracing utilities which allow you to declare a tracelistener(s) in your app config then simply write to them in your code like this:
Trace.Write("Test output ");
Alternatively you could use the log4Net framework.
精彩评论