I have made a Win Form and have a few controls like checkboxes, radio buttons etc. What I hope to happen is that the user will choose some settings e.g. tick the box to start the program on startup, then they can quit, when they open it again, how do I ensure that the choices that they made are saved? Thanks.
There are a few ways, but I'd recommend using the .NET user settings method to save their settings in the properties section of the application and reload and set them when they start the application again.
Here's an example:
Save Setting
Properties.Settings.Default.CheckboxChecked = true;
Properties.Settings.Default.Save();
Load Setting
checkBox.Checked = Properties.Settings.Default.CheckboxChecked;
I'd recommend giving them more meaningful names, however.
You can read more, with examples here: MSDN Using Application Settings and User Settings
This is also a nice tutorial on how to implement user settings from start to finish: C# - Saving User Settings - Easy way!
http://msdn.microsoft.com/en-us/library/aa730869%28v=vs.80%29.aspx Here is and Article how to use Settings in C# Application .
Where you can check ,if CheckBox is Checked with a Boolean etc.
Perhaps you’re looking for something like this:
Add this:
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
Then this to the program:
for_save info = new for_save();
string general_path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string path = general_path + "\\MyApplication";
BinaryFormatter serializer = new BinaryFormatter();
info.check = true;
info.radio = false;
//write
Directory.CreateDirectory(path);
Stream write_stream = File.Create(path + "\\MyFile.txt");
serializer.Serialize(write_stream, info);
write_stream.Close();
//read
Stream read_stream = File.OpenRead(path + "\\MyFile.txt");
for_save read_info = (for_save) serializer.Deserialize(read_stream);
read_stream.Close();
textBox1.Text = read_info.check.ToString() + read_info.radio.ToString();
And this class:
[Serializable()]
class for_save
{
public bool check;
public bool radio;
}
Related
C# Windows Forms.
I have successfully used Application Settings to save and load user settings for the values of controls on my form.
I have a checkbox and code where I can set whether this happens automatically (at application start and close), or not.
I also have a menu so I can load them and save them during runtime.
This is all using the default user.config.
Example.
In Application settings I have (for one of the items, which is a radio button called RbBitRate6Mbps):
Name: BitRate6Mbps
Type: String
Scope: User
Value: False
To save the settings I have a menu item, Save Defaults. This runs:
if (RbBitRate6Mbps.Checked == true)
{
Settings.Default["BitRate6Mbps"] = "True";
}
else
{
Settings.Default["BitRate6Mbps"] = "False";
}
Settings.Default.Save();
To load the settings back in I have a menu item, Load Defaults. This runs:
if (Settings.Default["BitRate6Mbps"].ToString() == "True")
{
RbBitRate6Mbps.Checked = true;
}
else
{
RbBitRate6Mbps.Checked = false;
}
There are about 10 other controls I save and load (text boxes, check boxes and radio buttons), in the rest of the above code.
This is all working with no issues.
Now I would like to have several sets of these settings, each will contain some identical values and some different ones.
Each will have a different file name and be saved into a custom location (which will be the app folder, by default).
I do not mind what format the file is (xml, ini, etc), but if it is the same as the default, this would be good.
I have created new menu items, Save Custom Settings and Load Custom Settings.
I have added a SaveFileDialog and a LoadFileDialog to hopefully be used for the above.
But if these are not necessay, that is good too.
This is where I have become stuck.
I have been searching for days for a clear example of how to do this.
I have been unable to find much. What I have found, I have been unable to understand the documentation.
I am thinking loading the settings back in will be the easier part?
But I also think, for saving the file, using:
Settings.Default.Save();
Will not accomplish my aims as it will just write to the default user.config file ?
Is what I want to do possible?
If so does anyone have any instructions and example code?
Update. I have installed a new Settings Provider and it is working well. It saves the XML to the app folder. I have also set up INI files to save the settings. Using both a custom path and custom file name. It allows for multiple INI files to be created. This also works extremely well.
Edit: Updated code (and instructions) so it is no longer necessary to create any custom folder manually. If it does not exist, it will be created.
The XML Settings Provider developers project is located here:
Settings Providers on Github
The INI file developers project (and demo) is located here:
C# WinForms Ini File demo on Github
Below are the instructions for setting up the new Settings Provider with an XML file and following that are the instructions for saving the settings to INI files (both types can be used in the same project at the same time, as I am doing here):
Using a new Settings Provider to save settings in an XML file:
1.
Setup the Application Settings (in Solution Explorer, right-click on the App. Then Select: Properties. Then open: Settings).
Name: txtFullName
Type: String
Scope: User
Value: John Doe
Name: txtSchool
Type: String
Scope: User
Value: Oxford
Name: txtClass
Type: String
Scope: User
Value: 4B
Name: chkActiveStudent
Type: bool
Scope: User
Value: True
2.
Install, from NuGet the new Settings Provider (in Solution Explorer, right-click on: References. Then Select: Manage NuGet Packages. Then search for: PortableSettingsProvider. Install it).
3.
In Program.cs modify static void Main(). Add to it the lines below.
//PortableSettingsProvider.SettingsFileName = "portable.config";
//PortableSettingsProvider.SettingsDirectory = "c:\\\testconfig\\\school";
//System.IO.Directory.CreateDirectory(PortableSettingsProvider.SettingsDirectory);
PortableSettingsProvider.ApplyProvider(Properties.Settings.Default);
If accepting the default settings (the config file, portable.config, will be created in the applications folder), a properly edited static void Main() entry would look like the below.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//PortableSettingsProvider.SettingsFileName = "portable.config";
//PortableSettingsProvider.SettingsDirectory = "c:\\testconfig\\school";
//System.IO.Directory.CreateDirectory(PortableSettingsProvider.SettingsDirectory);
PortableSettingsProvider.ApplyProvider(Properties.Settings.Default);
Application.Run(new MyTestApp());
}
3a.
To choose a different filename and location, remove the comments (//) and change to your preference for filename and location (double slashes are needed between the folder names). In this example I use settings.config as the filename and c:\testconfig\school as the path). In this case a properly edited static void Main() entry would look like the below.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
PortableSettingsProvider.SettingsFileName = "settings.config";
PortableSettingsProvider.SettingsDirectory = "c:\\testconfig\\school";
System.IO.Directory.CreateDirectory(PortableSettingsProvider.SettingsDirectory);
PortableSettingsProvider.ApplyProvider(Properties.Settings.Default);
Application.Run(new MyTestApp());
}
3b.
If you would like the settings directory to be created in a subfolder of the applications working directory, then change the code to include the subfolder name (in this example I use settings.config as the filename and Settings as the subfolder). In this case a properly edited static void Main() entry would look like the below.
static void Main()
{
Application.EnableVisualStyles();
PortableSettingsProvider.SettingsFileName = "settings.config";
var strSettingsDirectory = Directory.GetCurrentDirectory() + "\\Settings";
System.IO.Directory.CreateDirectory(strSettingsDirectory);
PortableSettingsProvider.SettingsDirectory = strSettingsDirectory;
PortableSettingsProvider.ApplyProvider(Properties.Settings.Default);
Application.Run(new MyTestApp());
}
4.
Still in Program.cs, add the following line to the bottom of the existing using section.
using Bluegrams.Application;
5.
On the form create some controls (these will correspond to the Application Settings made in step 1).
TextBox. Name: txtFullName
TextBox. Name: txtSchool
Textbox. Name: txtClass
Checkbox. Name: chkActiveStudent
Button. Name: btnLoadSettings Text: Load Config
Button. Name: btnSaveSettings Text: Save Config
6.
Enter the code for the Load Config buttons click events (btnLoadSettings).
private void btnLoadSettings_Click(object sender, EventArgs e)
{
txtName.Text = Properties.Settings.Default.txtName.ToString();
txtSchool.Text = Properties.Settings.Default.txtSchool.ToString();
txtClass.Text = Properties.Settings.Default.txtClass.ToString();
if (Properties.Settings.Default.chkActiveStudent == true)
{
chkActiveStudent.Checked = true;
}
else
{
chkActiveStudent.Checked = false;
}
}
7.
Enter the code for the Save Config buttons click events (btnSaveSettings).
private void btnSaveSettings_Click(object sender, EventArgs e)
{
Properties.Settings.Default.txtName = txtName.Text;
Properties.Settings.Default.txtSchool = txtSchool.Text;
Properties.Settings.Default.txtClass = txtClass.Text;
if (chkActiveStudent.Checked == true)
{
Properties.Settings.Default.chkActiveStudent = true;
}
else
{
Properties.Settings.Default.chkActiveStudent = false;
}
Properties.Settings.Default.Save();
}
8.
That’s it.
Run the app.
Load the settings using the first button).
Make some changes to the text on the controls.
Save them using the second button.
If you have not created a custom filename and/or path then in your app folder there should be a new file: portable.config.
Mine is located at: C:\Users\flakie\source\repos\TestApp\TestApp\bin\Debug
You can open the file in an txt/xml editor to verify the values were set.
If you run the app again, and load settings, you should see the new values.
The Code for Saving Settings to Multiple INI Files
The following instructions are easier to implement.
They do not require you to set-up the Application Settings as they are not used.
The settings will be saved in 1 or more INI files.
The path can be changed on-the-fly (though a default is set), as can the file name for the INI file.
Again it will be using the applications own folder as the default destination (for the INI files).
You will need to modify the Form.cs file only.
The demo (from the link above) is easy to understand and was enough to provide me with the knowledge to create this example (and I am a C# novice).
9.
Install, from NuGet, the INI files package (in Solution Explorer, right-click on: References. Then Select: Manage NuGet Packages. Then search for: PeanutButter.INI. Install it).
10.
In your Form.cs file (Form1.cs if you have not changed the name), add the following line to the bottom of the existing using section.
using PeanutButter.INIFile;
11.
In your Form.cs file, directly under the line, public partial class Form1 : Form, add the following single line of code.
private IINIFile _loadedConfig;
It should look like the below.
public partial class Form1 : Form {
private IINIFile _loadedConfig;
12.
On the form create two more buttons.
Button. Name: btnOpenIniFile Text: Open INI
Button. Name: btnSaveIniFile Text: Save INI
13.
Enter the code for the Open INI buttons click event (btnOpenIniFile).
private void btnOpenIniFile_Click(object sender, EventArgs e) {
using(OpenFileDialog OpenFileIni = new OpenFileDialog()) {
var strSettingsDirectory = Directory.GetCurrentDirectory() + "\\Settings";
System.IO.Directory.CreateDirectory(strSettingsDirectory);
OpenFileIni.InitialDirectory = strSettingsDirectory;
OpenFileIni.Filter = "INI File|*.ini";
OpenFileIni.RestoreDirectory = true;
OpenFileIni.CheckFileExists = true;
OpenFileIni.CheckPathExists = true;
OpenFileIni.Title = "Open an INI Settings File";
if (OpenFileIni.ShowDialog() == DialogResult.OK)
{
_loadedConfig = new INIFile(OpenFileIni.FileName);
txtName.Text = _loadedConfig.HasSetting("UserSettings", "txtName") ? _loadedConfig["UserSettings"]["txtName"] : "";
txtSchool.Text = _loadedConfig.HasSetting("UserSettings", "txtSchool") ? _loadedConfig["UserSettings"]["txtSchool"] : "";
txtClass.Text = _loadedConfig.HasSetting("UserSettings", "txtClass") ? _loadedConfig["UserSettings"]["txtClass"] : "";
if (_loadedConfig["UserSettings"]["chkActiveStudent"] == "Checked")
{
chkActiveStudent.Checked = true;
}
else
{
chkActiveStudent.Checked = false;
}
}
}
}
14.
Enter the code for the Save INI buttons click event (btnSaveIniFile).
private void btnSaveIniFile_Click(object sender, EventArgs e)
{
using (SaveFileDialog SaveFileIni = new SaveFileDialog())
{
var strSettingsDirectory = Directory.GetCurrentDirectory() + "\\Settings";
System.IO.Directory.CreateDirectory(strSettingsDirectory);
SaveFileIni.InitialDirectory = strSettingsDirectory;
SaveFileIni.Filter = "INI File|*.ini";
SaveFileIni.Title = "Save an INI Settings File";
if (SaveFileIni.ShowDialog() == DialogResult.OK)
{
_loadedConfig = new INIFile(SaveFileIni.FileName);
_loadedConfig["UserSettings"]["txtName"] = txtName.Text;
_loadedConfig["UserSettings"]["txtSchool"] = txtSchool.Text;
_loadedConfig["UserSettings"]["txtClass"] = txtClass.Text;
if (chkActiveStudent.Checked == true)
{
_loadedConfig["UserSettings"]["chkActiveStudent"] = "Checked";
}
else
{
_loadedConfig["UserSettings"]["chkActiveStudent"] = "UnChecked";
}
_loadedConfig.Persist();
}
}
}
15.
That’s it. Run the app.
Make some changes to the text on the textbox controls. Save them using the Save INI button.
You will be prompted for a file name. It can be anything you like (but in this example I used the name of the person I setup in the first textbox.
You do not need to enter the ini file extension. You can change the location if you wish.
Make some more changes to the text in the textBoxes but do not save them.
Click on the Open INI button. Browse to the ini file you just saved and open it.
The text you just modified, without saving, should now be changed to the text you saved into the ini file.
Use OpenExeConfiguration function to read settings and then Add/Update key values before Save it back. Finally you can ConfigurationManager.RefreshSection to refresh settings of a particular section.
Example at Link
static void AddUpdateAppSettings(string key, string value)
{
try
{
var configFile = ConfigurationManager
.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error writing app settings");
}
}
my project has been an extremely fun journey so far but I am looking to save the configuration of the Server settings that it will connect (using MySQL Net/Connector).
When the application has loaded up, by default it connects to a server named 'sqlserver05' but I want the user/admin to be able to configure the server settings in a menustrip. So I navigate to the menustrip and you can click 'Configure' where another form pops up asking for server details.
I can do this just by a global string but I have to change the settings everytime the application runs. Can I not create an XML file to read the configuration settings that I just changed?
Sorry if I am not being clear. Many thanks,
Brandon
Yes, you can. An easy way to do this is to use application settings. This is an out-of-the-box implementation of (user and program) settings that is serialized to XML.
Please take a look at the ancient, but still applicable Using Settings in C#.
Effectively what you have to do:
Add a settings file to your project. Go the the Solution Explorer, right click on your project and select Properties. Then select Settings. Follow the steps there.
Create a setting. (In the following code it has the name PropertyName)
Get and set that setting in code.
string value = Properties.Settings.PropertyName; // get
Properties.Settings.Default.PropertyName = value; // set
Save the settings when you have changed anything:
Properties.Settings.Default.Save()
I think in your case it's better to use the Settings class that came with C#, take a look at these links.
1 , 2
First of all, create a simple POCO object to handle the value you wish to set, then read / write this object through a serializer.
You could use a Javascript serializer to generate a JSON file (which is more "trendy" than XML, but if you prefer XML, the mechanism remains the same) :
class DatabaseSettings
{
// Settings file path
private const string DEFAULT_FILENAME = "settings.json";
// Server name or IP
public string Server { get; set; } = "127.0.0.1";
// Port
public int Port { get; set; } = 3306;
// Login
public string Login { get; set; } = "root";
// Password
public string Password { get; set; }
public void Save(string fileName = DEFAULT_FILENAME)
{
File.WriteAllText(
fileName,
(new JavaScriptSerializer()).Serialize(this));
}
public static DatabaseSettings Load(string fileName = DEFAULT_FILENAME)
{
var settings = new DatabaseSettings();
if (File.Exists(fileName))
settings = (new JavaScriptSerializer()).Deserialize<DatabaseSettings>(File.ReadAllText(fileName));
return settings;
}
}
Usage is then the following :
// Read
var settings = DatabaseSettings.Load(/* your path */);
// update
settings.Server = "10.10.10.2";
// save
settings.Save(/* your path */);
I'm trying to save user setting in a WPF application. I want to save their Window position and size. To do so, I inspire myself of this.
I change a little the save code to do the following :
var oBaseProp = Properties.Settings.Default.Properties["baseProp"];
Properties.Settings.Default["baseProp"] = "1";
System.Configuration.SettingsProperty property = new System.Configuration.SettingsProperty("W_" + this.GetType().FullName + "_PLACEMENT"
, typeof(string), oBaseProp.Provider, false, GetPlacement(this), System.Configuration.SettingsSerializeAs.String, oBaseProp.Attributes,
false, false);
Properties.Settings.Default.Properties.Add(property);
Properties.Settings.Default["W_" + this.GetType().FullName + "_PLACEMENT"] = GetPlacement(this);
Properties.Settings.Default.Save();
BaseProp is a string property defined in my settings which is useless and just used to retrieve provider and other things.
Everything works fine for saving, I have a new file in C:\Users\christophe.mom.DOMAINE-EPSILOG\AppData\Local\Epsilog\MSSante_GUI.vshost.exe_Url_fkwxpmo4exiyrjk2vha2qu2upx5sgrvn\1.0.0.0 path, user.config that contains the desired data.
The thing is, I cannot load this file as settings file :
void StandardWindow_SourceInitialized(object sender, EventArgs e)
{
try
{
Properties.Settings.Default.Reload();
var sPlacement = (string)Properties.Settings.Default.Properties["W_" + this.GetType().FullName + "_PLACEMENT"].DefaultValue;
if (!string.IsNullOrWhiteSpace(sPlacement))
{
this.SetPlacement(this, sPlacement);
}
}
catch { }
}
I don't understand why my actual settings are not loaded. I tried in execution (not debug) mode too, and still no results.
Is someone have an idea ?
Thanks !
Well, in fact, this works only on execution mode compiled in release (in my case).
I'm Using Geckfx18.0 and xulrunner18.01. Since Geckofx share cookie and user preferences with others instance so I try to create a new profile directory to make them have unique setting but it seems to be no use. here is my code. Is there any problem with my code?
String profileDir = port.ToString();
string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Path.Combine("Geckofx", profileDir));
this.Text = directory.ToString();
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
Gecko.Xpcom.ProfileDirectory = directory;
GeckoPreferences.User["network.proxy.type"] = 1;
GeckoPreferences.User["network.proxy.socks"] = "127.0.0.1";
GeckoPreferences.User["network.proxy.socks_port"] = port;
GeckoPreferences.User["network.proxy.socks_version"] = 5;
GeckoPreferences.User["general.useragent.override"] = ua;
Are you initializing the instance of Gecko before setting the ProfileDirectory?
Note that the XpCom.ProfileDirectory is a static property, so if you're trying to start each instance, keep in mind you may be undoing the path you set previously.
Additionally, rather than settings the preferences in code, you save your user preferences out to a file via GeckoPreferences.Save(). Then you can load them back in to support diferent users via GeckoPreferences.Load().
I believe I have been taking the right approach to this so far, but I would like to have a button start a video game on my computer.
So far, I have a button linking to a process:
void button2_Click(object sender, EventArgs e)
{
process1.Start();
}
this.process1.EnableRaisingEvents = true;
this.process1.StartInfo.Domain = "";
this.process1.StartInfo.FileName = "MBO\\marbleblast.exe";
this.process1.StartInfo.LoadUserProfile = false;
this.process1.StartInfo.Password = null;
this.process1.StartInfo.StandardErrorEncoding = null;
this.process1.StartInfo.StandardOutputEncoding = null;
this.process1.StartInfo.UserName = "";
this.process1.SynchronizingObject = this;
this.process1.Exited += new System.EventHandler(this.Process1Exited);
So, where-ever I place the EXE (the one I'm coding), it will launch the "marbleblast.exe" under the subfolder MBO relative to it's location.
It seems to be working and trying to launch the game, however, it says it cannot load files that are there. I tested the game without my launcher, and it worked. I believe it's trying to run the EXE, but not letting it use the other files inside of it's folder.
I'll give more details if needed.
How can I get the game to run normally?
try adding this
this.process1.StartInfo.WorkingDirectory= "MBO\\";
or something similar to set the Working Directory.
this.process1.StartInfo.WorkingDirectory= "MBO\";
There's sloppy programming in the game, it relies on the Environment.CurrentDirectory being set right. Which by default is the same directory as where the EXE is located. The upvoted answer repeats the mistake though. To make that statement actually fix the problem, you now rely on your CurrentDirectory being set right. If it is not set where you think it is then it still won't work.
The problem with the program's current directory is that it can be changed by software that you don't control. The classic example is OpenFileDialog with the RestoreDirectory property set to the default value of false. Etcetera.
Always program defensively and pass the full path name of files and directories. Like c:\mumble\foo.ext. To get that going, start with Assembly.GetEntryAssembly().Location, that's the path to your EXE. Then use the System.IO.Path class to generate path names from that. The correct always-works code is:
using System.IO;
using System.Reflection;
...
string myDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string gameDir = Path.Combine(myDir, "MBO");
string gameExe = Path.Combine(gameDir, "marbleblast.exe");
process1.StartInfo.FileName = gameExe;
process1.StartInfo.WorkingDirectory = gameDir;
process1.SynchronizingObject = this;
process1.EnableRaisingEvents = true;
process1.Exited += new EventHandler(Process1Exited);
Set the WorkingDirectory property of the ProcessInfo to the correct directory.
I am Dobrakmato from MBForums. You simple need to add Working directory for Marble Blast.
this.process1.EnableRaisingEvents = true;
this.process1.StartInfo.Domain = "";
this.process1.StartInfo.FileName = "MBO\\marbleblast.exe";
this.process1.StartInfo.WorkingDirectory = "pathto marbleblast.exe directory";
this.process1.StartInfo.LoadUserProfile = false;
this.process1.StartInfo.Password = null;
this.process1.StartInfo.StandardErrorEncoding = null;
this.process1.StartInfo.StandardOutputEncoding = null;
this.process1.StartInfo.UserName = "";
this.process1.SynchronizingObject = this;
this.process1.Exited += new System.EventHandler(this.Process1Exited);