2013-08-28 16 views
10

appSettingsにハードコードで与えたlogFilePath値を取得したいとします。私はMVC4のweb.configから文字列値を取得する方法

System.Configuration.Configuration rootWebConfig1 = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null); 
System.Configuration.KeyValueConfigurationElement customSetting = rootWebConfig1.AppSettings.Settings["azureLogUrl"]; 
string pathValue = customSetting.Value; 

でキー値に到達しようとしていますが、私はnull参照例外を取得しています。 web.configファイルから値を取得するにはどうすればよいですか?

答えて

43

用途:

値Web.configファイルののappSettings要素から読み取る のとおりです。

string pathValue = ConfigurationManager.AppSettings["azureLogUrl"]; 

あなたは、文字列にこれをキャストして、ドキュメントの状態があるため、ヌルをチェックする必要はありません。常にString型です。指定したキーが Web.configファイルに存在しない場合、エラーは発生しません。代わりに、空の文字列は が返されます。

+1

System.Configurationを使用して追加する必要があります。 – redwards510

2

あなたはこのようにweb.configファイルから値を取得することができます

string pathValue = WebConfigurationManager.AppSettings["azureLogUrl"].ToString(); 
関連する問題