c#.net寫入app.config

來源:互聯網
上載者:User

今天寫了個 windows的小程式,把我鬱悶了夠戧.太久沒有接觸了。就把一點兒小玩意兒寫下來,以方便大家以後查閱.
讀取app.config就不贅述了,主要說說寫入app.config.
據說微軟不太建議我們動態寫入app.config的,但是不可避免的有人因為業務或其他需要就非要寫入app.config.
其實app.config就是個xml檔案,找到位置,讀出來,改了,然後儲存回去,就行了。
重要一點:app.config運行時就不在原來的目錄下了,名稱也變了。所以在寫入時一定要寫運行時那個檔案.
代碼如下:
 

       /**//// <summary>
        /// 設定app.config中的某個key的value.
        /// </summary>
        /// <param name="AppKey">key</param>
        /// <param name="AppValue">value</param>
        public  void  SetValue(string AppKey, string AppValue)
        {
            XmlDocument xDoc = new XmlDocument();

            //此處設定檔在程式目錄下
            xDoc.Load(Application.StartupPath + "file://MailSender.exe.config/");
            XmlNode xNode;
            XmlElement xElem1;
            XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("//appSettings");
            xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
            if (xElem1 != null)
            {
                xElem1.SetAttribute("value", AppValue);
            }
            else
            {
                xElem2 = xDoc.CreateElement("add");
                xElem2.SetAttribute("key", AppKey);
                xElem2.SetAttribute("value", AppValue);
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(Application.StartupPath + "file://MailSender.exe.config/");
        }

 

 

其實挺簡單的,大家用時只需要把那個MailSender.exe.config改成自己的就行了(ProjectName.exe.config),編譯後去debug裡找一般都能找到.哈哈
備忘:代碼大部分來自網路,其它是自己的心得.謝謝大家支援.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.