Replace a word from a specific line in a text file

前端 未结 2 721
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: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});
    }
    

提交回复
热议问题