using System; using System.Collections; using System.Text; using System.IO; using System.Runtime.InteropServices; class INIOperationClass { /// /// 声明读ini文件所有key的API函数 /// /// 段落,也就是title /// 关键字,也就是key /// 无法读取时候时候的缺省数值 /// 读取的数值缓冲区数组 /// 读取的数值缓冲区数组大小 /// 文件路径 /// [DllImport("kernel32")] private static extern int GetPrivateProfileString( string strTitle, string strKey, string strDefaultValue, Byte[] bBuffer, int iBufferSize, string strFilePath ); /// /// 声明读ini文件单个key的API函数 /// /// 段落,也就是title /// 关键字,也就是key /// 无法读取时候时候的缺省数值 /// 读取的数值缓冲区 /// 读取的数值缓冲区大小 /// 文件路径 /// [DllImport("kernel32")] private static extern int GetPrivateProfileString( string strTitle, string strKey, string strDefaultValue, StringBuilder sbBuffer, int iBufferSize, string strFilePath ); /// /// 声明写ini文件单个key的API函数 /// /// 段落,也就是title /// 关键字,也就是key /// 写入的数值 /// 文件路径 /// [DllImport("kernel32")] private static extern bool WritePrivateProfileString( string strTitle, string strKey, string strValue, string strFilePath ); /// /// 读取ini文件所有title的名称,默认不包含重复的title /// /// /// public static string[] ReadIniTitles(string strFileName) { return ReadIniTitles(strFileName, false); } /// /// 读取ini文件所有title的名称:可以控制是否包含重复的title /// /// /// /// public static string[] ReadIniTitles(string strFileName, bool RepeatTitle) { if (RepeatTitle) { //允许包含重复的title return ReadIniArray(null, strFileName); } else { //禁止包含重复的title string[] strTitles = ReadIniArray(null, strFileName); if (strTitles.Length <= 1) { //如果title的数量小于1,则根本不会存在重复的元素 return strTitles; } else { //新建一个数组,用来筛选剔除重复title ArrayList alTitls = new ArrayList(); for (int i = 0; i < strTitles.Length; i++) { if (alTitls.Contains(strTitles[i]) == false) { alTitls.Add(strTitles[i]); } } //新建一个数组,并且赋值后把值返回给函数 string[] strValidTitles = new string[alTitls.Count]; for (int i = 0; i < alTitls.Count; i++) { strValidTitles[i] = alTitls[i].ToString(); } return strValidTitles; } } } /// /// 读取ini文件所有key的名称,默认不包含重复的key /// /// /// /// public static string[] ReadIniKeys(string strTitle, string strFileName) { return ReadIniKeys(strTitle, strFileName, false); } /// /// 读取ini文件所有key的名称:可以控制是否包含重复的key /// /// /// /// /// public static string[] ReadIniKeys(string strTitle, string strFileName, bool RepeatKey) { if (RepeatKey) { //允许包含重复的key return ReadIniArray(strTitle, strFileName); } else { //禁止包含重复的key string[] strKeys = ReadIniArray(strTitle, strFileName); if (strKeys.Length <= 1) { //如果key的数量小于1,则根本不会存在重复的元素 return strKeys; } else { //新建一个数组,用来筛选剔除重复key ArrayList alKeys = new ArrayList(); for (int i = 0; i < strKeys.Length; i++) { if (alKeys.Contains(strKeys[i]) == false) { alKeys.Add(strKeys[i]); } } //新建一个数组,并且赋值后把值返回给函数 string[] strValidKeys = new string[alKeys.Count]; for (int i = 0; i < alKeys.Count; i++) { strValidKeys[i] = alKeys[i].ToString(); } return strValidKeys; } } } /// /// 读取ini文件中title或key的所有名称 /// /// /// /// public static string[] ReadIniArray(string strTitle, string strFileName) { //获取到所有key并且存放到数组中 Byte[] bBuffer = new Byte[524287]; GetPrivateProfileString(strTitle, null, null, bBuffer, 524287, strFileName);//获取所有key string[] strBuffers = System.Text.Encoding.UTF8.GetString(bBuffer).Split('\0');//获取到的key进行分割存放数组,同时使用编码避免读取中文乱码 //对数组的值进行有效性判断,取得第一个无效值的数组下标 int iSize = strBuffers.Length;//定义有效数组的个数 for (int i = 0; i < strBuffers.Length; i++) { if (strBuffers[i].Trim().Length == 0) { //当读取到的数组为空时,则说明之后的数组值都无效,退出循环 iSize = i; break; } } //新建一个数组,并且赋值后把值返回给函数 string[] strKeys = new string[iSize]; for (int i = 0; i < iSize; i++) { strKeys[i] = strBuffers[i]; } return strKeys; } /// /// 读取ini文件单个key对应的value值 /// /// /// /// /// /// public static string ReadIniValue(string strTitle, string strKey, string strDefaultValue, string strFileName) { StringBuilder sbBuffer = new StringBuilder(65535); GetPrivateProfileString(strTitle, strKey, strDefaultValue, sbBuffer, 65535, strFileName); return sbBuffer.ToString(); } /// /// 文件遍历读取ini文件单个key对应的value值 /// /// /// /// /// /// /// public static string ReadIniValue(string strTitle, string strKey, string strDefaultValue, string strIniLines, int iCutBlank) { try { //循环遍历每一行 string[] strIniItems = strIniLines.Split('\n'); for (int i = 0; i < strIniItems.GetLength(0); i++) { //找到匹配的key if (strIniItems[i].Trim().ToUpper() == '[' + strTitle.Trim().ToUpper() + ']') { for (int j = i + 1; j < strIniItems.GetLength(0); j++) { string strIniLine = strIniItems[j].Trim(); if (strIniLine.Length > 0) { if (strIniLine[0] == '[' && strIniLine[strIniLine.Length - 1] == ']') { //越段了,则返回默认值 return strDefaultValue; } strIniLine = strIniItems[j].TrimStart().Replace(" ", ""); if (strIniLine.Substring(0, Math.Min(strKey.Length + 1, strIniLine.Length)).ToUpper() == strKey.ToUpper() + "=") { //如果找到了Key匹配 if (iCutBlank == 0) { //前后空格全部取消 return strIniItems[j].Substring(strIniItems[j].IndexOf('=') + 1).Trim(); } else if (iCutBlank == 1) { //只取消左边空格 return strIniItems[j].Substring(strIniItems[j].IndexOf('=') + 1).TrimStart(); } else if (iCutBlank == 2) { //只取消右边空格 return strIniItems[j].Substring(strIniItems[j].IndexOf('=') + 1).TrimEnd(); } else { //保留前后空格 return strIniItems[j].Substring(strIniItems[j].IndexOf('=') + 1); } } } } //没找到key,则返回默认值 return strDefaultValue; } } //没找到key,则返回默认值 return strDefaultValue; } catch { //异常情况返回默认值 return strDefaultValue; } } /// /// 写入ini文件单个key对应的value值 /// /// /// /// /// public static void WriteIniValue(string strTitle, string strKey, string strValue, string strFileName) { ClearFileReadOnly(strFileName); WritePrivateProfileString(strTitle, strKey, strValue, strFileName); } /// /// 删除ini文件单个key以及对应的value值 /// /// /// /// public static void DelIniKey(string strTitle, string strKey, string strFileName) { ClearFileReadOnly(strFileName); WritePrivateProfileString(strTitle, strKey, null, strFileName); } /// /// 删除ini文件单个title以及对应的所有key、value /// /// /// public static void DelIniTitle(string strTitle, string strFileName) { ClearFileReadOnly(strFileName); WritePrivateProfileString(strTitle, null, null, strFileName); } /// /// 给定一个字符串和非法分割符,检查字符串的有效性 /// /// /// /// public static bool CheckStringValidity(string strContent, string strIllegalSplit) { if (strContent.StartsWith(strIllegalSplit) == true) { return false; } else if (strContent.EndsWith(strIllegalSplit) == true) { return false; } else if (strContent.IndexOf(strIllegalSplit + strIllegalSplit) >= 0) { return false; } else { return true; } } /// /// 取消单个文件的只读属性 /// /// public static void ClearFileReadOnly(string strFilePath) { //try //{ // FileInfo fileInfo = new FileInfo(strFilePath); // fileInfo.Attributes = FileAttributes.Normal; //} //catch (Exception) //{ //} } /// /// 删除单个文件 /// /// public static void DelSingleFile(string strFilePath) { try { ClearFileReadOnly(strFilePath); File.Delete(strFilePath); } catch (Exception) { } } /// /// 获取一个指定文件路径的文件名:一个参数 /// /// /// public static string GetFileName(string strFilePath) { string[] strFileList = strFilePath.Trim().Split('\\'); return strFileList[strFileList.Length - 1]; } /// /// 获取一个指定文件路径的文件名:两个参数 /// /// /// /// public static string GetFileName(string strFilePath, bool bFileSuffix) { try { string[] strFileList = strFilePath.Trim().Split('\\'); string strFullFileName = strFileList[strFileList.Length - 1]; if (bFileSuffix) { //返回文件名的同时返回后缀名 return strFullFileName; } else { //只返回文件名不包括后缀名 string[] strFileName = strFullFileName.Trim().Split('.'); return strFullFileName.Substring(0, strFullFileName.Length - strFileName[strFileName.Length - 1].Length - 1); } } catch { return ""; } } /// /// 判断文件容量大小 /// /// /// public static string FormatFileSize(long lFileSize) { if (lFileSize >= 1024 * 1024 * 1024) { return Math.Round((lFileSize * 1.0) / (1024 * 1024 * 1024), 2).ToString() + " GB"; } else if (lFileSize >= 1024 * 1024) { return Math.Round((lFileSize * 1.0) / (1024 * 1024), 2).ToString() + " MB"; } else if (lFileSize >= 1024) { return Math.Round((lFileSize * 1.0) / 1024, 2).ToString() + " KB"; } else { return Language.Get("FileSize", lFileSize); //return string.Format("{0} 字节", lFileSize); } } /// /// 取消文件目录下所有文件的只读属性,包括子目录 /// /// public static void ClearDirectoryReadOnly(string strDirectoryPath) { //try //{ // DirectoryInfo DirCurrent = new DirectoryInfo(strDirectoryPath); // DirCurrent.Attributes = FileAttributes.Normal; // foreach (FileSystemInfo fsCurrentFile in DirCurrent.GetFileSystemInfos()) // { // fsCurrentFile.Attributes = FileAttributes.Normal; // } // foreach (DirectoryInfo DirCurrentFolder in DirCurrent.GetDirectories()) // { // ClearDirectoryReadOnly(DirCurrentFolder.FullName); // } //} //catch //{ //} } /// /// 获取文件的所有内容:按整个文本读取 + 默认编码 /// /// /// //public static string ReadAllText(string strFileName) //{ // try // { // return File.ReadAllText(strFileName, Encoding.Default); // } // catch // { // return ""; // } //} /// /// 获取文件的所有内容:按整个文本读取 + 指定编码 /// /// /// /// //public static string ReadAllText(string strFileName, string strCode) //{ // try // { // return File.ReadAllText(strFileName, Encoding.GetEncoding(Convert.ToInt32(strCode))); // } // catch // { // return ReadAllText(strFileName); // } //} /// /// 获取文件的所有内容:按行读取 + 默认编码 /// /// /// //public static string[] ReadAllLines(string strFileName) //{ // try // { // return File.ReadAllLines(strFileName, Encoding.Default); // } // catch // { // return null; // } //} /// /// 获取文件的所有内容:按行读取 + 指定编码 /// /// /// /// //public static string[] ReadAllLines(string strFileName, string strCode) //{ // try // { // return File.ReadAllLines(strFileName, Encoding.GetEncoding(Convert.ToInt32(strCode))); // } // catch // { // return ReadAllLines(strFileName); // } //} /// /// /内容写入文件:默认编码 /// /// /// public static void CreateFile(string strFilePath, string strContents) { CreateOrModifyFile(strFilePath, strContents, FileMode.Create, Encoding.Default); } /// /// 内容写入文件:指定编码 /// /// /// /// public static void CreateFile(string strFilePath, string strContents, string strCode) { CreateOrModifyFile(strFilePath, strContents, FileMode.Create, Encoding.GetEncoding(Convert.ToInt32(strCode))); } /// /// 修改文件内容:默认编码 /// /// /// public static void ModifyFile(string strFilePath, string strContents) { CreateOrModifyFile(strFilePath, strContents, FileMode.Append, Encoding.Default); } /// /// 修改文件内容:指定编码 /// /// /// /// public static void ModifyFile(string strFilePath, string strContents, string strCode) { CreateOrModifyFile(strFilePath, strContents, FileMode.Append, Encoding.GetEncoding(Convert.ToInt32(strCode))); } /// /// 创建或修改文件内容 /// /// /// public static void CreateOrModifyFile(string strFilePath, string sbContent, FileMode fileMode, Encoding encoding) { //文件夹不存在 if (!Directory.Exists(new DirectoryInfo(strFilePath).Parent.FullName)) { Directory.CreateDirectory(new DirectoryInfo(strFilePath).Parent.FullName); } //清除只读属性 if (File.Exists(strFilePath)) { ClearFileReadOnly(strFilePath); } //写入文件方式 FileStream fsLog = fsLog = new FileStream(strFilePath, fileMode, FileAccess.Write); //写入内容 StreamWriter swLog = new StreamWriter(fsLog, encoding); swLog.Flush(); swLog.Write(sbContent); swLog.Flush(); swLog.Close(); } /// /// 获取Ini文件的所有内容 /// /// /// public static string GetIniFileLines(string strFileName) { try { StreamReader strIniFile = new StreamReader(strFileName, System.Text.Encoding.Default); string strIniLines = strIniFile.ReadToEnd(); strIniFile.Close(); return strIniLines; } catch { return ""; } } }