aloneguid / config

⚙ Config.Net - the easiest configuration framework for .NET developers. No BS.
MIT License
656 stars 86 forks source link

Writing configuration #63

Closed jwillmer closed 6 years ago

jwillmer commented 6 years ago

I don't have any config file in my project since I like the tool to look for an existing config file first. My assumption is that the line below will create a new config file and write the default settings in it but it doesn't work. Is there a build in method to do this?

Settings = new ConfigurationBuilder<ApplicationSettings>()
                        .UseAppConfig()
                        .Build(); 
aloneguid commented 6 years ago

Hi @jwillmer the app.config provider is read-only at the moment therefore no files are created. It's a tricky question whether it should be writeable or not as many applications like asp.net are configured to restart as soon as config changes are detected. This can be implemented though.

jwillmer commented 6 years ago

My workaround is now as following:

var directory = Directory.GetCurrentDirectory();
var configName = "App.config";
var configPath = Path.Combine(directory, configName);
if (!File.Exists(configPath)) {
    File.Copy(configPath + ".bak", configPath);
}

But using Settings.MyPortValue only returns me the [Option(DefaultValue = 54400)] and not the one specified in the App.config.

jwillmer commented 6 years ago

Never mind, it got to complicated. I use now Newtonsoft.Json and wrote the following code for it:

private static void InitConfiguration() {
    var directory = Directory.GetCurrentDirectory();
    var configName = "app.config";
    var configPath = Path.Combine(directory, configName);

    if (!File.Exists(configPath)) {
        Settings = new ApplicationSettings();
        var content = JsonConvert.SerializeObject(Settings, Formatting.Indented);
        File.WriteAllText(configPath, content);
    }
    else {
        var content = File.ReadAllText(configPath);
        Settings = JsonConvert.DeserializeObject<ApplicationSettings>(content);
    }
}
aloneguid commented 6 years ago

That's fine.