在开源中国看到的操作ini文件的,写的还不看,留着以后用

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections;
using System.Collections.Specialized; namespace wuyisky{
  /**//**/
  /**//// <summary>
  /// IniFiles的类
  /// </summary>
  public class IniFiles
  {
    public string FileName; //INI文件名
    //声明读写INI文件的API函数
    [DllImport("kernel32")]
    private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
    //类的构造函数,传递INI文件名
    public IniFiles(string AFileName)
    {
      // 判断文件是否存在
      FileInfo fileInfo = new FileInfo(AFileName);
      //Todo:搞清枚举的用法
      if ((!fileInfo.Exists))
      { //|| (FileAttributes.Directory in fileInfo.Attributes))
        //文件不存在,建立文件
        System.IO.StreamWriter sw = new System.IO.StreamWriter(AFileName, false, System.Text.Encoding.Default);
        try
        {
          sw.Write("#表格配置档案");
          sw.Close();
        }         catch
        {
          throw (new ApplicationException("Ini文件不存在"));
        }
      }
      //必须是完全路径,不能是相对路径
      FileName = fileInfo.FullName;
    }
    //写INI文件
    public void WriteString(string Section, string Ident, string Value)
    {
      if (!WritePrivateProfileString(Section, Ident, Value, FileName))
      {
 
        throw (new ApplicationException("写Ini文件出错"));
      }
    }
    //读取INI文件指定
    public string ReadString(string Section, string Ident, string Default)
    {
      Byte[] Buffer = new Byte[];
      int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(), FileName);
      //必须设定0(系统默认的代码页)的编码方式,否则无法支持中文
      string s = Encoding.GetEncoding().GetString(Buffer);
      s = s.Substring(, bufLen);
      return s.Trim();
    }     //读整数
    public int ReadInteger(string Section, string Ident, int Default)
    {
      string intStr = ReadString(Section, Ident, Convert.ToString(Default));
      try
      {
        return Convert.ToInt32(intStr);       }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
        return Default;
      }
    }     //写整数
    public void WriteInteger(string Section, string Ident, int Value)
    {
      WriteString(Section, Ident, Value.ToString());
    }     //读布尔
    public bool ReadBool(string Section, string Ident, bool Default)
    {
      try
      {
        return Convert.ToBoolean(ReadString(Section, Ident, Convert.ToString(Default)));
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
        return Default;
      }
    }     //写Bool
    public void WriteBool(string Section, string Ident, bool Value)
    {
      WriteString(Section, Ident, Convert.ToString(Value));
    }     //从Ini文件中,将指定的Section名称中的所有Ident添加到列表中
    public void ReadSection(string Section, StringCollection Idents)
    {
      Byte[] Buffer = new Byte[];
      //Idents.Clear();       int bufLen = GetPrivateProfileString(Section, null, null, Buffer, Buffer.GetUpperBound(),
       FileName);
      //对Section进行解析
      GetStringsFromBuffer(Buffer, bufLen, Idents);
    }     private void GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings)
    {
      Strings.Clear();
      if (bufLen != )
      {
        int start = ;
        for (int i = ; i < bufLen; i++)
        {
          if ((Buffer[i] == ) && ((i - start) > ))
          {
            String s = Encoding.GetEncoding().GetString(Buffer, start, i - start);
            Strings.Add(s);
            start = i + ;
          }
        }
      }
    }
    //从Ini文件中,读取所有的Sections的名称
    public void ReadSections(StringCollection SectionList)
    {
      //Note:必须得用Bytes来实现,StringBuilder只能取到第一个Section
      byte[] Buffer = new byte[];
      int bufLen = ;
      bufLen = GetPrivateProfileString(null, null, null, Buffer,
       Buffer.GetUpperBound(), 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;
    //  string[] sectionValueSplit;
    //  StringCollection KeyList = new StringCollection();
    //  ReadSection(Section, KeyList);
    //  Values.Clear();
    //  foreach (string key in KeyList)
    //  {
    //    sectionValue=ReadString(Section, key, "");
    //    sectionValueSplit=sectionValue.Split(splitString);
    //    Values.Add(key, sectionValueSplit[0].ToString(),sectionValueSplit[1].ToString());
 
    //  }
    //}
    //清除某个Section
    public void EraseSection(string Section)
    {
      //
      if (!WritePrivateProfileString(Section, null, null, FileName))
      {         throw (new ApplicationException("无法清除Ini文件中的Section"));
      }
    }
    //删除某个Section下的键
    public void DeleteKey(string Section, string Ident)
    {
      WritePrivateProfileString(Section, Ident, null, FileName);
    }
    //Note:对于Win9X,来说需要实现UpdateFile方法将缓冲中的数据写入文件
    //在Win NT, 2000和XP上,都是直接写文件,没有缓冲,所以,无须实现UpdateFile
    //执行完对Ini文件的修改之后,应该调用本方法更新缓冲区。
    public void UpdateFile()
    {
      WritePrivateProfileString(null, null, null, FileName);
    }     //检查某个Section下的某个键值是否存在
    public bool ValueExists(string Section, string Ident)
    {
      //
      StringCollection Idents = new StringCollection();
      ReadSection(Section, Idents);
      return Idents.IndexOf(Ident) > -;
    }     //确保资源的释放
    ~IniFiles()
    {
      UpdateFile();
    }
  }
}

C# Ini文件操作的更多相关文章

  1. ini文件操作

    Config.ini 文件操作 [SYS] sysname=hy company=hyhy tel=2 using System; using System.Collections.Generic; ...

  2. ini 文件操作记要(1): 使用 TIniFile

    ini 文件操作记要(1): 使用 TIniFile unit Unit1; interface uses   Windows, Messages, SysUtils, Variants, Class ...

  3. winform INI文件操作辅助类

    using System;using System.Runtime.InteropServices;using System.Text; namespace connectCMCC.Utils{ // ...

  4. Ini文件操作类

    /// <summary> /// Ini文件操作类 /// </summary> public class Ini { // 声明INI文件的写操作函数 WritePriva ...

  5. C# ini文件操作【源码下载】

    介绍C#如何对ini文件进行读写操作,C#可以通过调用[kernel32.dll]文件中的 WritePrivateProfileString()和GetPrivateProfileString()函 ...

  6. C#读写ini文件操作

    ini文件,是windows操作系统下的配置文件,ini文件是一种按照特点方式排列的文本文件,它的构成分为三部分,结构如下: [Section1] key 1 = value2 key 1 = val ...

  7. 读写INI文件操作类

    详情介绍:http://zh.wikipedia.org/wiki/INI%E6%96%87%E4%BB%B6 示例: 下面是一个虚拟的程序,其INI文件有两个小节,前面的小节是用来设置拥有者的信息, ...

  8. python基础——15(加密、excel操作、ini文件操作、xml操作模块及数据格式分类)

    一.加密模块 1.有解密的加密方式(base64) #base64加密 import base64 str_encrypt = input("输入要加密的字符串:\n") base ...

  9. Delphi ini文件操作 TIniFile、TMemIniFile

    1.使用TIniFile unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Co ...

随机推荐

  1. Computer Vision Algorithm Implementations

    Participate in Reproducible Research General Image Processing OpenCV (C/C++ code, BSD lic) Image man ...

  2. GitHub上传不了的解决 ssh: connect to host github.com port 22: Bad file number git did not exit cleanly (exit code 128)

    问题情况 本来一直用的是github的客户端,结果现在上传的时候出问题了,去网站上看,新项目已经创建,但是代码却怎么都上传不上去.于是只好用命令行的方式解决. Tortoisegit上是这样说的: g ...

  3. Necklace of Beads

    http://poj.org/problem?id=1286 // File Name: poj1286.cpp // Author: bo_jwolf // Created Time: 2013年1 ...

  4. eclipse连接远程hadoop集群开发时0700问题解决方案

    eclipse连接远程hadoop集群开发时报错 错误信息: Exception in thread "main" java.io.IOException:Failed to se ...

  5. 理解RESTful架构(转)

    理解RESTful架构   作者: 阮一峰 http://www.ruanyifeng.com/blog/2011/09/restful 越来越多的人开始意识到,网站即软件,而且是一种新型的软件. 这 ...

  6. Android的adb命令使用以及在DOS的一系列操作

    adb是什么?:adb的全称为Android Debug Bridge,就是起到调试桥的作用.      adb有什么用?:借助adb工具,我们可以管理设备或手机模拟器的状态.还可以进行很多手机操作, ...

  7. angular2的管道初体验

    ng管道是应用里面比较重要的一个技术,他涉及很多功能 包括排序过滤 废话不说 直接上代码 新建个文件夹吧这个samplepipe.ts放进去 然后 你要做什么 在里面写管道代码 然后在app.modu ...

  8. 使用Dreamwaver cc中的SVN功能,用于传输BAE和SAE中的文件

    前沿: 假期使用BAE和SAE开发应用,两个服务器都需要通过SVN提交代码,因为平时大多使用Dreamwaver,所以查了查资料,通过Subversion方便了开发. 因为网上的资料都不全,所以根据自 ...

  9. 如何调试delphi的Access violation at address错误

    1.什么是 MAP 文件?简单地讲,MAP 文件是程序的全局符号.源文件和代码行号信息的唯一的文本表示方法,它可以在任何地方.任何时候使用,不需要有额外的程序进行支持. 2.DELPHI下生成MAP文 ...

  10. Memento 备忘录 快照模式

    简介 定义: 在不破坏封装的前提下,捕获一个对象的[内部状态],并在该对象之外保存这个状态,这样以后就可以将该对象恢复到原先保存的状态. 角色: 发起人Originator:要被备份的成员,它提供一创 ...