1

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)

rth
  • 10,680
  • 7
  • 53
  • 77
user2550641
  • 317
  • 4
  • 18
  • 1
    Can you provide a short but complete example demonstrating the problem? I strongly suspect the problem is that you're overwriting an existing (longer) file, and that you just need to change `FileMode.OpenOrCreate` to `FileMode.Truncate` or just call `File.CreateText` instead. – Jon Skeet Jul 10 '15 at 09:14
  • `FileMode.Truncate` did the job. I wonder why, because I also tried removing all files manually before and checked, that every file is opened only once but it works, so thank you very much :-) – user2550641 Jul 10 '15 at 09:24
  • @Jon Skeet, really helpful. Thank you. – Elvis Jul 02 '16 at 21:21

1 Answers1

1

You Open or Create the file, while it looks like you expect to start with a blank file each time. The text you are referring to can be left over from previous run. look at this question about how to start with an empty file

Remove all previous text before writing

Community
  • 1
  • 1
n00b
  • 1,832
  • 14
  • 25