FoldFence
FoldFence

Reputation: 2802

Streamwriter writes different then Console.WriteLine()

I have a streamwriter who writes the data from a process stream in to a log file. When I show the output with Console.WriteLine() the Result looks like:

SW DATA = Sep 23, 2016 9:40:37 AM hudson.remoting.jnlp.Main$CuiListener status
SW DATA = INFO: Trying protocol: JNLP3-connect
SW DATA = Sep 23, 2016 9:40:38 AM hudson.remoting.jnlp.Main$CuiListener status
SW DATA = INFO: Server didn't accept the handshake: Unknown protocol:Protocol:JNLP3-connect
SW DATA = Sep 23, 2016 9:40:38 AM hudson.remoting.jnlp.Main$CuiListener status
SW DATA = INFO: Connecting to Machine:51136
SW DATA = Sep 23, 2016 9:40:38 AM hudson.remoting.jnlp.Main$CuiListener status
SW DATA = INFO: Trying protocol: JNLP2-connect
SW DATA = Sep 23, 2016 9:40:38 AM hudson.remoting.jnlp.Main$CuiListener status
SW DATA = INFO: Connected

But when I open the Textfile, it looks like:

INFO: Connected
:38 AM hudson.remoting.jnlp.Main$CuiListener status
LP3-connect
6231dd with ID 
ad is recommended.

My Code is:

    static void ShowOutput(string data)
    {
        if (data != null)
        {
            FileStream fileStream = new FileStream(@"c:\temp\LogFile.txt", FileMode.OpenOrCreate, FileAccess.Write);
            Console.WriteLine("SW DATA = " + data);
            using (StreamWriter w = new StreamWriter(fileStream))
            {
                w.WriteLine(data);
                w.Flush();
            }
            fileStream.Close();
        }
    }

It looks like the writer only writes the end of every Line.

The Data Comes from a console process similar to this:

http://www.codeproject.com/Articles/4665/Launching-a-process-and-displaying-its-standard-ou

My Question is:

How can I prevent this ?

Upvotes: 1

Views: 1012

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292405

It looks like the writer only writes the end of every Line.

This is because you re-open the file every time, overwriting the previous content. You either need to keep the file open between calls to ShowOutput, or open it in Append mode.

The mixed-up content in the file is because it only overwrites the beginning of the file (doesn't truncate it), so if you write a log entry shorter than the previous ones, the end of the the previous text remains.

Upvotes: 4

Related Questions