C# 逐行检查文件
我正在逐行读取文件,我想编辑我读到的一些行。 我想要编辑的行必须在其上方或下方有一些其他特定行,但我不知道如何在 C# 中表达这一点。 例如:
http://www.youtube.com
You Tube | Music | something
Sports
Music
Radio
Clips
http://www.youtube.com/EDIT ME
Sports
Music
Radio
Clips
我想编辑一行 仅当下一行是
Sports
并且上一行是
Clips
所以我想从上面的示例编辑的唯一行是
http://www.youtube.com/EDIT ME
有什么想法吗?
I am reading from a file line by line and i want to edit some of the lines i read..
The lines i want to edit must have some other specific lines above or below them, but i dont know how to express that in C#.
For example:
http://www.youtube.com
You Tube | Music | something
Sports
Music
Radio
Clips
http://www.youtube.com/EDIT ME
Sports
Music
Radio
Clips
and i want to edit a line
only if next line is
Sports
and the previous line is
Clips
So the only line i want to edit from the example above is
http://www.youtube.com/EDIT ME
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法真正逐行“编辑”文件。最好采用以下两种方法之一:
File.ReadAllLines
,然后在内存中进行适当的更改并重写整个内容(例如使用File.WriteAllLines
)第一个版本更简单,但显然需要更多内存。正如您提到的,如果您需要查看下一行和上一行,那就特别棘手。
第一种方法的简单示例:
You can't really "edit" a file line by line. It would be best to take one of two approaches:
File.ReadAllLines
, then make appropriate changes in memory and rewrite the whole thing (e.g. usingFile.WriteAllLines
)The first version is simpler, but obviously requires more memory. It's particularly tricky if you need to look at the next and previous line, as you mentioned.
Simple example of the first approach:
方法#1
当您循环访问文件时,请为前一行保留一个变量(在循环之前始终将其更新为当前行)。现在您知道了当前行和上一行,您可以决定是否需要编辑当前行。
方法#2
当您循环访问文件时,设置与某些条件相对应的标志,例如我刚刚找到了
Sports
。如果您稍后发现应取消设置该标志的条件,例如我刚刚找到了Radio
,请取消设置它。如果您找到Clips
,您可以检查SportsFlag
是否设置,以查看是否需要编辑此Clips
行。第二种方法更加灵活(允许您根据当前行设置和取消设置多个标志),并且如果
Sports
和Clips
。它实际上是一个穷人状态机Approach #1
While you're looping through the file, keep a variable for the the previous line (always update this to the current line before you loop). Now you know the current line and previous line, you can decide if you need to edit the current line.
Approach #2
While you're looping through the file, set a flag corresponding to some condition e.g. I've just found
Sports
. If you later find a condition that should unset the flag e.g. I've just foundRadio
, un set it. If you findClips
you can check is theSportsFlag
set to see if you need to edit thisClips
line.The second approach is more flexible (allows you to set and unset multiple flags depending on the current line) and and is good if there could be multiple lines of crud between
Sports
andClips
. It's effectively a poor mans State Machine如果文件不是那么大,我会将整个文件作为字符串读取。然后你可以使用像indexOf和substring这样的方法自由地操作它。
一旦您获得了所需的字符串,请将其写回到您拥有的文件上。
If the file isn't that large, I would read in the entire file as a string. Then you can freely manipulate it using methods like indexOf and substring.
Once you have the string how you need it, write it back over the file you had.