使用 C# 搜索和替换文本文件中的值 [英] Search and replace values in text file with C#

查看:36
本文介绍了使用 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

我需要做的是搜索,例如对于 ID2 : 并将 Value2 替换为新值 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屋!

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