How to write to a file in .NET Core?
This code is the skeleton I was looking for when I posed the question. It uses only facilities available in .NET Core.
var watcher = new BluetoothLEAdvertisementWatcher();
var logPath = System.IO.Path.GetTempFileName();
var logFile = System.IO.File.Create(logPath);
var logWriter = new System.IO.StreamWriter(logFile);
logWriter.WriteLine("Log message");
logWriter.Dispose();
Even better:
using System.IO;
var logPath = Path.GetTempFileName();
using (var writer = File.CreateText(logPath)) // or File.AppendText
{
writer.WriteLine("log message"); //or .Write(), if you wish
}
If writing fewer lines of code is your thing, the above can be re-written as
using (var writer = System.IO.File.CreateText(System.IO.Path.GetTempFileName()))
{
writer.WriteLine("log message"); //or .Write(), if you wish
}
This is the solution I'm using. It uses fewer lines of code and does the job just as good. It's also very compatible with .NET core 2.0
using (StreamWriter writer = System.IO.File.AppendText("logfile.txt"))
{
writer.WriteLine("log message");
}