tags:

views:

123

answers:

2

I had this code

StreamWriter sw = new StreamWriter(this.FileName, true);
sw.WriteLine(text);
sw.Close();

Which I changed to this (because of a contention issue):

StreamWriter sw = new StreamWriter(
          new FileStream(this.FileName, FileMode.OpenOrCreate
               , FileAccess.ReadWrite, FileShare.Write)
          , Encoding.ASCII); 
sw.WriteLine(strLog);
sw.Close();

The issue is that the first one worked fine, outputted proper text that was human readable (this is for a log text file). The second one outputs totally screwy output, regardless of the Encoding type I've used. I've tried ASCII, UTF7, 8, Unicode and Default. So clearly I'm missing something fundamental about FileStream or TextWriter. Please edumacate me.

+3  A: 

I've tried your code without being able to reproduce any weird behavior.

A few thoughts:

  • You do not flush your StreamWriter or your FileStream.
  • You do not call Dispose on your StreamWriter and FileStream. Try wrapping these in using statements.
  • Ascii encoding is evil. I assume this is just a test step.
  • FileMode.OpenOrCreate will ... open or create the file. It will open an already existing file and overwrite the first bytes. Do you want to use FileMode.Create to create a new file, or overwrite an existing?

EDIT:

The solution to the problem was to use FileMode.Append, per comments to this post.

Simon Svensson
Ah hah, thanks! The issue was with the FileMode. Should be FileMode.Append. Please edit your answer to highlight this and I'll mark it as the answer. All the other things you mentioned are important, but the FileMode was the real issue.
jcollum
+1, Good catch, he's wasn't clearing the file, and wasn't flushing. The encoding was a red herring!
Michael Meadows
the StreamWriter was set to AutoFlush, I checked that at the beginning; ASCII encoding was just there because I tried it, I'd tried Default first; I omitted the using statements, but the final code did have that
jcollum
A: 

Just to check the obvious, you have:

sw.WriteLine(text);

in the first example and

sw.WriteLine(strLog);

in the second. Without seeing all your code, I can't know the answer to the following so I feel compelled to ask:

Are test and strLog different things in your source, or is the difference only a typo?

JeffH