0

How can I create and then modify writing on this file?

string fileName = @"C:\...\MioFile.txt";

In main:

File.CreateText(fileName);

Then when I would edit the file by adding text.

StreamWriter writer = new StreamWriter(fileName);
sw.WriteLine("Hello"+variable);
sw.Close();

But the file is empty and I cannot write anything.

I would like create a file.txt and I would like for this file to always add new information every time I call it in writing mode. A kind of "log file".

TylerH
  • 20,799
  • 66
  • 75
  • 101
Skipper
  • 83
  • 1
  • 2
  • 8
  • If you look at the docs of the [StreamWriter](http://msdn.microsoft.com/en-us/library/system.io.stringwriter(v=vs.110).aspx) class you will find a lot of links that explain how to work with files – Steve Oct 20 '14 at 14:28

3 Answers3

2

Use File.AppendAllText instead of StreamWriter. Its simple:

File.AppendAllText(filename, "Hello"+variable);
Shaharyar
  • 12,254
  • 4
  • 46
  • 66
0

You have sw.WriteLine, But your streamwriter is called "writer". That might be the problem.

Koen
  • 634
  • 3
  • 14
0

I like to use the "using" statements:

//full path
var fileName = @"C:\Users\...\Desktop\newFile2.txt";
//Get the stream in FileMode.Append (will create or open)
using (var fileStream = new FileStream(fileName,FileMode.Append))
{
    //pass the fileStream into the writer.
    using (var writer = new StreamWriter(fileStream))
    {
        writer.WriteLine("{0} => file appended", DateTime.Now);
    }//dispose writer
}//dispose fileStream