2015-06-21 41 views
2

我試圖從窗戶保存表單到的app.config以下設置在.NET應用WF保存到mailSettings在App.Config中

<system.net> 
    <mailSettings> 
    <smtp from="[email protected]"> 
    <network host="ops01" port="25" defaultCredentials="true"/> 
    </smtp> 
    </mailSettings> 
</system.net> 

我嘗試使用下面的代碼來設置但是,我收到配置是隻讀的錯誤。

private void SaveMailSettings() 
{ 
    var smtpSection = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection; 
    try 
    { 
     if (smtpSection == null) return; 
     smtpSection.Network.Host = txtSmtpHost.Text; 
     smtpSection.Network.Port = Convert.ToInt32(txtSmtpPort.Text); 
     smtpSection.From = txtSmtpFrom.Text; 
     if (smtpSection.Network.UserName != null) smtpSection.Network.UserName = txtSmtpUserName.Text; 
     if (smtpSection.Network.Password != null) smtpSection.Network.Password = txtSmtpPassword.Text; 
     Logger.Log(string.Format("Host: {0}, Port: {1}, From: {2}, UserName: {3}, Password: {4}", smtpSection.Network.Host, smtpSection.Network.Port, smtpSection.Network.UserName, smtpSection.Network.Password), "INFO"); 
    } 
    catch (Exception ex) 
    { 
     Logger.Log(ex.Message, "ERROR:"); 
    } 
} 

有沒有什麼辦法可以更新App.Config文件mailSettings?

+0

可能重複http://stackoverflow.com/questions/4100215/how-to-programmatically-store-save- smtp-server-details-back-to-web-config) –

+0

我試過了,無法啓動它。 – Nim

+0

對不起,引用的問題是在web項目 –

回答

3

無法通過ConfigurationManager.GetSection

編輯配置文件,你應該打開文件,並進行修改和保存文件。

注意:不要在調試模式下測試。我不知道爲什麼更改不在調試模式下保存。但是當正常運行保存的.exe文件更改時。

var webConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
var settings =(MailSettingsSectionGroup)webConfig.GetSectionGroup("system.net/mailSettings"); 
webConfig.AppSettings.Settings["test"].Value = "asdad"; 
SmtpSection smtp = settings.Smtp; 
SmtpNetworkElement net = smtp.Network; 
net.Port = 2005; 
net.Host = "localhostEditedEdited"; 
webConfig.Save(ConfigurationSaveMode.Modified); 
的【如何以編程方式保存(保存)SMTP服務器詳細信息回的web.config(
+0

非常感謝,我不得不刪除測試設置,但除了核心工作。 – Nim