First of all you must use a StreamWriter in order to write lines to a text file.
Then you must loop through the ObservableCollection in order to get the items.
Then you must format a string by using the properties of each item.
This could look like this:
using (var sw = new StreamWriter(@"c:\temp\output.txt"))
{
foreach (var timer in timers)
{
await sw.WriteLineAsync($"Start: {timer.Start:dd.MM.yyyy HH:mm:ss}" +
$", Ende: {timer.Ende:dd.MM.yyyy HH:mm:ss}" +
$", Dauer: {timer.Dauer}" +
$", Bemerkung: {timer.Bemerkung}");
}}
}
Maybe you wonder about WriteLineAsync.
This will not block the User Interface while writing the file.
The mixture of String Interpolation and String Concatenation was suggested by Resharper.
It was a one liner before. I did not see it...
In order to get a better source code readability it is a good idea to use a so called StringBuilder.
Another good idea is to refactor the code in order to have a method which cares about writing the files.
You can pass an object that implements IEnumerable.
The ObservableCollection also derives from it.
This will allow you to pass a List as well.
Please have a look at this snippet:
private static void WriteListToFile(IEnumerable<Timer> timers, string path)
{
var sb = new StringBuilder();
var delimiter = " ";
using (var sw = new StreamWriter(path))
{
foreach (var timer in timers)
{
sb.Clear();
sb.Append($"Start: {timer.Start:dd.MM.yyyy HH:mm:ss}");
sb.Append(delimiter);
sb.Append($"Ende: {timer.Ende:dd.MM.yyyy HH:mm:ss}");
sb.Append(delimiter);
sb.Append($"Dauer: {timer.Dauer}");
sb.Append(delimiter);
sb.Append($"Bemerkung: {timer.Bemerkung}");
sw.WriteLine(sb.ToString());
}
}
}
The output in this example would be this:
Start: 25.11.2020 11:02:52, Ende: 25.11.2020 11:02:52, Dauer: 01:00:00, Bemerkung: A
Start: 25.11.2020 11:02:52, Ende: 25.11.2020 11:02:52, Dauer: 02:00:00, Bemerkung: B
Another suggestion: You could rename your Timer class to something more meaningful as it is confusing. There are already at least two other Timer classes in the .Net Framework.
For the sake of completeness here is a way to serialize your list to a JSON File by using Newtonsoft.Json
Json.NET - Newtonsoft[
^]
private static void WriteObjectToJsonFile(object obj, string path)
{
var json = JsonConvert.SerializeObject(obj, Formatting.Indented);
using (var sw = new StreamWriter(path))
{
sw.Write(json);
}
}
As you can see this approach is far more elegant than writing a serializer by yourself.
You can pass any object and it will be written as JSON.
For your class it would look like this:
[
{
"Start": "2020-11-26T09:12:38.0565577+01:00",
"Ende": "2020-11-26T10:12:38.0565577+01:00",
"Dauer": "01:05:22",
"Bemerkung": "A"
},
{
"Start": "2020-11-26T09:12:38.0565577+01:00",
"Ende": "2020-11-26T11:12:38.0565577+01:00",
"Dauer": "01:02:43",
"Bemerkung": "B"
}
]
A JSON file can easily deserialized and thus be understood by your application without the need of complicated parsing.