将大字符串写入文件的最佳方法 [英] Best way to write huge string into a file
问题描述
在C#中,我正在读取中等大小的文件(100 KB〜1 MB),修改内容的某些部分,最后写入另一个文件.所有内容均为文本.修改是通过字符串对象和字符串操作完成的.我目前的方法是:
In C#, I'm reading a moderate size of file (100 KB ~ 1 MB), modifying some parts of the content, and finally writing to a different file. All contents are text. Modification is done as string objects and string operations. My current approach is:
- 使用
StreamReader
从原始文件中读取每一行. - 打开
StringBuilder
以获得新文件的内容. - 修改字符串对象并调用
StringBuilder
的AppendLine
(直到文件末尾) - 打开一个新的
StreamWriter
,并将StringBuilder
写入写入流.
- Read each line from the original file by using
StreamReader
. - Open a
StringBuilder
for the contents of the new file. - Modify the string object and call
AppendLine
of theStringBuilder
(until the end of the file) - Open a new
StreamWriter
, and write theStringBuilder
to the write stream.
但是,我发现StremWriter.Write
截断了32768个字节(2 ^ 16),但是StringBuilder
的长度大于该长度.我可以编写一个简单的循环以确保将整个字符串保存到文件中.但是,我想知道在C#中执行此任务的最有效方法是什么?
However, I've found that StremWriter.Write
truncates 32768 bytes (2^16), but the length of StringBuilder
is greater than that. I could write a simple loop to guarantee entire string to a file. But, I'm wondering what would be the most efficient way in C# for doing this task?
总而言之,我只想修改文本文件的某些部分并写入其他文件.但是,文本文件的大小可能大于32768字节.
To summarize, I'd like to modify only some parts of a text file and write to a different file. But, the text file size could be larger than 32768 bytes.
==答案==很抱歉让您困惑!只是我没有打电话给flush
. StremWriter.Write
没有简短的限制(例如2 ^ 16).
== Answer == I'm sorry to make confusin to you! It was just I didn't call flush
. StremWriter.Write
does not have a short (e.g., 2^16) limitation.
推荐答案
StreamWriter.Write
截断字符串,没有限制.
truncate the string and has no limitation.
内部使用String.CopyTo
,另一方面使用不安全代码(使用fixed
)复制字符,因此它是最有效的.
Internally it uses String.CopyTo
which on the other hand uses unsafe code (using fixed
) to copy chars so it is the most efficient.
这篇关于将大字符串写入文件的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!