[C#] C#进行INI文件的读写操作 →→→→→进入此内容的聊天室

来自 , 2021-02-24, 写在 C#, 查看 130 次.
URL http://www.code666.cn/view/147540e1
  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. using System.Collections;
  6. using System.Collections.Specialized;
  7.  
  8. namespace wuyisky{
  9.   /**//**/
  10.   /**//// <summary>
  11.   /// IniFiles的类
  12.   /// </summary>
  13.   public class IniFiles
  14.   {
  15.     public string FileName; //INI文件名
  16.     //声明读写INI文件的API函数
  17.     [DllImport("kernel32")]
  18.     private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
  19.     [DllImport("kernel32")]
  20.     private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
  21.     //类的构造函数,传递INI文件名
  22.     public IniFiles(string AFileName)
  23.     {
  24.       // 判断文件是否存在
  25.       FileInfo fileInfo = new FileInfo(AFileName);
  26.       //Todo:搞清枚举的用法
  27.       if ((!fileInfo.Exists))
  28.       { //|| (FileAttributes.Directory in fileInfo.Attributes))
  29.         //文件不存在,建立文件
  30.         System.IO.StreamWriter sw = new System.IO.StreamWriter(AFileName, false, System.Text.Encoding.Default);
  31.         try
  32.         {
  33.           sw.Write("#表格配置档案");
  34.           sw.Close();
  35.         }
  36.  
  37.         catch
  38.         {
  39.           throw (new ApplicationException("Ini文件不存在"));
  40.         }
  41.       }
  42.       //必须是完全路径,不能是相对路径
  43.       FileName = fileInfo.FullName;
  44.     }
  45.     //写INI文件
  46.     public void WriteString(string Section, string Ident, string Value)
  47.     {
  48.       if (!WritePrivateProfileString(Section, Ident, Value, FileName))
  49.       {
  50.  
  51.         throw (new ApplicationException("写Ini文件出错"));
  52.       }
  53.     }
  54.     //读取INI文件指定
  55.     public string ReadString(string Section, string Ident, string Default)
  56.     {
  57.       Byte[] Buffer = new Byte[65535];
  58.       int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(0), FileName);
  59.       //必须设定0(系统默认的
  60. //csharp/1134

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

这儿你可以回复上面这条便签

captcha