C# 配置文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/939074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:47:43  来源:igfitidea点击:

C# Configuration Files

c#.netfileconfig

提问by akif

Okay, so a while ahead I posted how to read other config files of other programs (here is the link Previous Post. I managed to do it. But now there is another problem. The scenario is like this, I have two programs. Program Areads its configuration from a config file and program Bis only used to modify the contents of the config file which Areads. The name of the config file is email.config. It is in the same directory in which program A& Bresides.

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

The problem is that I get path of a file for attachment using open file dialog. If the path points to a file in the same directory, the program works perfect! But if it points to a file outside the directory it throws an exception of type System.NullReferenceException.

问题是我使用打开文件对话框获取附件文件的路径。如果路径指向同一目录中的文件,则程序运行完美!但如果它指向目录外的文件,则会引发System.NullReferenceException类型的异常。

Here is the code

这是代码

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();
    }
}

The content of email.configis:

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>

What am I doing wrong here?

我在这里做错了什么?

EDIT:The value of configFileNameis "email.config"

编辑:configFileName的值是“email.config”

采纳答案by akif

Well, I figured it out myself after debugging for almost 5 hours, Damn!

好吧,我在调试了将近 5 个小时后自己弄明白了,该死!

The problem was when I used OpenFileDialog to get the file path, it changed the current directory to the one which is selected in the dialog, so the program couldn't find the config file. All I did was to set the RestoreDirectory property of OpenFileDialog to true and poofit worked

问题是当我使用 OpenFileDialog 获取文件路径时,它将当前目录更改为对话框中选择的目录,因此程序找不到配置文件。我所做的只是设置的OpenFileDialog到真正的RestoreDirectory性质和它的工作

Thanks everyone, ChrisF, Eoin Campbell and pablito.

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

回答by ChrisF

Are you accessing the file by its full path or just the file name?

您是通过完整路径还是仅通过文件名访问文件?

If the latter then this will work when the file is in the same folder as the executable, but not otherwise.

如果是后者,则当文件与可执行文件位于同一文件夹中时,这将起作用,否则就不起作用。

UPDATE

更新

It looks as though things are more complicated than I first thought and this doesn't seem to be the issue here - see the comments. The line that's raising the exception is:

看起来事情比我最初想象的要复杂,这似乎不是这里的问题 - 请参阅评论。引发异常的行是:

externalConfig.AppSettings.Settings["ServerAddress"].Value = serverAddr;

So that means that there's a null reference somewhere along the chain. If you can identify which it is then that should give you a pointer to the problem.

所以这意味着在链的某处有一个空引用。如果您能确定它是哪个,那么这应该会给您一个指向问题的指针。

回答by Eoin Campbell

What code are you using to get the FileName and Path back from the OpenFileDialog.

您使用什么代码从 OpenFileDialog 中获取 FileName 和 Path。

Is it a fully qualified path to the file ?

它是文件的完全限定路径吗?

e.g.

例如

openFileDialog1.FileName; //Contains "C:\Path\To\The\File.txt"

By the sounds of it, whats being saved is only a filename, so your application is only looking in the current path.

听上去,被保存的只是一个文件名,所以你的应用程序只在当前路径中查找。

回答by Pablo Retyk

I had the same problem, I don't know if this can help you but when I changed the name of the config file, which was in another folder as in your case, to .config and it didn't crash anymore, in my case I could change the name so I didn't continue the investigation how to make it work with other name, but of course I would like to know.

我遇到了同样的问题,我不知道这是否可以帮助您,但是当我将配置文件的名称(与您的情况一样位于另一个文件夹中)更改为 .config 并且它不再崩溃时,在我的如果我可以更改名称,因此我没有继续调查如何使其与其他名称一起使用,但我当然想知道。

回答by Andrew Rokicki

externalConfig.AppSettings.Settings["SSL"].Value = ssl.ToString();

Config file does not contain "SSL"

配置文件不包含“SSL”

just my 2c for those that are trying this code.

对于那些正在尝试此代码的人,只是我的 2c。