FileStream vs StreamWriter
I am a new programmer and have been reading the Beginning C# book.
In chapter 22 (File System Data) they explain that you must use FileStream if you want to determine the location of data input to a file, and StreamWriter if you dont have a specified location.
Well I did code that set the area of beginning input using StreamWriter, and it works perfeclty fine. I made a very simple windows form application with a button as an event handler. The code is:
private void button1_Click(object sender, EventArgs e)
{
DateTime time = DateTime.Now;
string logstring = textBox1.Text;
FileStream loggy = new FileStream(@"C:\Log.txt", FileMode.Append, FileAccess.Write);
loggy.Seek(0, SeekOrigin.End);
StreamWriter log = new StreamWriter(loggy);
log.WriteLine("");
log.WriteLine(time);
log.WriteLine(logstring);
log.Close();
}
Everytime you hit the button it does this:
(empty line)
Current time
Textbox value
Instead of using FileStream directly to write stuff in, all you have to do is set the Seek and then give the StreamWriter the FileStream file, which is automatically set to "Append" the file.
|