Saving & Loading Application Settings in C#

If your application uses application settings that are the scope of “User”, in C# you will need to add code that will save and load these settings during shutdown and startup (this is automatic when using VB.NET).

In your Main() method of the Program.cs file add the first two lines below to load the settings and setup an event for saving:

[STAThread]
  static void Main()
  {
    HelloWorld.Properties.Settings.Default.Reset();
    Application.ApplicationExit +=
      new EventHandler(Application_ApplicationExit);
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
  }

Then add this method to save the settings during application shutdown:

static void Application_ApplicationExit(object sender, EventArgs e)
{
  HelloWorld.Properties.Settings.Default.Save();
}

Tip By: David McCarter

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s