Create and write file txt

368 Views Asked by At

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".

3

There are 3 best solutions below

0
On

Use File.AppendAllText instead of StreamWriter. Its simple:

File.AppendAllText(filename, "Hello"+variable);
0
On

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

0
On

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