How to retain the Properties.Settings.Default.ApplicationData after closing and re-opening the application
I’ve a windows forms desktop application which keeps contact details. The application stores contacts data as below when closing the application,
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
Properties.Settings.Default.ApplicationData = mydata;
Properties.Settings.Default.Save();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When application starts it load data as below,
try
{
this.mydata = (DataHandeler) Properties.Settings.Default.ApplicationData;
}
catch (NullReferenceException)
{
mydata = new DataHandeler();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
mydata = new DataHandeler();
}
SettingsSerializeAs has been added into Settings.Designer.cs as below,
[global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.SettingsSerializeAs( System.Configuration.SettingsSerializeAs.Binary)]
public object ApplicationData {
get {
return ((object)(this["ApplicationData"]));
}
set {
this["ApplicationData"] = value;
}
But application cannot recover already stored data after each time I close and re-open the applicatio开发者_JAVA百科n. Nullreferenceexception is thrown when application trying to load data. How can I recover the data?
Is there an exception being thrown when the settings are saved or loaded?
Are the settings actually being saved to the file? On Windows Vista or 7, there should be a user.config file in a directory named something like:
C:\Users\{user_name}\AppData\Roaming\Microsoft\{project_or_assembly_name}\{version_number}\user.config
Is your DataHandeler
class serializable?
This MSDN thread might also help.
after changing your settings just call the save method in the setings
like this
Properties.Settings.Default.AppLaststarted = date;
Properties.Settings.Default.Save();
this will save the app.config files so that it will use new settings.
Note that there are 2 kinds of application settings with different scope. User level settings are not saved in app.config file and it is not possible to save Application level settings as I know.
精彩评论