Search code examples
c#windowswindows-7streamwriterconsole.writeline

error to write text to a text file line by line by appending in C# , but got nothing in the file


I am working on C# on Win7 VS 2012.

I need to write text to a text file line by line by appending.

 StreamWriter ofile = new StreamWriter(@"C:\myPath\my_data_output.txt", true);

  ofile.WriteLine(myString + "\t");

But, there is nothing in the output file.

Any help would be appreciated.


Solution

  • Enclose your code in a using clause. This will call the Dispose method on the StreamWriter class. The Dispose method calls the Flush method, which writes to the stream.

    Your code would look like this:

    using (StreamWriter ofile = 
               new StreamWriter(@"C:\myPath\my_data_output.txt", true)
    {
        ofile.WriteLine(myString + "\t"); 
    }
    

    You can always call the flush method at any time.