C#替换文件中关键字后的文本

时间:2017-12-10 00:13:25

标签: c# file

如何更改关键字后面的文字?

我的档案如下;

[DbServer] = localhost
[DbUser] =用户
[DbPassword] =通过
[DBNAME] = TESTDB

对于前。如何在[DbUser] =之后找到用户并在c#中更改它?

2 个答案:

答案 0 :(得分:0)

你可能想要这样的东西:

using System.Text.RegularExpressions;
...

string[] lines = new string[] {
  "[DbServer]=localhost", 
  "[DbUser]=user", 
  "[DbPassword]=pass", 
  "[DbName]=testDb"};

foreach (string line in lines) {
    string user = "<none>";
    var m = Regex.Match(line, @"^\s*\[DbUser\]\s*=\s*(\S+)\s*");
    if (m.Success) {
        user = m.Groups[1].Value;
        line = Regex.Replace(line, user, "Joe");
        #replaced User with Joe and reassigned it to line
    }
}

答案 1 :(得分:0)

public void replaceWordInFile(string fileName, string keyWord, string newWord) //Keyword sonrasındaki stringi verilen string ile değiştirir
    {
        StreamReader reading = File.OpenText(fileName);
        string pattern = @"\w+=([A-Za-z0-9\-_]+)";
        string str;

        while ((str = reading.ReadLine()) != null)
        {
            if (str.Contains(keyWord))
            {
                Regex regex = new Regex(pattern);
                Match match = regex.Match(str);

                if (match.Success)
                {
                    testLabel.Text = match.Groups[1].Value;
                }
            }
        }
        reading.Close();
    }