C#进行INI文件的读写操作

VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面是一个C# ini文件读写类

[代码] [C#]代码

001using System;
002using System.IO;
003using System.Runtime.InteropServices;
004using System.Text;
005using System.Collections;
006using System.Collections.Specialized;
007 
008namespace wuyisky{
009  /**//**/
010  /**//// <summary>
011  /// IniFiles的类
012  /// </summary>
013  public class IniFiles
014  {
015    public string FileName; //INI文件名
016    //声明读写INI文件的API函数
017    [DllImport("kernel32")]
018    private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
019    [DllImport("kernel32")]
020    private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
021    //类的构造函数,传递INI文件名
022    public IniFiles(string AFileName)
023    {
024      // 判断文件是否存在
025      FileInfo fileInfo = new FileInfo(AFileName);
026      //Todo:搞清枚举的用法
027      if ((!fileInfo.Exists))
028      { //|| (FileAttributes.Directory in fileInfo.Attributes))
029        //文件不存在,建立文件
030        System.IO.StreamWriter sw = new System.IO.StreamWriter(AFileName, false, System.Text.Encoding.Default);
031        try
032        {
033          sw.Write("#表格配置档案");
034          sw.Close();
035        }
036 
037        catch
038        {
039          throw (new ApplicationException("Ini文件不存在"));
040        }
041      }
042      //必须是完全路径,不能是相对路径
043      FileName = fileInfo.FullName;
044    }
045    //写INI文件
046    public void WriteString(string Section, string Ident, string Value)
047    {
048      if (!WritePrivateProfileString(Section, Ident, Value, FileName))
049      {
050 
051        throw (new ApplicationException("写Ini文件出错"));
052      }
053    }
054    //读取INI文件指定
055    public string ReadString(string Section, string Ident, string Default)
056    {
057      Byte[] Buffer = new Byte[65535];
058      int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(0), FileName);
059      //必须设定0(系统默认的代码页)的编码方式,否则无法支持中文
060      string s = Encoding.GetEncoding(0).GetString(Buffer);
061      s = s.Substring(0, bufLen);
062      return s.Trim();
063    }
064 
065    //读整数
066    public int ReadInteger(string Section, string Ident, int Default)
067    {
068      string intStr = ReadString(Section, Ident, Convert.ToString(Default));
069      try
070      {
071        return Convert.ToInt32(intStr);
072 
073      }
074      catch (Exception ex)
075      {
076        Console.WriteLine(ex.Message);
077        return Default;
078      }
079    }
080 
081    //写整数
082    public void WriteInteger(string Section, string Ident, int Value)
083    {
084      WriteString(Section, Ident, Value.ToString());
085    }
086 
087    //读布尔
088    public bool ReadBool(string Section, string Ident, bool Default)
089    {
090      try
091      {
092        return Convert.ToBoolean(ReadString(Section, Ident, Convert.ToString(Default)));
093      }
094      catch (Exception ex)
095      {
096        Console.WriteLine(ex.Message);
097        return Default;
098      }
099    }
100 
101    //写Bool
102    public void WriteBool(string Section, string Ident, bool Value)
103    {
104      WriteString(Section, Ident, Convert.ToString(Value));
105    }
106 
107    //从Ini文件中,将指定的Section名称中的所有Ident添加到列表中
108    public void ReadSection(string Section, StringCollection Idents)
109    {
110      Byte[] Buffer = new Byte[16384];
111      //Idents.Clear();
112 
113      int bufLen = GetPrivateProfileString(Section, null, null, Buffer, Buffer.GetUpperBound(0),
114       FileName);
115      //对Section进行解析
116      GetStringsFromBuffer(Buffer, bufLen, Idents);
117    }
118 
119    private void GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings)
120    {
121      Strings.Clear();
122      if (bufLen != 0)
123      {
124        int start = 0;
125        for (int i = 0; i < bufLen; i++)
126        {
127          if ((Buffer[i] == 0) && ((i - start) > 0))
128          {
129            String s = Encoding.GetEncoding(0).GetString(Buffer, start, i - start);
130            Strings.Add(s);
131            start = i + 1;
132          }
133        }
134      }
135    }
136    //从Ini文件中,读取所有的Sections的名称
137    public void ReadSections(StringCollection SectionList)
138    {
139      //Note:必须得用Bytes来实现,StringBuilder只能取到第一个Section
140      byte[] Buffer = new byte[65535];
141      int bufLen = 0;
142      bufLen = GetPrivateProfileString(null, null, null, Buffer,
143       Buffer.GetUpperBound(0), FileName);
144      GetStringsFromBuffer(Buffer, bufLen, SectionList);
145    }
146    //读取指定的Section的所有Value到列表中
147    public void ReadSectionValues(string Section, NameValueCollection Values)
148    {
149      StringCollection KeyList = new StringCollection();
150      ReadSection(Section, KeyList);
151      Values.Clear();
152      foreach (string key in KeyList)
153      {
154        Values.Add(key, ReadString(Section, key, ""));
155  
156      }
157    }
158    /**/读取指定的Section的所有Value到列表中,
159    //public void ReadSectionValues(string Section, NameValueCollection Values,char splitString)
160    //{  string sectionValue;
161    //  string[] sectionValueSplit;
162    //  StringCollection KeyList = new StringCollection();
163    //  ReadSection(Section, KeyList);
164    //  Values.Clear();
165    //  foreach (string key in KeyList)
166    //  {
167    //    sectionValue=ReadString(Section, key, "");
168    //    sectionValueSplit=sectionValue.Split(splitString);
169    //    Values.Add(key, sectionValueSplit[0].ToString(),sectionValueSplit[1].ToString());
170 
171    //  }
172    //}
173    //清除某个Section
174    public void EraseSection(string Section)
175    {
176      //
177      if (!WritePrivateProfileString(Section, null, null, FileName))
178      {
179 
180        throw (new ApplicationException("无法清除Ini文件中的Section"));
181      }
182    }
183    //删除某个Section下的键
184    public void DeleteKey(string Section, string Ident)
185    {
186      WritePrivateProfileString(Section, Ident, null, FileName);
187    }
188    //Note:对于Win9X,来说需要实现UpdateFile方法将缓冲中的数据写入文件
189    //在Win NT, 2000和XP上,都是直接写文件,没有缓冲,所以,无须实现UpdateFile
190    //执行完对Ini文件的修改之后,应该调用本方法更新缓冲区。
191    public void UpdateFile()
192    {
193      WritePrivateProfileString(null, null, null, FileName);
194    }
195 
196    //检查某个Section下的某个键值是否存在
197    public bool ValueExists(string Section, string Ident)
198    {
199      //
200      StringCollection Idents = new StringCollection();
201      ReadSection(Section, Idents);
202      return Idents.IndexOf(Ident) > -1;
203    }
204 
205    //确保资源的释放
206    ~IniFiles()
207    {
208      UpdateFile();
209    }
210  }
211}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值