如何在窗口应用程序c#中更改app.config文件

时间:2012-12-08 06:58:35

标签: c# .net windows-applications

我有一个窗口应用程序,我在其中使用了电子邮件功能,并且电子邮件设置位于app.config文件中。如下所示

<system.net>
<mailSettings>
  <smtp from="email@gmail.com">
    <network host="smtp.gmail.com" port="587" userName="username" password="password" enableSsl="true" />

  </smtp>
</mailSettings>
</system.net>

我想使用上面部分的编码进行更改..我必须通过配置文件中的smtp和网络部分进行编码。

2 个答案:

答案 0 :(得分:0)

我认为你问的是如何以编程方式执行此操作?

这里有一个答案:

Sending email through Gmail SMTP server with C#

也是msdn网站上的一个很好的例子:

http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx

如果这不是您要求的,请告诉我..

修改:在问题明确后显示答案:

How can I read/write app.config settings at runtime without using user settings?

祝你好运

答案 1 :(得分:0)

我找到了解决方案......

 FileInfo objFileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location + ".config");
            XmlDocument objXmlDoc = new XmlDocument();
            objXmlDoc.Load(objFileInfo.FullName);
            XmlElement objElement = objXmlDoc.DocumentElement;
            XmlNode objAppSettingNode = objElement.SelectSingleNode("appSettings");

            foreach (XmlNode appSetting in objAppSettingNode)
            {
                if (appSetting.Name.Equals("add"))
                {
                    appSetting.Attributes["value"].Value = txtEmailAddress.Text.Trim();
                }

            }

            XmlNode objMailSettingNode = objXmlDoc.DocumentElement.SelectSingleNode("system.net/mailSettings");
            if (objMailSettingNode != null)
            {
                foreach (XmlNode childNode in objMailSettingNode)
                {
                    if (childNode.Name.ToLower().Equals("smtp"))
                    {
                        childNode.Attributes["from"].Value = txtEmailAddress.Text.Trim();
                        foreach (XmlNode networkNode in childNode)
                        {
                            if (networkNode.Name.ToLower().Equals("network"))
                            {
                                networkNode.Attributes["host"].Value = txtSmtp.Text.Trim();
                                networkNode.Attributes["userName"].Value = txtEmailAddress.Text.Split('@')[0].Trim();
                                networkNode.Attributes["password"].Value = txtPassword.Text.Trim();
                                networkNode.Attributes["port"].Value = txtPort.Text.Trim();
                            }
                        }
                    }
                }
            }

            objXmlDoc.Save(objFileInfo.FullName);
            lblErrormsg.Text = string.Empty;
            this.Close();