两种读取ini文件的方式(调用windows API和IO的方式读取)对比

时间:2021-11-25 04:25:44

第一种:调用windowsAPI中的WritePrivateProfileStringGetPrivateProfileString方法.

   在此,我们需要调用包含上文提到的两个读写INI文件方法的DLL(kernel32),语法如下:[DllImport("kernel32")]。

  #region 调用windowsAPI方式
    class Program
    {
        static void Main(string[] args)
        {
            string Current;

            Current = Directory.GetCurrentDirectory();//获取当前根目录
            Console.WriteLine("Current directory {0}", Current);
            // 写入ini
            Ini ini = new Ini(Current + "/config.ini");
            ini.Writue("Setting", "key1", "hello word!");
            ini.Writue("Setting", "key2", "hello ini!");
            ini.Writue("SettingImg", "Path", "IMG.Path");
            // 读取ini
            string stemp = ini.ReadValue("SETTING", "KEY2");
            Console.WriteLine(stemp);
            Console.ReadKey();
        }
    }
    class Ini
    {
        // 声明INI文件的写操作函数 WritePrivateProfileString()

        [System.Runtime.InteropServices.DllImport("kernel32")]

        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        // 声明INI文件的读操作函数 GetPrivateProfileString()

        [System.Runtime.InteropServices.DllImport("kernel32")]

        private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);


        private string sPath = null;
        public Ini(string path)
        {
            this.sPath = path;
        }

        public void Writue(string section, string key, string value)
        {

            // section=配置节,key=键名,value=键值,path=路径

            WritePrivateProfileString(section, key, value, sPath);

        }
        public string ReadValue(string section, string key)
        {

            // 每次从ini中读取多少字节

            System.Text.StringBuilder temp = new System.Text.StringBuilder(255);

            // section=配置节,key=键名,temp=上面,path=路径

            GetPrivateProfileString(section, key, "", temp, 255, sPath);

            return temp.ToString();
        }
    }
    #endregion

这种方法,是不区分大小写的,ini.Writue("Setting", "key2", "hello ini!")和string stemp = ini.ReadValue("SETTING", "KEY2")进行对比可以看出,返回的结果是一样的都是hello ini!

第二种方法:利用IO进行文件操作(代码基本都是由个人所写,所以会区分大小写)

#region
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, Dictionary<string, string>> test = new Dictionary<string, Dictionary<string, string>>();
            test = readIni("d:xxx.ini");
            foreach (string key in test.Keys)
            {
               // foreach (Dictionary<string, string> subKey in test.Values)
               // {
                  //  Console.WriteLine("(k1={0},(k2={1},value={2}))", key, subKey.Keys, subKey.Values);
                //}
                foreach (string subKey in test[key].Keys)
                {
                    Console.WriteLine("(k1={0},(k2={1},value={2}))", key, subKey,test[key][subKey]);             
                }
            }
            Console.ReadKey();
        }
        static Dictionary<string, Dictionary<string, string>> readIni(string filePath)
        {
            int count = 0;//计算节点数
            int j = 0;//节点数值下标
            string[] lines = System.IO.File.ReadAllLines(filePath, Encoding.Default);
            foreach (string item in lines)
            {
                Console.WriteLine(item);
                if (item.StartsWith("[") && item.EndsWith("]"))
                {
                    count++;
                }
            }
            string[] nodeName = new string[count];

            #region 确定节点数组
            for (int i = 0; i < lines.Length; i++)
            {
                if (lines[i].StartsWith("[") && lines[i].EndsWith("]"))
                {
                    while (j < count)
                    {
                        nodeName[j] = lines[i];
                        j++;
                        break;
                    }
                }
            }
            #endregion
            #region
            Dictionary<string, string>[] dicKey = new Dictionary<string, string>[count];
            Dictionary<string, Dictionary<string, string>> dic = new Dictionary<string, Dictionary<string, string>>();
            for (int m = 0; m < lines.Length; m++)
            {
                for (int i = 0; i < count; i++)
                {
                    dicKey[i] = new Dictionary<string, string>();
                    if (lines[m].Contains(nodeName[i]))//某个节点所在的行
                    {
                        for (int n = m + 1; n < lines.Length; n++)
                        {
                            //读到下一个节点跳出
                            if ((i + 1) < count && lines[n].Contains(nodeName[i + 1]))//位置不能颠倒
                            {
                                break;
                            }

                            string str1 = lines[n].Substring(0, lines[n].IndexOf("="));
                            string str2 = lines[n].Substring(lines[n].IndexOf("=") + 1);
                            (dicKey[i]).Add(str1, str2);
                            //(dicKey[i])[str1] = str2;                          
                        }
                        dic.Add(nodeName[i].Substring(1, nodeName[i].Length - 2), dicKey[i]);
                    }
                }
            }
            #endregion
            return dic;
        }
    }
  #endregion

区分大小写。