Domanda

Basically I have a C# application that has certain settings that I want any user to be able to change but I want these settings to apply to all users. (The exact implementation is for computer-specific but not user-specific items like folder paths and com ports, etc) So far I have implemented this using appSettings and it has been working well but this breaks down when a user does not have permission to write to the Program Files directory.

I'm looking for suggestions on how to best handle this situation either utilizing appSettings, userSettings, or values in the registry. Whatever solution I use has to work for users that are not administrators as well as those that are. What would be considered a 'best practice' for this type of requirement?

È stato utile?

Soluzione

I will try to write an XML file containing all the settings that need to be read/written.
This file could be saved in a well known folder like ProgramData (using Enviroment.SpecialFolder.CommonApplicationData)

The easyest way to do this is using the builtin methods of a datatable WriteXml and ReadXml.
You could implement a class that internally Load and Save your settings using a datatable and offer methos to retrive and set individual settings (rows in the datatable);

public class MyAppSettings
{
    // Where to store your settings
    private DataTable _storage = null;

    public MyAppSettings()
    {
       string settingFile = Path.Combine(Environment.GetFolderPath
                            (Environment.SpecialFolder.CommonApplicationData), 
                            "MyAppName", "MyAppSettings.xml");
       _storage = new DataTable();
       _storage.ReadXml(settingFile);
    }
    public void Save()
    {
       string settingFile = Path.Combine(Environment.GetFolderPath
                            (Environment.SpecialFolder.CommonApplicationData), 
                            "MyAppName", "MyAppSettings.xml");
       _storage.WriteXml(settingFile);
    }

    public string GetValue(string settingName)
    {
        // Code to search the base table
    }
    public void SetValue(string settingName, string settingValue)
    {
        // Code to update/insert the base table
    }
}

Altri suggerimenti

You should use Application Settings for this.

Visual Studio provides good support and auto-generates accessor classes with the properties (settings) you declare.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top