StreamWriter.Write doesn't write to file; no exception thrown

sarsnake picture sarsnake · Jun 13, 2012 · Viewed 61.5k times · Source

My code in C# (asp.net MVC)

StreamWriter tw = new StreamWriter("C:\\mycode\\myapp\\logs\\log.txt");

// write a line of text to the file
tw.Write("test");

The file is created but is empty. No exception is thrown. I have never seen this before and I am stuck here; I just need to write some debugging output.

Please advise.

Answer

Benjamin Cox picture Benjamin Cox · Jun 13, 2012

StreamWriter is buffered by default, meaning it won't output until it receives a Flush() or Close() call.

You can change that by setting the AutoFlush property, if you want to. Otherwise, just do:

StreamWriter tw = new StreamWriter("C:\\mycode\\myapp\\logs\\log.txt");

// write a line of text to the file
tw.Write("test");
tw.Close();  //or tw.Flush();