R. Matveev R. Matveev - 28 days ago 14
C# Question

Create or Open file and then Append data to it

We can use such code to open or create file and then write some data into it (all contents will be replaced).

using (var file = File.Open(path, FileMode.OpenOrCreate))
using (var stream = new StreamWriter(file))
stream.WriteLine(_message);


Or we can use following code to add data at the end of the file, assuming that the file is exist.

using (var file = File.Open(path, FileMode.Append))
using (var stream = new StreamWriter(file))
stream.WriteLine(_message);


Is there any way to combine these 3 things: ((Create || Open) & Append) to the file?

Answer

You can create your own FileStream factory or you could do it on one line like so.

using (var file = File.Exists(path) ? File.Open(path, FileMode.Append) : File.Open(path, FileMode.CreateNew))
using (var stream = new StreamWriter(file))
    stream.WriteLine(_message);