2015-08-27 56 views
-1

我必須在C#中設置 - >值中獲取字符串。如何通過代碼到達那裏並從App.config文件中獲取該值。請幫幫我。謝謝。我想在C#中獲得App.config文件的不同標籤

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
<configSections> 
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" > 
    <section name="MyApplication.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> 
</sectionGroup> 
</configSections> 

<startup> 
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> 
</startup> 


<applicationSettings> 
<MyApplication.Properties.Settings> 

    **<setting name="ConnectionString" serializeAs="String"> 
    <value>server=127.0.0.1;uid=root;pwd=root;database=MyApplication_db;</ 
    </setting>** 

</VASI_Application.Properties.Settings> 
</applicationSettings> 


</configuration> 

回答

1

您可以使用下面的代碼:

var section = (ClientSettingsSection)ConfigurationManager.GetSection("applicationSettings/MyApplication.Properties.Settings"); 
var settingElement = section.Settings.Get("ConnectionString"); 
var settingValue = settingElement.Value.ValueXml.InnerText; 

// settingValue equals "server=127.0.0.1;uid=root;pwd=root;database=MyApplication_db;" 

首先,您檢索ClientSettingsSection部分。該部分的名稱是"applicationSettings"部分的名稱與其內部"MyApplication.Properties.Settings"部分的組合。然後,通過在返回的ClientSettingsSection實例上調用Settings.Get("ConnectionString")來檢索實際設置。最後,您可以使用返回設置的Value.ValueXml.InnerText屬性來獲取實際值。

順便說一句,你有你的XML文件中的兩個小錯誤:

  1. </VASI_Application.Properties.Settings>
  2. 正常關閉的<MyApplication.Properties.Settings>元素<value>元素不能正確地與</value>
關閉
0

難道你沒有屬性ConnectionString?

如記錄here,通常你可以用這種方式訪問​​它:

var setting = Properties.Settings.Default.ConnectionString;

順便說一句,你的應用程序標籤與MyApplication.Properties.Settings啓動,但如果你真的想與VASI_Application.Properties.Settings

相關問題