Question

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.

Was it helpful?

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.

OTHER TIPS

or better ofile.Close(); which closes the stream and also flushs it when you finished with it MSDN link

I suggest to use System.IO.File static class it takes care of flushing and disposing, you just need to call AppendAllText method like this:

System.IO.File.AppendAllText(@"C:\myPath\my_data_output.txt", myString + "\t");

And if you need to call it many times then my suggestion is using StringBuilder:

StringBuilder sb = new StringBuilder();
while(condition)
{
    //Your loop body

    sb.AppendText(myString + "\t");
}
File.AppendAllText(@"C:\myPath\my_data_output.txt",sb.ToString());

You have couple of options:

StringBuilder sb = new StringBuilder();
while(SOME CONDITION)
{
    sb.AppendLine("YOUR STRING"); 

}
// Set boolean to true to append to the existing file.
using (StreamWriter outfile = new StreamWriter(mydocpath + @"\AllTxtFiles.txt", true))
{
    outfile.WriteLine(sb.ToString());
}



//Append new text to an existing file. 
// The using statement automatically closes the stream and calls  
// IDisposable.Dispose on the stream object. 
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines.txt", true))
{
    file.WriteLine("Your line");
}

Also, make sure that you have write permission on the dir/file you are trying to write to and that you are running your application as an admin.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top