2010-11-24 193 views
1

我知道如何獲得一個句柄並寫入到這一點:C#寫入App.config文件

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <appSettings> 
    <add key="Param1" value="" /> 
    <add key="Param2" value="" /> 
    <add key="Param3" value="" /> 
    </appSettings> 
</configuration> 
時,它的結構是這樣大約

可是什麼?

<configuration> 
    <userSettings> 
     <MyEXEName.Properties.Settings> 
      <setting name="some_setting" serializeAs="String> 
       <value>some value</value> 
      </setting> 
     </MyEXEName.Properties.Settings> 
    </userSettings> 
</configuration> 
+1

你可以嘗試使用ConfigurationManager.GetSection,雖然我不確定這樣的結構可以訪問它。我只使用了鍵/值結構,與appSettings相同,並且工作正常。 – 2010-11-24 16:31:36

回答

0

.Net Framework和Visual Studio非常友好,可以在您的應用程序名稱空間上生成一個靜態的Properties類。您可以通過此類訪問和設置用戶設置。考慮到設置值保存在用戶的漫遊配置文件中,所以即使應用文件夾中的配置文件具有某些設置,用戶設置也會保存在%USERPROFILE%\AppData的某處。

繼提供的信息,您可以訪問屬性,如:

MyEXEName.Properties.Settings.some_setting = "new value"; 
+0

我有這些在設置中,你是正確的。當代碼通過MSI部署時,我想更改app.config。我有一個自定義安裝程序類,它從安裝程序的自定義文本輸入屏幕獲取用戶輸入的值。當程序運行時,你說MyEXE.app.config值不被使用? – 2010-11-24 16:46:25

1

然後你想要Application Settings

這裏(從MSDN解除)的例子:

public class MyUserSettings : ApplicationSettingsBase 
{ 
    [UserScopedSetting()] 
    [DefaultSettingValue("white")] 
    public Color BackgroundColor 
    { 
     get 
     { 
      return ((Color)this["BackgroundColor"]); 
     } 
     set 
     { 
      this["BackgroundColor"] = (Color)value; 
     } 
    } 
} 

然後你可以使用它像這樣:

MyUserSettings mus; 

private void Form1_Load(object sender, EventArgs e) 
{ 
    mus = new MyUserSettings(); 
    mus.BackgroundColor = Color.AliceBlue; 
    this.DataBindings.Add(new Binding("BackColor", mus, "BackgroundColor")); 
} 

void Form1_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    mus.Save(); 
} 

我建議你閱讀MSDN上的整體部分,不過,因爲它提供了很多有用的信息。

0
string someSetting = Settings.Default.some_setting; 

此文件由VS自動生成你可以在項目 - >屬性 - > Settings.settings打開它。 執行應用程序時注意,此設置保存在%APPDATA%(應用程序用戶文件夾)中(因爲%APPDATA%中的文件夾具有隨機名稱,所以可以搜索* .config)。