如何使用webconfig文件中的密钥获取文件路径

时间:2016-03-07 05:56:48

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

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

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

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

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

请任何人帮助我

3 个答案:

答案 0 :(得分:0)

你需要像这样打电话

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

答案 1 :(得分: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

希望得到这个帮助。

答案 2 :(得分:0)

您的代码没有任何问题。这表明Undefined DSC resource 'MyCustomResource'. Use Import-DSCResource to import the resource. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : ResourceNotDefined 不在执行项目中。例如,如果您有一个Web项目和一些其他类库,并且类库引用<appSettings>,则该设置需要位于网站的web.config中。如果您的类库有自己的app.config,则不会被读取。 无论执行什么 - 网站,网络表单,控制台应用程序等 - 这都是<appSettings>需要的地方,无论是什么尝试阅读它。