云梯的博客园 发表于 2013-1-2 23:04:12

C#学习笔记——读写ini文件

<div id="cnblogs_post_body"><div id="codeSnippetWrapper">   <div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">      1: using System;       2: using System.Collections.Generic;       3: using System.Linq;       4: using System.Text;       5: //引入命名空间       6: using System.Collections.Specialized;       7: using System.IO;       8:       9:    10: namespace ConfigFiles    11: {    12:   /// <summary>    13:   /// IniFiles的类    14:   /// </summary>    15:   public class IniFiles    16:   {    17:         public string FileName; //INI文件名    18:    19:         //声明读写INI文件的API函数    20:         "kernel32")]    21:         private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);    22:         "kernel32")]    23:         private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);    24:    25:         //类的构造函数,传递INI文件名    26:         public IniFiles(string AFileName)    27:         {    28:             // 判断文件是否存在    29:             FileInfo fileInfo = new FileInfo(AFileName);    30:    31:             //Todo:搞清枚举的用法    32:             if ((!fileInfo.Exists))    33:             { //|| (FileAttributes.Directory in fileInfo.Attributes))    34:               //文件不存在,建立文件    35:               System.IO.StreamWriter sw = new System.IO.StreamWriter(AFileName, false, System.Text.Encoding.Default);    36:               try    37:               {    38:                     sw.Write("#应用程序配置文件");    39:                     sw.Close();    40:               }    41:    42:               catch    43:               {    44:                     throw (new ApplicationException("Ini文件不存在"));    45:               }    46:             }    47:    48:             //必须是完全路径,不能是相对路径    49:             FileName = fileInfo.FullName;    50:         }    51:    52:         //写INI文件    53:         public void WriteString(string Section, string Ident, string Value)    54:         {    55:             if (!WritePrivateProfileString(Section, Ident, Value, FileName))    56:             {    57:               throw (new ApplicationException("写Ini文件出错"));    58:             }    59:         }    60:    61:         //读取INI文件指定    62:         public string ReadString(string Section, string Ident, string Default)    63:         {    64:             Byte[] Buffer = new Byte;    65:             int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(0), FileName);    66:             //必须设定0(系统默认的代码页)的编码方式,否则无法支持中文    67:             string s = Encoding.GetEncoding(0).GetString(Buffer);    68:             s = s.Substring(0, bufLen);    69:             return s.Trim();    70:         }    71:    72:         //读整数    73:         public int ReadInteger(string Section, string Ident, int Default)    74:         {    75:             string intStr = ReadString(Section, Ident, Convert.ToString(Default));    76:             try    77:             {    78:               return Convert.ToInt32(intStr);    79:    80:             }    81:             catch (Exception ex)    82:             {    83:               Console.WriteLine(ex.Message);    84:               return Default;    85:             }    86:         }    87:    88:         //写整数    89:         public void WriteInteger(string Section, string Ident, int Value)    90:         {    91:             WriteString(Section, Ident, Value.ToString());    92:         }    93:    94:         //读布尔    95:         public bool ReadBool(string Section, string Ident, bool Default)    96:         {    97:             try    98:             {    99:               return Convert.ToBoolean(ReadString(Section, Ident, Convert.ToString(Default)));    100:             }    101:             catch (Exception ex)    102:             {    103:               Console.WriteLine(ex.Message);    104:               return Default;    105:             }    106:         }    107:     108:         //写Bool    109:         public void WriteBool(string Section, string Ident, bool Value)    110:         {    111:             WriteString(Section, Ident, Convert.ToString(Value));    112:         }    113:     114:         //从Ini文件中,将指定的Section名称中的所有Ident添加到列表中    115:         public void ReadSection(string Section, StringCollection Idents)    116:         {    117:             Byte[] Buffer = new Byte;    118:             //Idents.Clear();    119:     120:             int bufLen = GetPrivateProfileString(Section, null, null, Buffer, Buffer.GetUpperBound(0),    121:            FileName);    122:             //对Section进行解析    123:             GetStringsFromBuffer(Buffer, bufLen, Idents);    124:         }    125:     126:         private void GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings)    127:         {    128:             Strings.Clear();    129:             if (bufLen != 0)    130:             {    131:               int start = 0;    132:               for (int i = 0; i < bufLen; i++)    133:               {    134:                     if ((Buffer == 0) && ((i - start) > 0))    135:                     {    136:                         String s = Encoding.GetEncoding(0).GetString(Buffer, start, i - start);    137:                         Strings.Add(s);    138:                         start = i + 1;    139:                     }    140:               }    141:             }    142:         }    143:     144:         //从Ini文件中,读取所有的Sections的名称    145:         public void ReadSections(StringCollection SectionList)    146:         {    147:             //Note:必须得用Bytes来实现,StringBuilder只能取到第一个Section    148:             byte[] Buffer = new byte;    149:             int bufLen = 0;    150:             bufLen = GetPrivateProfileString(null, null, null, Buffer,    151:            Buffer.GetUpperBound(0), FileName);    152:             GetStringsFromBuffer(Buffer, bufLen, SectionList);    153:         }    154:     155:         //读取指定的Section的所有Value到列表中    156:         public void ReadSectionValues(string Section, NameValueCollection Values)    157:         {    158:             StringCollection KeyList = new StringCollection();    159:             ReadSection(Section, KeyList);    160:             Values.Clear();    161:             foreach (string key in KeyList)    162:             {    163:               Values.Add(key, ReadString(Section, key, ""));    164:     165:             }    166:         }    167:     168:     169:         //清除某个Section    170:         public void EraseSection(string Section)    171:         {    172:             //    173:             if (!WritePrivateProfileString(Section, null, null, FileName))    174:             {    175:     176:               throw (new ApplicationException("无法清除Ini文件中的Section"));    177:             }    178:         }    179:     180:         //删除某个Section下的键    181:         public void DeleteKey(string Section, string Ident)    182:         {    183:             WritePrivateProfileString(Section, Ident, null, FileName);    184:         }    185:     186:         //Note:对于Win9X,来说需要实现UpdateFile方法将缓冲中的数据写入文件    187:         //在Win NT, 2000和XP上,都是直接写文件,没有缓冲,所以,无须实现UpdateFile    188:         //执行完对Ini文件的修改之后,应该调用本方法更新缓冲区。    189:         public void UpdateFile()    190:         {    191:             WritePrivateProfileString(null, null, null, FileName);    192:         }    193:     194:         //检查某个Section下的某个键值是否存在    195:         public bool ValueExists(string Section, string Ident)    196:         {    197:             //    198:             StringCollection Idents = new StringCollection();    199:             ReadSection(Section, Idents);    200:             return Idents.IndexOf(Ident) > -1;    201:         }    202:     203:         //确保资源的释放    204:         ~IniFiles()    205:         {    206:             UpdateFile();    207:         }    208:   }    209: }
页: [1]
查看完整版本: C#学习笔记——读写ini文件