0

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#?

  • maybe [System.Text.RegularExpressions](https://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx). Or [this post](http://stackoverflow.com/questions/485659/can-net-load-and-parse-a-properties-file-equivalent-to-java-properties-class) in case you have `=` sign in value – gwillie Oct 05 '16 at 03:54

1 Answers1

0

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);
 }
Shannon Holsinger
  • 2,293
  • 1
  • 15
  • 21