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.
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.
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.
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.
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.
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();
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With