3

我在字符串变量中有大量内容,我想使用流编写器将该内容写入文本文件。但是流编写器正在截断文本,而不是将整个内容写入文件。为什么?

using (StreamWriter sw = new StreamWriter(completeFilePath))
{
    sw.Write(txt);
}
4

4 回答 4

7

写入后,使用 Flush 方法清除缓冲区。

sw.Write(Html);
sw.Flush();
于 2013-03-22T07:34:11.063 回答
0

你为什么不使用

File.WriteAllText(completeFilePath, txt);

File.WriteAllText 的 MSDN 文档

于 2013-03-22T07:36:25.207 回答
0

如果尺寸太大,

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

如果大小不是那么大,我建议使用 File.WriteAllText 方法

//no need to Open or Close anything
File.WriteAllText(Path, txt);
于 2013-03-22T07:42:17.960 回答
0

假设txt是一个包含 HTML 的字符串变量,尝试调用sw.Flush()after sw.Write()。这应该强制流编写器将字符串的其余部分写入文件。如果文件仍被截断,请确保txt字符串包含预期的完整输出。

于 2013-03-22T07:33:17.183 回答