Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 358
sarsnake Avatar asked Jun 13 '12 21:06

sarsnake


People also ask

Where does StreamWriter write to?

StreamWriter class in C# writes characters to a stream in a specified encoding. StreamWriter. Write() method is responsible for writing text to a stream. StreamWriter class is inherited from TextWriter class that provides methods to write an object to a string, write strings to a file, or to serialize XML.

What is the difference between FileStream and StreamWriter?

Specifically, a FileStream exists to perform reads and writes to the file system. Most streams are pretty low-level in their usage, and deal with data as bytes. A StreamWriter is a wrapper for a Stream that simplifies using that stream to output plain text.

Will StreamWriter create a file?

public StreamWriter(string path, bool append); This constructor initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, the constructor creates a new file.

Can be used to write a stream of text to a file?

The StreamWriter class in C# is used for writing characters to a stream. It uses the TextWriter class as a base class and provides the overload methods for writing data into a file. The StreamWriter is mainly used for writing multiple characters of data into a file.


2 Answers

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(); 
like image 138
Benjamin Cox Avatar answered Sep 20 '22 17:09

Benjamin Cox


Neither flushed nor closed nor disposed. try this

using (StreamWriter tw = new StreamWriter(@"C:\mycode\myapp\logs\log.txt")) {     // write a line of text to the file     tw.Write("test");     tw.Flush(); } 

or my preference

using (FileStream fs = new FileStream( @"C:\mycode\myapp\logs\log.txt"                                      , FileMode.OpenOrCreate                                      , FileAccess.ReadWrite)           ) {     StreamWriter tw = new StreamWriter(fs);     tw.Write("test");     tw.Flush(); } 
like image 28
Tony Hopkinson Avatar answered Sep 17 '22 17:09

Tony Hopkinson