简体   繁体   English

如何在C#中使用应用程序配置文件?

[英]How to use application config file in C#?

I am trying to use a config file in my C# console application. 我试图在我的C#控制台应用程序中使用配置文件。 I created the file within the project by going New --> Application Configuration File, and naming it myProjectName.config. 我通过转到New - > Application Configuration File并将其命名为myProjectName.config在项目中创建了该文件。 My config file looks like this: 我的配置文件如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SSDirectory" value="D:\Documents and Settings\****\MyDocuments\****" />
</appSettings>
</configuration>

The code to access it looks like this: 访问它的代码如下所示:

private FileValidateUtil()
    {
        sSDirFilePath = ConfigurationSettings.AppSettings["SSDirectory"];
        if (sSDirFilePath == null)
            Console.WriteLine("config file not reading in.");
    }

Can anyone lend a hint as to why this is not working? 任何人都可以提示为什么这不起作用? (I am getting the error message.) (我收到错误消息。)

Thanks!! 谢谢!!

badPanda badPanda

You can't change the name from app.config and expect ConfigurationManager to find it without providing it more information. 您无法从app.config更改名称,并希望ConfigurationManager在不提供更多信息的情况下找到它。 Change the name of myProjectName.config back to app.config, rebuild, and you will see a file in the bin folder called myProjectName.exe.config. 将myProjectName.config的名称更改回app.config,rebuild,您将在bin文件夹中看到名为myProjectName.exe.config的文件。 Then your call to ConfigurationManager.AppSettings should work correctly. 然后您对ConfigurationManager.AppSettings的调用应该正常工作。

First off, use ConfigurationManager instead of ConfigurationSettings . 首先,使用ConfigurationManager而不是ConfigurationSettings

Second, instead of saying "doesn't work", which provides no useful information, tell us what you're seeing. 其次,而不是说“不起作用”,它没有提供有用的信息,而是告诉我们你所看到的。 Does it compile? 它编译? Does it throw an exception at runtime? 它是否在运行时抛出异常? Does your PC start to smoke and smell like melting plastic? 你的电脑是否开始吸烟,闻起来像融化的塑料?

Try this: 尝试这个:

    public string GetSSDirectory()
    {
        string sSDirFilePath = string.Empty;

        if (!ConfigurationManager.AppSettings.AllKeys.Contains("SSDirectory"))
        {
            Console.WriteLine("AppSettings does not contain key  \"SSDirectory\"");
        }
        else
        {
            sSDirFilePath = ConfigurationManager.AppSettings["SSDirectory"];
            Console.WriteLine("AppSettings.SSDirectory = \"" + sSDirFilePath + "\"");
        }

        return sSDirFilePath;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM