C# 修改文本文件中特定行的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15656198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Modify the content of specific line in text file
提问by user2148116
I'm new on c# and currently working on project so that I need to open an existing text file and editing the content of a specific line (i.e. 32) but I failed! Any help?
我是 c# 新手,目前正在处理项目,因此我需要打开一个现有的文本文件并编辑特定行(即 32)的内容,但我失败了!有什么帮助吗?
回答by Mike Perrenoud
Well, based on your question you know the line number, so do something like this:
好吧,根据您的问题,您知道行号,因此请执行以下操作:
var lines = File.ReadAllLines("path to file");
lines[31] = "some value";
File.WriteAllLines("path to file", lines);
the first line of code gets you all the lines of a file into an array. The second line clearly sets thy known line to some value, and the third line overwrites the file with the new set of lines.
第一行代码将文件的所有行放入一个数组中。第二行清楚地将你的已知行设置为某个值,第三行用新的行集覆盖文件。