Replace a word from a specific line in a text file

前端 未结 2 712
Happy的楠姐
Happy的楠姐 2020-12-22 09:41

I\'m working on a little test program to experiment with text files and storing some data in them, and I\'ve stumbled accross a problem when trying to replace a value in a s

2条回答
  •  一生所求
    2020-12-22 10:02

    Try this:

    var path = @"c:\temp\test.txt";
    var originalLines = File.ReadAllLines(path);
    
    var updatedLines = new List();
    foreach (var line in originalLines)
    {
        string[] infos = line.Split(',');
        if (infos[0] == "user2")
        {
            // update value
            infos[1] = (int.Parse(infos[1]) + 1).ToString();
        }
    
        updatedLines.Add(string.Join(",", infos));
    }
    
    File.WriteAllLines(path, updatedLines);
    

提交回复
热议问题