• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

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

OC/C/C++ 水墨上仙 2280次浏览

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


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[65535];
      int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(0), FileName);
      //必须设定0(系统默认的


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C#进行INI文件的读写操作
喜欢 (0)
加载中……