Brett Powell Brett Powell - 1 year ago 57
C# Question

Replace line in file containing specific string w/ C#

I have a configuration file where each line is a setting and value combo. I don't know what the value is set to, however I do know the name of the setting, where I need to update the entire line. I've found numerous examples making use of File.ReadAllText.Replace and File.WriteAllText but these are replacing a specific string with another string.

Example Setting Line:


I need to find the line that contains "Server.ServerType=" and in this example I would replace it with "Server.ServerType=modded".

What would be the most simplistic approach to do this using C#?

Answer Source

Split the line on the "=" sign, then test using the first element and change the second element as necessary, then join by replacing the "=" sign. I used a switch assuming you will have multiple tests (easier than a lot of IF/THENs):

  string line = ReadLine();
  string[] parts = line.Split('=');
      case "Server.ServerType":
         parts[1] = "modded";
  string newline = String.Join("=",parts);

If you change the values numerous times, you could use:

 Dictionary<string,string> values = new Dictionary<string,string>
 string[] parts = Readline().Split('=');
 values["Server.ServerType"] = "modded";
 foreach(KeyValuePair<string,string> kvp in values){