创建并写入文件txt

Create and write file txt

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

Use File.AppendAllText instead of StreamWriter. Its simple:

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

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

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