bkjames
bkjames

Reputation: 266

User Settings for all users

I know there has to be a way to have Application/User settings that are read/write and be the same for all users. I write code for automated laser marking machines that are installed in factories. I want the code to be as simple as

        private void _btnApply_Click(object sender, EventArgs e)
    {
        Settings.Default.IOCOM = comboIOCOM.Text;
        Settings.Default.TLoc = tbTLoc.Text;
        Settings.Default.Save();
    }

but I don't want the .config file to be saved in each user's folder. I want the same settings to be used by all users.

things to keep in mind when answering is that the user that will be logged in will have admin rights to the c:\ and all folders

Also, I am using VS 2010.

Upvotes: 3

Views: 1827

Answers (2)

bkjames
bkjames

Reputation: 266

The solution I came up with is to use the EF and SQLite to store all the settings for my applications. This way I can load from the DB to a Model and store the DB file to any location I wish. Also I gain the structure and organisation of SQL and can skip all the serialization of an XML file. In addition, the DB file is not plain text and I can limit an unauthorized user from changing setting by using notepad.

Upvotes: 0

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

Not automatically like the user.config or the app.config. But the way to do it is use Environment.GetFolderPath( to find the CommonApplicationData folder.

//Finding the file
var commonPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
var programPath = Path.Combine(commonPath, "Your Programs Name");
var settingFile = Path.Combine(programPath, "settings.xml");



//Saving settings
Directory.CreateDirectory(programPath);
var serializer = new XmlSerializer(typeof(YourCustomSettingsType));
using(var fs = File.Open(settingFile, FileMode.Create))
{
    serializer.Serialize(fs, yourCustomSettings);
}


//loading settings
try
{
    var serializer = new XmlSerializer(typeof(YourCustomSettingsType));
    using(var fs = File.Open(settingFile, FileMode.Open))
    {
        yourCustomSettings = (YourCustomSettingsType)serializer.Deserialize(fs);
    }
}
catch
{
    //If it fails to load just use the default settings (set in the constructor)
    yourCustomSettings = new YourCustomSettingsType();

    //Save the settings out so it won't fail next time.
    SaveSettings(yourCustomSettings);
}

You would use your custom settings class just like you would use the normal settings class.

Upvotes: 3

Related Questions