How to make designer generated .Net application settings portable

╄→гoц情女王★ 提交于 2019-11-28 10:26:05

Why not use the CodeProject PortableSettingsProvider solution as is (with a few minor changes) ? I have done so in my project (StreamRecorder.NET) with success.

Some comments on the project's page were useful:

And the code I ended up with:

    static void Main(string[] args)
    {
        if (args.Contains("-p") || args.Contains("--portable"))
        {
            MakePortable(Properties.Settings.Default);
            MakePortable(Properties.LastUsedSettings.Default);
            MakePortable(Properties.DefaultSettings.Default);
        }
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm(args));
    }

    private static void MakePortable(ApplicationSettingsBase settings)
    {
        var portableSettingsProvider = 
            new PortableSettingsProvider(settings.GetType().Name + ".settings");
        settings.Providers.Add(portableSettingsProvider);
        foreach (System.Configuration.SettingsProperty prop in settings.Properties)
            prop.Provider = portableSettingsProvider;
        settings.Reload();
    }

Lastly I made these changes to the CP project:

string _fileName;
public PortableSettingsProvider(string fileName)
{
    _fileName = fileName;
}

public virtual string GetAppSettingsFilename()
{
    //Used to determine the filename to store the settings
    //return ApplicationName + ".settings";
    return _fileName;
}

I know this question is quite old already. I just want to share my own version of a portable settings provider which I published as nuget package here.

The usage is pretty simple:

// make the default settings class portable
PortableSettingsProvider.ApplyProvider(Properties.Settings.Default);

I also explained the basic strategy of this implementation at https://www.codeproject.com/Articles/1238550/Making-Application-Settings-Portable.

Just to 'close' the question: The somewhat unsatisfactory solution I ended up with was

  1. Create a custom settings provider, which inherits from SettingsProvider and stores the settings in a XML file
  2. Set the Provider property of each of the setting (by selecting the entire grid in the designer) to the custom settings provider using the designer

Drawbacks: The forms designer breaks and gives an exception which basically says that the custom provider class cannot be found. The built exe however works OK. Setting the provider in the code as described in the question makes the designer work, but then for some reason, which I haven't looked closely at, the settings won't serialize.

It seems that making settings portable was all that was needed to make Doppler portable. Whether I'll start using Doppler as my main podcast aggregator or stick with my homebrew command line aggregator, I'll see.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!