我的App.Config中已经有了一个名为“App.Config”的键,如下所示:
<setting name="Alert_Sound_File" serializeAs="String">
<value />
</setting>我的按钮是这样的:
public OpenFileDialog dialog1 = new OpenFileDialog();
private void browseSoundToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result = dialog1.ShowDialog();
dialog1.Title = "Browse to find sound file to play first sound";
dialog1.InitialDirectory = @"c:\";
dialog1.Filter = "Wav Files (*.wav)|*.wav";
dialog1.FilterIndex = 2;
dialog1.RestoreDirectory = true;
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
app.Settings["Alert_Sound_File"].Value = dialog1.FileName;
config.Save(ConfigurationSaveMode.Modified);
}目前我遇到的错误是:
“对象引用未设置为对象的实例。”
但是在按钮中设置了dialog1.FileName,如何获得返回的空值?
我甚至尝试过这个测试&这不会保存到我的App.Config中。
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("y", "this is Y");
config.Save(ConfigurationSaveMode.Modified);更新:我添加了
<appSettings>
<add key="Alert_Sound_File" value="" />
<add key="Error_Sound_File" value="" />
到我的App.Config文件中,并将其放在我的按钮中:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
if (result == DialogResult.OK)
{
app.Settings["Alert_Sound_File"].Value = dialog1.FileName;
config.Save(ConfigurationSaveMode.Modified);
}结果是,我不再获得对象引用错误,但是声音文件没有被添加到App.Config文件中。但我没有任何错误!
发布于 2016-06-22 13:47:34
请尝试这样做,以确保您之前选择了一个文件:
if (result == DialogResult.OK) {
app.Settings["Alert_Sound_File"].Value = dialog1.FileName;
config.Save(ConfigurationSaveMode.Modified);
}发布于 2016-06-22 14:27:02
将app.config文件更改为:
<configuration>
<appSettings>
<add key="Alert_Sound_File" value="" />
</appSettings>
</configuration>您需要在上一篇文章中以wrotes形式检查对话框结果,因为如果用户单击cancel字段被擦除(可能真的需要吗?)
为了保存,您需要在修改后的设置值之后调用save方法:
config.Save(ConfigurationSaveMode.Modified);https://stackoverflow.com/questions/37969459
复制相似问题