SoFunction
Updated on 2025-04-06

c# NameValueCollection class reads configuration information

I will first introduce the writing method in the configuration file:
1.Create a config file under the project in VS2005, name is, and edited as follows:
Copy the codeThe code is as follows:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section
name="StartParameters"
type=",System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</configSections>
<StartParameters>
<add key="IPAddress" value="127.0.0.1"/>
<add key="Port" value="13000"/>
</StartParameters>
</configuration>

The name value of the section node is defined by itself. Here I define it as "StartParameters", then add the node declared above, and add two test items "<add key="IPAddress" value="127.0.0.1"/>" and "<add key="Port" value="13000"/>" inside the node; the configuration file is defined.

2. Open the code file to read the configuration information and add two references, namely:
Copy the codeThe code is as follows:

using ;
using ;

Define a variable of type NameValueCollection:
Copy the codeThe code is as follows:

NameValueCollection _table = null;
_table = (NameValueCollection)("StartParameters");
String ipAddress =_table["IPAddress"].ToString();
String port = _table["Port"].ToString();

The "StartParameters" in the previous sentence is the name value defined in the configuration file.
The output values ​​of ipAddress and port are:
Copy the codeThe code is as follows:

“127.0.0.1”
“13000”