C #. Net write to app. config

Source: Internet
Author: User

Today I wrote a Windows exampleProgram, I am depressed enough. I haven't been in touch for too long. Write down a little gadgets for future reference.
I will not go into details when reading app. config.
It is said that Microsoft does not recommend that we write app. config dynamically, but it is inevitable that some people write app. config.
In fact, app. config is an XML file. Find the location, read it, modify it, and save it.
Important: the app. config is not running in the original directory, and the name has changed. Therefore, you must write the file at runtime During writing.
CodeAs follows:
 

/**/ ///   <Summary>
/// Set the value of a key in APP. config.
///   </Summary>
///   <Param name = "appkey"> Key </Param>
///   <Param name = "appvalue"> Value </Param>
Public Void Setvalue ( String Appkey, String Appvalue)
{
Xmldocument xdoc =   New Xmldocument ();

// The configuration file is in the program directory.
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/ " );
}

 

 

In practice, you can simply change mailsender.exe.configto another (projectname.exe. config). After compilation, you can find it in debug. Haha
Note: Most of the Code comes from the network, and others are your own experiences. Thank you for your support.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.