I've read a lot about using the Streamwriter. At least I have a solution that nearly works - but in some files, the last line is appended twice. I tried inserting Flush() at the end of writing and even after every if statement, but the behaviour stays the same. Maybe someone knows an answer and can help me?
Use case: I extract information out of another file and save them in an object (all information are stored correctly - I tested this). After that I call the method to write the information stored in the object in a file:
for (int i = 0; i < allCMs.Count; i++)
{
using (var stream = File.Open(allCMs[i].dir,
FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(version);
writer.WriteLine();
if (allCMs[i].name != null)
{
writer.WriteLine(addProject(allCMs[i].name));
writer.WriteLine();
writer.Flush();
}
if (allCMs[i].header != null)
{
writer.WriteLine(addHeader(allCMs[i].header));
writer.WriteLine();
writer.Flush();
}
if (allCMs[i].src != null)
{
writer.WriteLine(addSrc(allCMs[i].src));
writer.WriteLine();
writer.Flush();
}
}
}
}
The output in the txt is like the following:
project: projectname
header: header
src: source
src: source
or sometimes like this:
project: projectname
header: header
src: source
: source
(I simplified the files for understanding)