简体   繁体   中英

Transfer values between 2 config files

I have a problem, and i can't figure this out myself.. In my program i have an auto updater, when my program updates a new(changed, some new keys) config file is created. what i want my program to do is, is when it's updating to look at both config files(old and new) and transfer old settings that match a key in the new file to the new file.

This is an example of the old file:

 {
  "Setting1": false,
  "Setting2": 123,
  "Setting3": "test",
  "LocationList": {
    "Country": "NL",
    "Locations": [
      {
        "Latitude": 38.556807486461118,
        "Longitude": -121.2383794784546
      },
      {
        "Latitude": -33.859019,
        "Longitude": 151.213098
      },
      {
        "Latitude": 47.5014969,
        "Longitude": -122.0959568
      },
      {
        "Latitude": 51.5025343,
        "Longitude": -0.2055027
      }
    ]
  }
}

And this can be the new file(can also be different):

{
  "Setting1": null,
  "Setting2": null,
  "Setting3": "",
  "Setting4": ""
  "LocationList": {
    "Country": "",
    "Locations": [
      {
        "Latitude": null,
        "Longitude": null
      },
      {
        "Latitude": null,
        "Longitude": null
      }
    ]
  }
}

Expected result:

 {
  "Setting1": false,
  "Setting2": 123,
  "Setting3": "test",
  "Setting4": ""
  "LocationList": {
    "Country": "NL",
    "Locations": [
      {
        "Latitude": 38.556807486461118,
        "Longitude": -121.2383794784546
      },
      {
        "Latitude": -33.859019,
        "Longitude": 151.213098
      },
      {
        "Latitude": 47.5014969,
        "Longitude": -122.0959568
      },
      {
        "Latitude": 51.5025343,
        "Longitude": -0.2055027
      }
    ]
  }
}

First, i looked at creating a class in c# and just deserialize it, then, i came to the conclusion that this is not possible because i don't know what the config is going to look like.

Second, i thought using a dynamic would do the trick, it didn't, because i didn't knew any keys that were in it. And couldn't figure out how to figure that out.

And lastly, i've looked if it would be possible using regex, for me, this seems impossible..

Can anybody give me some ideas of how they would do it? I don't need code, just a push in the right direction.

PS i do not want to combine the two, when there is a key in the old file but not in the new one, it doesn't need to be transferred(Only lists will be completely transferred from the old file, also when the list is empty/filled in the new one).

I don't need code, just a push in the right direction.

Store your configuration in a regular App.config file and leverage the System.Configuration . Depending on the configuration complexity you can either use the ready <appSettings> or construct your own config section(s) and elements. It still be easier and error proof than doing custom config.

The matter is too complicated to start inventing the wheel just to use another (text) format. Even if you solve your current problem, there will be more, which are already solved somewhere within the System.Configration ...

You can start exploring the configuration options here ; anyways a regular search in your favorite search engine will do the trick...

If you really want to try something in JSON, I can only recommend the excellent JSON.Net library to parse the json for you. Using LINQ to JSON you could easily find matching keys in a recursive fashion between the old config file and the newer one and simply copy the value from one to the other

see documentation and a small example at http://www.newtonsoft.com/json/help/html/LINQtoJSON.htm

briefly you could do so in pseudoCode. Obviously this would not be super performant because you would recursively walk two files a lot of times and could be optimized, but at the same time unless your configuration files are monstrous blobs this should not pose any problem on any kind of modern hardware

//load both config files

//load the first token in original file and walk recursively

 //for each token try to match in the new file and write data if required using the same recursive technique to walk the other file

Oke after some trouble i've managed to fix it(Thanks @Louis).

This is how i've done it:

        private static bool TransferConfig(string baseDir, ISession session)
        {
            //if (!session.LogicSettings.TransferConfigAndAuthOnUpdate)
            //    return false;

            var configDir = Path.Combine(baseDir, "Config");
            if (!Directory.Exists(configDir))
                return false;

            var oldConf = GetJObject(Path.Combine(configDir, "config.json.old"));
            var oldAuth = GetJObject(Path.Combine(configDir, "auth.json.old"));

            GlobalSettings.Load("");

            var newConf = GetJObject(Path.Combine(configDir, "config.json"));
            var newAuth = GetJObject(Path.Combine(configDir, "auth.json"));

            TransferJSON(oldConf, newConf);
            TransferJSON(oldAuth, newAuth);

            File.WriteAllText(Path.Combine(configDir, "config.json"), newConf.ToString());
            File.WriteAllText(Path.Combine(configDir, "auth.json"), newAuth.ToString());

            return true;
        }

        private static JObject GetJObject(string filePath)
        {
            return JObject.Parse(File.ReadAllText(filePath));
        }

        private static bool TransferJSON(JObject oldFile, JObject newFile)
        {
            try
            {
                foreach (var newProperty in newFile.Properties())
                    foreach (var oldProperty in oldFile.Properties())
                        if (newProperty.Name.Equals(oldProperty.Name))
                        {
                            newFile[newProperty.Name] = oldProperty.Value;
                            break;
                        }

                return true;
            }
            catch
            {
                return false;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM