将大字符串写入文件的最佳方法 [英] Best way to write huge string into a file

查看:393
本文介绍了将大字符串写入文件的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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:

  1. 使用StreamReader从原始文件中读取每一行.
  2. 打开StringBuilder以获得新文件的内容.
  3. 修改字符串对象并调用StringBuilderAppendLine(直到文件末尾)
  4. 打开一个新的StreamWriter,并将StringBuilder写入写入流.
  1. Read each line from the original file by using StreamReader.
  2. Open a StringBuilder for the contents of the new file.
  3. Modify the string object and call AppendLine of the StringBuilder (until the end of the file)
  4. Open a new StreamWriter, and write the StringBuilder 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆