tags:

views:

78

answers:

5

We are having an issue with one server and it's utilization of the StreamWriter class. Has anyone experienced something similar to the issue below? If so, what was the solution to fix the issue?

  using( StreamWriter logWriter = File.CreateText( logFileName ) )
  {
    for (int i = 0; i < 500; i++)
      logWriter.WriteLine( "Process completed successfully." );
  } 

When writing out the file the following output is generated:

  Process completed successfully.
  ...  (497 more lines)
  Process completed successfully.
  Process completed s

Tried adding logWriter.Flush() before close without any help. The more lines of text I write out the more data loss occurs.

A: 

Can you try

logWriter.WriteLine( i + ".  Process completed successfully." );

To see where it is failing?

Vivek
From the question, it is failing on the last line.
adrianbanks
"The more lines of text I write out the more data loss occurs" => Does not mean it is the last line
Vivek
A: 

Is this happening in the secondary thread that gets killed cause program is finished?

Grozz
A: 

Cannot reproduce this.

Under normal conditions, this should not and will not fail.

  • Is this the actual code that fails ? The text "Process completed" suggests it's an extract.
  • Any threading involved?
  • Network drive or local?
  • etc.
Henk Holterman
After a lot of digging by several of us, we have come to the conclusion that this truncation is being caused by enabling compression on dynamic content for the web site. We have been able to recreate the truncation issue locally and it disappeared when we disabled compression.
Rob Packwood
A: 

This certainly appears to be a "flushing" problem to me, even though you say you added a call to Flush(). The problem may be that your StreamWriter is just a wrapper for an underlying FileStream object.

I don't typically use the File.CreateText method to create a stream for writing to a file; I usually create my own FileStream and then wrap it with a StreamWriter if desired. Regardless, I've run into situations where I've needed to call Flush on both the StreamWriter and the FileStream, so I imagine that is your problem.

Try adding the following code:

            logWriter.Flush();
            if (logWriter.BaseStream != null)
                logWriter.BaseStream.Flush();
Dr. Wily's Apprentice
I was thinking about the same, but `StreamWriter` is flushing the underlying stream in its `Dispose`.
Ondrej Tucny
A: 

sometimes even u call flush(), it just won't do the magic. becus Flush() will cause stream to write most of the data in stream except the last block of its buffer.

try
{
 // ... write method
 // i dont recommend use 'using' for unmanaged resource
}
finally
{
 stream.Flush();
 stream.Close();
 stream.Dispose();
}
888