StreamWriter – Don’t Forget To Flush

I started working through the examples in the CLR Profiler documentation over the weekend.  The 1st one looks like this:

StreamReader streamReader = new StreamReader(@"C:\Users\Jamie\Desktop\Demo1.dat");
string line;
int lineCount = 0;
int itemCount = 0;
while ((line = streamReader.ReadLine()) != null)
{
    lineCount++;
    string[] items = line.Split();
    for (int i = 0; i < items.Length; i++)
    {
        itemCount++;
    }
}
streamReader.Close();

Console.WriteLine("{0} lines, {1} items", lineCount, itemCount);

To make that Demo1.dat file, I needed to write a quick function that spits out the expected values.  I coded up this:

StreamWriter streamWriter = new StreamWriter(@"C:\Users\Jamie\Desktop\Demo1.dat");
string word = "0123456789 ";
for(int i=0; i<2000; i++)
{
    StringBuilder stringBuilder = new StringBuilder();
    for(int j = 0; j < 10; j++)
    {
        stringBuilder.Append(word); 
    }
    streamWriter.WriteLine(stringBuilder.ToString());
}

When I ran the function, the last chunks of data was not showing up:

image

I talked to my friend Rob Seder and he said “You dummy, you forgot to flush!*”  Sure enough, when I set this:

streamWriter.AutoFlush = true;

the results came out as expected.

 

*He really didn’t say “You Dummy”, that is what I told myself once he mentioned it…..

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: