C#读写INI文件的方法

2019-12-26 13:35:00王冬梅
  • {  WriteString(Section, Ident, Convert.ToString(Value)); 
  • }  //从Ini文件中,将指定的Section名称中的所有Ident添加到列表中 
  • public void ReadSection(string Section, StringCollection Idents)  { 
  • Byte[] Buffer = new Byte[16384];  //Idents.Clear(); 
  • int bufLen = GetPrivateProfileString(Section, null, null, Buffer, Buffer.GetUpperBound(0),  FileName); 
  • //对Section进行解析  GetStringsFromBuffer(Buffer, bufLen, Idents); 
  • }  private void GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings) 
  • {  Strings.Clear(); 
  • if (bufLen != 0)  { 
  • int start = 0;  for (int i = 0; i < bufLen; i++) 
  • {  if ((Buffer[i] == 0) && ((i - start) > 0)) 
  • {  String s = Encoding.GetEncoding(0).GetString(Buffer, start, i - start); 
  • Strings.Add(s);  start = i + 1; 
  • }  } 
  • }  } 
  • //从Ini文件中,读取所有的Sections的名称  public void ReadSections(StringCollection SectionList) 
  • {  //Note:必须得用Bytes来实现,StringBuilder只能取到第一个Section 
  • byte[] Buffer = new byte[65535];  int bufLen = 0; 
  • bufLen = GetPrivateProfileString(null, null, null, Buffer,  Buffer.GetUpperBound(0), FileName); 
  • GetStringsFromBuffer(Buffer, bufLen, SectionList);  } 
  • //读取指定的Section的所有Value到列表中  public void ReadSectionValues(string Section, NameValueCollection Values) 
  • {  StringCollection KeyList = new StringCollection(); 
  • ReadSection(Section, KeyList);  Values.Clear(); 
  • foreach (string key in KeyList)  { 
  • Values.Add(key, ReadString(Section, key, ""));  } 
  • }  ////读取指定的Section的所有Value到列表中, 
  • //public void ReadSectionValues(string Section, NameValueCollection Values,char splitString)  //{  string sectionValue;