获取配置文件中的值
在配置文件中添加数据
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<customErrors mode="Off" />
</system.web>
<appSettings>
<add key="name1" value="AAAAAA" />
<add key="name2" value="111111" />
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
获取数据方法
- 定义一个ConfigHelper类来获取这两个数据。
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
namespace DDSDK
{
public class ConfigHelper
{
#region FetchName1
public static String Fetchname1 ()
{
return FetchValue("name1 ");
}
#endregion
#region Fetchname2 Function
public static String Fetchname2()
{
return FetchValue("name2");
}
#endregion
#region FetchValue Function
private static String FetchValue(String key)
{
String value = ConfigurationManager.AppSettings[key];
if (value == null)
{
throw new Exception($"{key} is null.请确认配置文件中是否已配置.");
}
return value;
}
#endregion
}
}