gpt4 book ai didi

C# 配置文件

转载 作者:太空狗 更新时间:2023-10-29 23:04:44 27 4
gpt4 key购买 nike

好吧,我之前发布了如何读取其他程序的其他配置文件(这里是链接 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"

最佳答案

好吧,调试了将近 5 个小时,我自己弄明白了,妈的!

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

谢谢大家,ChrisF、Eoin Campbell 和 pablito。

关于C# 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/939074/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com