2016-03-07 54 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>需要的地方,無論試圖閱讀什麼內容。

相關問題