C# 常用配置加载方法

一、XML文件存储配置

 

 

一般来说XML文件样式如上图 ,包含声明节点、根节点、子节点,创建XML文件也是这个流程

创建XML文件

/// <summary>
/// 创建Xml文件
/// </summary>
public void CreateXmlFile()
{
  XmlDocument doc= new XmlDocument();

  //创建类型声明节点  
  XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
  doc.AppendChild(dec);

  //创建Xml根节点  
  XmlElement root = doc.CreateElement("Roots");
  doc.AppendChild(root);

  //创建子节点
  XmlElement node= xmlDoc.CreateElement("Node");
  node.InnerText = "这是子节点内容";
  node.Value = "这是子节点的Value";   root.AppendChild(node);   
//将文件保存到指定位置   doc.Save("XmlFile\\Config.xml"); }

读取XML文件

/// <summary>
/// 加载XML配置文件
/// </summary>
/// <returns>返回List<string>类型配置信息</returns>
public static List<string> LoadXML()
{
    List<string> xmlList = new List<string>();
    try
    {
        doc.Load("XmlFile\\Config.xml");
        //获取指定节点的所有子节点
        XmlNodeList xmlNodeList = doc.SelectSingleNode("/Configs/Config").ChildNodes;
        foreach (XmlNode item in xmlNodeList)
        {
            xmlList.Add(item.InnerText);
            //xmlList.Add(item.Value);
        }
        return setList;
    }
    catch (Exception e)
    {
        Message.Show(e.Message);
        return setList;
    }
}                            

二、app.config文件存储配置

使用VS开发每一个项目都会有一个app.config文件,可以把配置信息写进这个文件

在使用之前需要先引用System.Configuration

 可以手动在app.config添加appSettings节点,添加 key/value 信息存储配置信息

读取配置信息

 /// <summary>
/// 初始化配置信息(设备IP&端口以及引用服务的地址&站别)
/// </summary>
private void InitConfig()
{
    try
    {
        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        plcIP = configuration.AppSettings.Settings["plcIP"].Value;
        plcPort = configuration.AppSettings.Settings["plcPort"].Value;
        cIP = configuration.AppSettings.Settings["cIP"].Value;
        cPort = configuration.AppSettings.Settings["cPort"].Value;
        apiAddress = configuration.AppSettings.Settings["apiAddress"].Value;
        apiStation = configuration.AppSettings.Settings["apiStation"].Value;
        arriveAdrs = ushort.Parse(configuration.AppSettings.Settings["arriveAdrs"].Value);
        signalAdrs = ushort.Parse(configuration.AppSettings.Settings["signalAdrs"].Value);
        sizeAdrs = ushort.Parse(configuration.AppSettings.Settings["sizeAdrs"].Value);
        isSendSignal = bool.Parse(configuration.AppSettings.Settings["isSendSignal"].Value);
    }
    catch (Exception e)
    {
        _logger.Debug("初始化配置异常:" + e.Message);
    }
}

.net core里面的配置文件好像不一样,是叫appsetting.json,一般会将数据库连接字符串存到里面,样式如下

 获取数据库连接字符串

//获取数据库连接字符串
private void GetConnectStr()
{
     var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
    var config = builder.Build();
    string connectionstring = config.GetConnectionString("DefaultConnection");   
}

 

posted on 2023-09-25 16:17  othersheart  阅读(257)  评论(0编辑  收藏  举报