好的,所以提前我发布了如何读取其他程序的其他配置文件(这是链接Previous Post。我设法做到了。但现在还有另一个问题。场景是这样的,我有两个程序。程序A从一个配置文件中读取自己的配置,程序B只用来修改A读取的配置文件的内容,配置文件名为email.config,与程序A & B所在目录相同.
问题是我使用打开文件对话框获取附件的文件路径。如果路径指向同一目录中的文件,则程序完美运行!但是,如果它指向目录之外的文件,则会引发System.NullReferenceException类型的异常。
这是代码
private void saveBtn_Click(object sender, EventArgs e)
{
try
{
// save everything and close
string attachment = attachTxtBox.Text;
var configMap = new ExeConfigurationFileMap { ExeConfigFilename = configFileName };
// it throws exception here when
// the path points to a file outside the exes directory
Configuration externalConfig = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
externalConfig.AppSettings.Settings["ServerAddress"].Value = serverAddr;
externalConfig.AppSettings.Settings["Port"].Value = port;
externalConfig.AppSettings.Settings["SSL"].Value = ssl.ToString();
externalConfig.AppSettings.Settings["Sender"].Value = senderAddr;
externalConfig.AppSettings.Settings["SenderPassword"].Value = password;
externalConfig.AppSettings.Settings["Subject"].Value = subject;
externalConfig.AppSettings.Settings["AttachmentPath"].Value = attachment;
externalConfig.AppSettings.Settings["Body"].Value = messageBody;
// Save values in config
externalConfig.Save(ConfigurationSaveMode.Full);
Application.Exit();
}
catch (System.Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
Application.Exit();
}
}
email.config的内容是:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="">
<clear />
<add key="ServerAddress" value="" />
<add key="Port" value="" />
<add key="Sender" value="" />
<add key="SenderPassword" value="" />
<add key="Subject" value="" />
<add key="AttachmentPath" value="" />
<add key="Body" value="" />
</appSettings>
</configuration>
我在这里做错了什么?
编辑:configFileName的值为“ email.config”