I’ve written the following code:
public static class PLog
{
private static FileStream logFileStream;
private static string logFilePath;
public static void Initialize()
{
logFilePath = PSettings.IO.dirLogs + "log_" + DateTime.Now.ToString("ddMMyy_HHmmss") + ".txt";
if (!Directory.Exists(PSettings.IO.dirLogs)) Directory.CreateDirectory(PSettings.IO.dirLogs);
logFileStream = new FileStream(logFilePath, FileMode.Create);
}
public static void WriteLine(string text)
{
byte[] textArray = Encoding.ASCII.GetBytes("[" + DateTime.Now.ToString("dd.MM.yyyy - HH:mm:ss") + "] " + text + "\n");
logFileStream.Write(textArray, 0, textArray.Length);
}
public static void Close()
{
logFileStream.Close();
}
}
But when I call it like this, it doesn’t write anything to the file:
PLog.Initialize();
PLog.WriteLine("test");
PLog.Close();
The file was created but it had the size of 0 bytes.
FileStreamimplementsIDisposable.It is rarely a good idea to use it in a static context like you show in your code because it is hard to really ensure that IDisposable.Dispose() gets called to properly clean up the stream.
If you can, use
FileStreamwith the using keyword to ensure thatDispose()is calledIf you must keep your current structure, check that
Close()really is called (and you’re not e.g. getting an Exception that prevents it from being called).UPDATE
Regarding your comment to the other answer:
Append
Environment.Newlineto the end of your string before you write it out.Alternatively, you can use a StreamWriter, which exposes a
WriteLine()method.