tags:

views:

76

answers:

2

Hi Everyone,

I'm wondering what is the easiest way to persist a string value, once the form and program are shutdown that I want to use again later when they open the program and form later. In my case I'm using a FolderBrowserDialog and saving the directory the user picks.

I know I can use File.IO and such, but just wondering what everyone thinks is the easiest/most efficient/ least lines of code.

Thanks!

+7  A: 

Application Settings are nice and easy to use.

  1. Right click on your project and select "Properties"
  2. Go to the "Settings" tab (Click to link to create a new file if one hasn't been created)
  3. Give your new settings a name and default value (ie "MySavedDirectory")
  4. Access your setting from code:

-

private string folder;
private void Form1_Load(object sender, EventArgs e)
{
  this.folder = Properties.Settings.Default.MySavedDirectory;
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
  Properties.Settings.Default.MySavedDirectory = this.folder;
  Properties.Settings.Default.Save();
}
heavyd
eschneider
Yes, you are correct, user settings are more suitable
heavyd
Thanks! That worked perfectly. Amazing how this has been driving me bonkers for the last couple hours.
Jason More
A: 

There is the built-in Settings feature. You can configure the settings via the property pages for the project and then access them from code via Properties.Settings. But I have had some problems with this approach. For one thing, the file is saved in a location that you can't choose with a name you can't choose. And IIRC, that location/filename changes base on the location from which you run the application. Plus you don't control the format of the file. In addition to those shortcomings, I've experienced some sort of file corruption that causes exceptions when the settings are accessed. The fix is to have the user locate and delete the settings file.

I don't use the Settings feature anymore. I prefer JSON-serialized text files that I can save wherever I like. File.IO is certainly nothing to shy away from and neither is JSON serialization. I'm sure you can find a ton of great examples of both of those on this site.

Fantius