【问题标题】:How to get the file path using key from webconfig file如何使用 Web 配置文件中的密钥获取文件路径
【发布时间】:2016-06-20 14:39:17
【问题描述】:

我的 D 盘中存储了 JSON 文件。我在 web 配置文件中也提到了相同的内容。请参考以下代码

    <appSettings>
    <add key="inputFilePath" value="D:\products.json"/>
    </appSettings> 

当我尝试使用以下代码获取文件路径时,我得到空值。

    string filepath = ConfigurationManager.AppSettings["inputFilePath"];

请任何人帮助我解决这个问题

【问题讨论】:

    标签: asp.net .net json wcf c#-4.0


    【解决方案1】:

    您的代码没有问题。这表明&lt;appSettings&gt; 不在执行项目中。例如,如果您有一个 Web 项目和其他一些类库,并且该类库引用 &lt;appSettings&gt;,则该设置需要在网站的 web.config 中。如果您的类库有自己的 app.config,则不会被读取。 无论正在执行什么 - 网站、Web 表单、控制台应用程序等 - 这就是 &lt;appSettings&gt; 需要的位置,无论尝试读取什么。

    【讨论】:

      【解决方案2】:

      参考这个 - How to: Read Application Settings from the Web.config File

      System.Configuration.Configuration rootWebConfig1 =
                      System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
                  if (rootWebConfig1.AppSettings.Settings.Count > 0)
                  {
                      System.Configuration.KeyValueConfigurationElement customSetting = 
                          rootWebConfig1.AppSettings.Settings["customsetting1"];
                      if (customSetting != null)
                          Console.WriteLine("customsetting1 application string = \"{0}\"", 
                              customSetting.Value);
                      else
                          Console.WriteLine("No customsetting1 application string");
                  }
      

      //配置文件

      <appSettings>
        <add key="customsetting1" value="Some text here"/>
      </appSettings>
      

      您需要在项目的引用文件夹中添加对 System.Configuration 的引用。

      添加命名空间

      using System.Configuration;
      

      然后获取文件路径

      String path = ConfigurationManager.AppSettings["inputFilePath"];
      

      更多参考:
      AppSettings
      How to read appSettings section in the web.config file?
      Getting configuration settings from web.config/app.config using class library
      Reading settings from app.config or web.config in .net

      希望对您有所帮助。

      【讨论】:

        【解决方案3】:

        你需要这样打电话

        string filepath = ConfigurationManager.AppSettings["inputFilePath"].ToString();
        

        【讨论】:

        • 我已经尝试使用上面的代码,但我得到一个类型为“System.NullReferenceException”的异常。
        • @anithalm 你能得到字符串路径还是空值?
        • @anithalm 你的实现一定是不正确的。这绝对适用于从配置文件中检索键值。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-10
        • 2011-02-26
        • 2010-10-14
        • 2012-04-24
        • 1970-01-01
        相关资源
        最近更新 更多