C# 之 管理配置文件(三)

        通过上两篇博客《C# 之 管理配置文件(一)》和《C# 之 管理配置文件(二)》给大家介绍了一下对我们传统的app.config或者web.config配置文件和ini文件中配置变量的读取和写入,今天继续来给大家介绍一下对xml文件中配置变量的读取和写入。


        首先我们创建一个Test.xml的文件,其内容为:

<?xml version="1.0" encoding="gb2312"?>
<CONFIG>
  <DateTime>2015/10/21 17:06:38</DateTime>
</CONFIG>

        编写读取和写入方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace ConsoleApplication2
{
    public static class XmlHelper
    {
        //获取xml文件中某节点的值
        public static string GetConfig(string sNode)
        {
            string s_File = System.Environment.CurrentDirectory;
            s_File = s_File.Replace('\\', '/');
            s_File = s_File.Substring(0, s_File.Substring(0, s_File.LastIndexOf('/')).LastIndexOf('/'));
            s_File = s_File + "/Test.xml";

            System.Xml.XmlDocument objXmlDoc = new System.Xml.XmlDocument();

            System.IO.FileInfo fif;

            fif = new System.IO.FileInfo(s_File);
            if (!fif.Exists)
            {
                return "Error:Test.xml";
            }
            try
            {
                objXmlDoc.Load(s_File);
                return objXmlDoc.SelectSingleNode("/CONFIG/" + sNode).InnerText.Replace("\r\n", "");
            }
            catch
            {
                return "Error:Test.xml";
            }
        }


        //更新xml文件中某节点的值
        public static void WriteConfig(string sNode, string sContent)
        {
            string s_File = System.Environment.CurrentDirectory;
            s_File = s_File.Replace('\\', '/');
            s_File = s_File.Substring(0, s_File.Substring(0, s_File.LastIndexOf('/')).LastIndexOf('/'));
            s_File = s_File + "/Test.xml";

            System.Xml.XmlDocument objXmlDoc = new System.Xml.XmlDocument();

            System.IO.FileInfo fif;

            fif = new System.IO.FileInfo(s_File);

            try
            {
                objXmlDoc.Load(s_File);
                XmlNode node = objXmlDoc.SelectSingleNode("/CONFIG/" + sNode);

                node.InnerText = sContent;

                objXmlDoc.Save(s_File);

            }
            catch
            { 
                
            }
        }

        
    }
}

        调用我们的读取和写入方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(XmlHelper.GetConfig("DateTime").Trim());

            XmlHelper.WriteConfig("DateTime", DateTime.Now.ToString());

            Console.WriteLine(XmlHelper.GetConfig("DateTime").Trim());
        }
    }
}

C# 之 管理配置文件(三)_第1张图片






你可能感兴趣的:(C#)