该类 实现了 自动创建 一个 APP.CONFIG 功能
注意 因为使用了 Configuration 所以需要在项目里面添加
///
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Xml;
using System.IO;
namespace mySerialPort.Com
{
public static class MyConfig
{
public static void ConfigInit()
{
string Filename =System.Environment.CurrentDirectory + "\\app.config";
if (File.Exists(Filename) != true)
{
SetVaule("ServerIp", "192.168.1.126"); // 包含了 自动创建 的功能
SetVaule("ServerPort", "1261");
}
}
///<summary>
///返回*.exe.config文件中appSettings配置节的value项
///</summary>
///<param name="strKey"></param>
///<returns></returns>
public static string GetVaule(string strKey)
{
ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "app.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
foreach (string key in config.AppSettings.Settings.AllKeys)
{
if (key == strKey)
{
return config.AppSettings.Settings[strKey].Value.ToString();
}
}
return null;
}
///<summary>
///在*.exe.config文件中appSettings配置节增加一对键值对
///</summary>
///<param name="newKey"></param>
///<param name="newValue"></param>
public static void SetVaule(string newKey, string newValue)
{
ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "app.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
bool exist = false;
foreach (string key in config.AppSettings.Settings.AllKeys)
{
if (key == newKey)
{
exist = true;
}
}
if (exist)
{
config.AppSettings.Settings.Remove(newKey);
}
config.AppSettings.Settings.Add(newKey, newValue);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
public static void testc()
{
MyConfig.SetVaule("path", "");
// cancle.WriteLine(MyConfig.GetVaule("path"));
}
}
}