2016-03-07 70 views
2

我有JSON文件存储在我的D驱动器。我在web配置文件中提到过相同的内容。请参考下面的代码如何从webconfig文件中使用密钥获取文件路径

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

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

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

请任何一个可以帮助我在此

回答

0

,你需要这样的

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

我已经尝试使用上面的代码,但我得到一个'System.NullReferenceException'类型的异常。 –

+0

@anithalm你能够获得stringpath还是为null值? – Webruster

+0

@anithalm您的实施必须是不正确的。这绝对适用于从配置文件中检索关键值。 – Webruster

0

调用参考本 - 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

希望得到这个帮助。

0

你的代码没有问题。这表明<appSettings>不在正在执行的项目中。例如,如果您有一个Web项目和一些其他类库,并且类库指向<appSettings>,那么该设置需要位于网站的web.config中。如果你的类库有它自己的app.config,它不会被读取。无论执行什么 - 网站,网页表单,控制台应用程序等, - 这就是<appSettings>需要的地方,无论试图阅读什么内容。