Brett Powell Brett Powell - 2 months ago 12
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:

Server.ServerType=official


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

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('=');
  switch(parts[0]){
      case "Server.ServerType":
         parts[1] = "modded";
         break;
         ....
  }
  string newline = String.Join("=",parts);
  WriteLine(newline);

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

 Dictionary<string,string> values = new Dictionary<string,string>
 string[] parts = Readline().Split('=');
 values.Add(parts[0],parts[1]);
 values["Server.ServerType"] = "modded";
 ....
 foreach(KeyValuePair<string,string> kvp in values){
    WriteLine(kvp.Key+"="+kvp.Value);
 }