Replace a word from a specific line in a text file

前端 未结 2 713
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<string>();
    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);
    
    0 讨论(0)
  • 2020-12-22 10:06

    use ReadLines and LINQ:

    var line = File.ReadLines("path")
                   .FirstOrDefault(x => x.StartsWith(username));
    
    if (line != null)
    {
         var parts = line.Split(',');
         parts[1] = "1500"; // new number
         line = string.Join(",", parts);
         File.WriteAllLines("path", File.ReadLines("path")
             .Where(x => !x.StartsWith(username)).Concat(new[] {line});
    }
    
    0 讨论(0)
提交回复
热议问题