Puneet Pant
Puneet Pant

Reputation: 1048

StreamWriter truncating text while writing to a text file

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);
}

Upvotes: 3

Views: 5651

Answers (4)

User2012384
User2012384

Reputation: 4919

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);

Upvotes: 1

Noffls
Noffls

Reputation: 5427

Why don't you use

File.WriteAllText(completeFilePath, txt);

MSDN Documentation for File.WriteAllText

Upvotes: 0

akton
akton

Reputation: 14386

Assuming txt is a string variable containing the HTML, try calling sw.Flush() after sw.Write(). That should force the stream writer to write the rest of the string to the file. If the file is still truncated, ensure txt string contains the full output as intended.

Upvotes: 0

Adeel
Adeel

Reputation: 19238

After Write, use Flush method to clear buffer.

sw.Write(Html);
sw.Flush();

Upvotes: 8

Related Questions