C#配置文件

aki*_*kif 5 .net c# config file

好的,所以提前一段时间我发布了如何阅读其他程序的其他配置文件(这里是链接上一篇文章.我设法做到了.但是现在还有另外一个问题.场景是这样的,我有两个程序.程序A从配置文件读取其配置,程序B仅用于修改A读取的配置文件的内容.配置文件的名称是email.config.它位于程序AB所在的目录中.

问题是我使用打开文件对话框获取附件文件的路径.如果路径指向同一目录中的文件,则程序运行完美!但如果它指向目录外的文件,则会抛出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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

编辑:configFileName的值是"email.config"

aki*_*kif 5

好吧,经过近5个小时的调试,我自己想出来了,该死的!

问题是当我使用OpenFileDialog获取文件路径时,它将当前目录更改为在对话框中选择的目录,因此程序找不到配置文件.我所做的就是将OpenFileDialog的RestoreDirectory属性设置为true,并将其设置为poof

谢谢大家,ChrisF,Eoin Campbell和pablito.

  • 你*想出来了;-)抱歉无法抗拒:) (3认同)