2025年6月9日 星期一 乙巳(蛇)年 三月十三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > .net

C# WinForm 简单读写ini文件帮助类 INIHelp

时间:04-11来源:作者:点击数:73

软件里需要读取一些初始化信息,

决定用ini来做,简单方便。

于是查了一写代码,自己写了一个帮助类。

INI文件格式是某些平台或软件上的配置文件的非正式标准,

以节(section)和键(key)构成,常用于微软Windows操作系统中。

这种配置文件的文件扩展名多为INI,故名INI。

INI是英文“初始化”(initialization)的缩写。正如该术语所表示的,INI文件被用来对操作系统或特定程序初始化或进行参数设置。

帮助类:

  • 1 using System;
  • 2 using System.Collections.Generic;
  • 3 using System.Linq;
  • 4 using System.Text;
  • 5 using System.Runtime.InteropServices;
  • 6 using System.IO;
  • 7
  • 8 namespace ConsoleApplication1
  • 9 {
  • 10 class INIhelp
  • 11 {
  • 12 [DllImport("kernel32")]
  • 13 private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
  • 14 [DllImport("kernel32")]
  • 15 private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);
  • 16
  • 17 //ini文件名称
  • 18 private static string inifilename = "Config.ini";
  • 19 //获取ini文件路径
  • 20 private static string inifilepath = Directory.GetCurrentDirectory() + "\\" + inifilename;
  • 21
  • 22 public static string GetValue(string key)
  • 23 {
  • 24 StringBuilder s = new StringBuilder(1024);
  • 25 GetPrivateProfileString("CONFIG",key,"",s,1024,inifilepath);
  • 26 return s.ToString();
  • 27 }
  • 28
  • 29
  • 30 public static void SetValue(string key,string value)
  • 31 {
  • 32 try
  • 33 {
  • 34 WritePrivateProfileString("CONFIG", key, value, inifilepath);
  • 35 }
  • 36 catch (Exception ex)
  • 37 {
  • 38 throw ex;
  • 39 }
  • 40 }
  • 41 }
  • 42 }

我将 section 写死在代码中因为我是用不到其他的 section 的,各位有需要自己改一下方法参数就可以了。

调用:

  • 1 static void Main(string[] args)
  • 2 {
  • 3 INIhelp.SetValue("data", "abcdefg");
  • 4 INIhelp.SetValue("哈哈", "123456");
  • 5 INIhelp.SetValue("呵呵", "123456");
  • 6 INIhelp.SetValue("数据库", "123456");
  • 7 INIhelp.SetValue("123", "123456");
  • 8 Console.WriteLine("写入完成");
  • 9 Console.ReadLine();
  • 10
  • 11 string s = INIhelp.GetValue("data");
  • 12 Console.WriteLine(s);
  • 13 string a = INIhelp.GetValue("哈哈");
  • 14 Console.WriteLine(a);
  • 15 string b = INIhelp.GetValue("123");
  • 16 Console.WriteLine(b);
  • 17 Console.ReadLine();
  • 18 }

结果:

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门