Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamWriter truncating text while writing to a text file

Tags:

c#

asp.net

I have a huge content in a string variable and I want to write that content to a text file using stream writer. But the stream writer is truncating the text and not writing the whole content to file. Why?

using (StreamWriter sw = new StreamWriter(completeFilePath))
{
    sw.Write(txt);
}
like image 384
Puneet Pant Avatar asked Oct 21 '25 10:10

Puneet Pant


2 Answers

After Write, use Flush method to clear buffer.

sw.Write(Html);
sw.Flush();
like image 160
Adeel Avatar answered Oct 22 '25 23:10

Adeel


If the size is too large,

    using (StreamWriter sw = new StreamWriter(completeFilePath))
{
    sw.Write(txt);
    //just to make sure the stream writer flushes the command
    sw.Flush();
}

If the size isn't that large, I suggest to use File.WriteAllText method

//no need to Open or Close anything
File.WriteAllText(Path, txt);
like image 42
User2012384 Avatar answered Oct 22 '25 23:10

User2012384