Documentation says FileMode.OpenOrCreate
"specifies that the operating system should open a file if it exists; otherwise, a new file should be created", which sounds like it will open the file and write to it. Instead, the file seems to be overwritten.
How do I add to the file, rather than overwrite it?
class Logger : IDisposable
{
private FileStream fs;
private StreamWriter sw;
public Logger()
{
// INTENT (but not reality): Will create file if one does not exist, otherwise opens existing file to append text
fs = new FileStream("log.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
sw = new StreamWriter(fs, Encoding.UTF8);
}
public void Log(string message)
{
sw.WriteLine(message);
sw.Flush();
fs.Flush();
}
public void Dispose()
{
sw?.Dispose();
fs?.Dispose();
}
}
FileMode.OpenOrCreate
might be thought to overwrite a file. (afterallFileMode.Create
will). so I'm removing my comment above regarding duplication (links are probably still associate to this question though) – Calc