INI配置文件在linux下的读写

时间:2022-03-26 04:28:37

       因项目需要,要实现一个在PC机写一个ini配置文件,然后让linux去读取

           其实只是简单的几个函数而已,我把它写在了一个类里面

         public class IniHelper
    {
        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);

        public static void WriteValue(string path, string section, string key, string value)
        {
            // section=配置节,key=键名,value=键值,path=路径
            WritePrivateProfileString(section, key, value, path);
        }

        public static string ReadValue(string path, string section, string key)
        {
            // 每次从ini中读取多少字节
            System.Text.StringBuilder temp = new System.Text.StringBuilder(255);
            // section=配置节,key=键名,temp=上面,path=路径
            GetPrivateProfileString(section, key, "", temp, 255, path);
            return temp.ToString();
        }

    }
        但是这 不能再linux下直接读取,而是转化为16进制所以我又写了一个转换的函数

         

        private static string Transform(string str)
        {
            char[] trTab = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            string str2 = null ;
            for (int i = 0; i < str.Length; i++)
            {
                int j = str.ElementAt(i);
                str2 += "\\x";
                if (j > 0xff)
                {
                    str2 += trTab[j >> 12];
                    str2 += trTab[(j >> 8) & 0x0f];
                }
                str2 += trTab[(j >> 4) & 0x0f];
                str2 += trTab[(j) & 0x0f];
            }
            return str2;
        }