“就地"替换文件中的一行- C# [英] Replacing a line in a file "in place" - C#

查看:85
本文介绍了“就地"替换文件中的一行- C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
通过 C# 就地编辑文本文件

我需要在一个非常大的文件中替换一行,所以我不想 readAll 和 writeAll - 我想到达需要替换的行,替换并关闭文件.知道如何在 C# 中做到这一点吗?

I need to replace a line in a very big file , so I don't want to readAll and writeAll - I want to get to the line requiring replacement , replace , and close the file. Any idea how to do it in C#?

谢谢!

推荐答案

实际上,您有两个选择,第一个有一些严格的限制,第二个是最简单的,可能也是您想要的.

Really, you've two options, the first has some severe restrictions, the second is the simplest and probably the one you want.

  1. 打开文件进行读写访问,逐行读取文件,记住位置您刚刚阅读的当前行(StreamReader.BaseStream.pos).如果这是替换 和的行新行完全一样长如旧,寻回行的开头并写入.
  2. 打开文件,读取每一行,写入到新文件,不要将行写入被替换,但写新行反而.然后继续阅读 &写作直到完成.
  1. Open the file for Read Write access, read the file line by line, remembering the position of the current line you've just read (StreamReader.BaseStream.pos). If this is the line to replace and the new line is exactly the same length as the old, seek back to the start of the line and write.
  2. Open the file, read each line, write to new file, don't write the line to be replaced, but write the new line instead. Then just keep reading & writing until done.

第二个选项更简单,而且速度可能更快(您需要进行分析以确保),并且它没有新行的长度完全相同作为旧的限制.

The second option is much simpler and could well be faster (you'd need to profile to be sure), and it doesn't have the new line is exactly the same length as the old restriction.

选择选项 2

附言改掉使用 ReadAll WriteAll 函数的习惯,它们不适用于现实世界的应用程序.读取一行,处理一行"习惯用法同样适用于 100k 和 100TB 的文件...100TB 文件显然需要更长的时间:)

P.S. Get out of the habit of using ReadAll WriteAll functions, they're not good for real world applications. The "read a line, process a line" idiom will work on files of 100k and 100TB equally well . . . the 100TB file will obviously take a little longer :)

P.P.S 虽然选项 1 听起来很简单,但实际上很难正确实施,有 100 多个小问题可能会出错.可变字节大小、不同编码等.选项 2 听起来很简单.

P.P.S While Option 1 sounds straight forward, it's actually surprising difficult to implement correctly, there are 100's of little things that can go wrong. Variable byte sizes, different encodings etc. Option 2 is as simple as it sounds.

这篇关于“就地"替换文件中的一行- C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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