C#读写INI文件的方法

2019-12-26 13:35:00王冬梅

易采站长站为您分析C#读写INI文件的方法,涉及C#读写ini文件的相关实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了C#读写INI文件的方法。。具体如下:

虽然微软早已经建议在WINDOWS中用注册表代替INI文件,但是在实际应用中,INI文件仍然有用武之地,尤其现在绿色软件的流行,越来越多的程序将自己的一些配置信息保存到了INI文件中。

INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value)

[Section]

Key=Value

VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面是一个C# ini文件读写类,从网上收集的,很全,就是没有对section的改名功能,高手可以增加一个。

 

 
  1. using System;  using System.IO; 
  2. using System.Runtime.InteropServices;  using System.Text; 
  3. using System.Collections;  using System.Collections.Specialized; 
  4. namespace wuyisky  { 
  5. /// <summary>  /// IniFiles的类 
  6. /// </summary>  public class IniFiles 
  7. {  public string FileName; //INI文件名 
  8. //声明读写INI文件的API函数  [DllImport("kernel32")] 
  9. private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);  [DllImport("kernel32")] 
  10. private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);  //类的构造函数,传递INI文件名 
  11. public IniFiles(string AFileName)  { 
  12. // 判断文件是否存在  FileInfo fileInfo = new FileInfo(AFileName); 
  13. //Todo:搞清枚举的用法  if ((!fileInfo.Exists)) 
  14. { //|| (FileAttributes.Directory in fileInfo.Attributes))  //文件不存在,建立文件 
  15. System.IO.StreamWriter sw = new System.IO.StreamWriter(AFileName, false, System.Text.Encoding.Default);  try 
  16. {  sw.Write("#表格配置档案"); 
  17. sw.Close();  }