C#读写Properties配置文件

C#读写Properties文件

本来想在项目里读取和写入一些配置数据。一番探索后,INI 文件需要引用API;XML的层次结构用不着,也麻烦。

这时想到Java的Properties配置文件挺方便,格式类似于INI,自己动手写一个。

using System;
using System.IO;
using System.Text;
using System.Collections;

/*
 * @author : RoadToTheExpert
 * @date : 2019.07
 * @file : Properties.cs
 */
namespace roadtotheexpert
{
    public class Properties
    {
        public static Hashtable Load(string file)
        {
            Hashtable ht = new Hashtable(16);
            string content = null;
            try
            {
                content = File.ReadAllText(file, System.Text.Encoding.UTF8);
            }
            catch (Exception e)
            {
                return null;
            }
            string[] rows = content.Split('\n');
            string[] kv = null;
            foreach (string c in rows)
            {
                if (c.Trim().Length == 0)
                    continue;
                kv = c.Split('=');
                if (kv.Length == 1)
                {
                    ht[kv[0].Trim()] = "";
                }
                else if (kv.Length == 2)
                {
                    ht[kv[0].Trim()] = kv[1].Trim();
                }
            }
            return ht;
        }

        public static bool Save(string file, Hashtable ht)
        {
            if (ht == null || ht.Count == 0)
                return false;
            StringBuilder sb = new StringBuilder(ht.Count * 12);
            foreach (string k in ht.Keys)
            {
                sb.Append(k).Append('=').Append(ht[k]).Append(System.Environment.NewLine);
            }
            try
            {
                File.WriteAllText(file, sb.ToString(), System.Text.Encoding.UTF8);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        public static string test()
        {
            string file = @"D:\cfg.txt";
            if (!File.Exists(file)) 
                File.WriteAllText(file, "");

            Hashtable ht = Properties.Load(file);
            if (ht != null)
            {
                ht["Time" + ht.Count] = System.DateTime.Now.ToString();
                Properties.Save(file, ht);

                StringBuilder sb = new StringBuilder(ht.Count * 12);
                foreach (string k in ht.Keys)
                {
                    sb.Append(k).Append('=').Append(ht[k]).Append(System.Environment.NewLine);
                }
                return sb.ToString();
            }
            return "none";
        }

        public static void Main(string[] args)
        {
            Console.WriteLine(test());
        }

        
    }
}

猜你喜欢

转载自blog.csdn.net/RoadToTheExpert/article/details/95964809