C#進行INI文件的讀寫操作

bdnp 9年前發布 | 2K 次閱讀 C# 算法

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(系統默認的</pre>

 本文由用戶 bdnp 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!