问题描述
我有一个文本文件,另一个应用程序将其用作配置文件。我已将文件的每一行读入String数组:
I have a text file that is used by another application as a configuration file. I have read in each line of the file into a String array:
string[] arrLine = File.ReadAllLines(pathToFile);
这完全符合我的需要。
现在,我要做的就是用字符串替换arrLine [x]的整个行,并覆盖该行和仅该行中的内容。我已经编写了代码以知道我需要替换的确切行,我只需要知道如何替换它。
Now, all i need to do is replace the entire line of arrLine[x] with a string, overwriting what is there on that line and that line only. I have wrote code to know the exact line i need to replace, i just need to know how to replace it.
我正在考虑arrLine [x] .Replace( oldString,newString)-如果可行,我实际上如何将更改提交到文本文件?我是否需要重写整个文件?我认为当只需要重写一行时,效率低下会有点吗?
I am thinking of arrLine[x].Replace(oldString, newString) - if this works, how would i actually commit the change to the text file? Do i somehow need to rewrite the whole file? Im thinking that would be a little on the inefficient side when only one line needs rewriting?
推荐答案
您应该能够分配该元素:
You should be able to just assign that element:
arrLine[yourLineNumber] = "Foo";
完成此操作后,可以使用 File.WriteAllLines(pathToFile,arrLine);
将数据写回到原始文件。
Once you've done this, you can use File.WriteAllLines(pathToFile, arrLine);
to write the data back to the original file.
这篇关于替换文本文件中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!