搜索和使用C#替换文本文件中的值 [英] Search and replace values in text file with C#
本文介绍了搜索和使用C#替换文本文件中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一定格式的文本文件。首先是一个标识符后跟三个空格和冒号。然后说到这个标识符值
I have a text file with a certain format. First comes an identifier followed by three spaces and a colon. Then comes the value for this identifier.
ID1 :Value1
ID2 :Value2
ID3 :Value3
我需要做的是搜索例如:What为 ID2:
和替换值2
新值 NewValue2
。这将是一个办法做到这一点?我需要解析的文件不会得到非常大的。最大的将围绕150线。
What I need to do is searching e.g. for ID2 :
and replace Value2
with a new value NewValue2
. What would be a way to do this? The files I need to parse won't get very large. The largest will be around 150 lines.
推荐答案
如果该文件并不大,你可以做一个 File.ReadAllLines
来得到所有行的集合,然后替换你正在寻找这样的
If the file isn't that big you can do a File.ReadAllLines
to get a collection of all the lines and then replace the line you're looking for like this
using System.IO;
using System.Linq;
using System.Collections.Generic;
List<string> lines = new List<string>(File.ReadAllLines("file"));
int lineIndex = lines.FindIndex(line => line.StartsWith("ID2 :"));
if (lineIndex != -1)
{
lines[lineIndex] = "ID2 :NewValue2";
File.WriteAllLines("file", lines);
}
这篇关于搜索和使用C#替换文本文件中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文