1. 程式人生 > >C#操作Ini檔案類

C#操作Ini檔案類

      在Windows系統中,INI檔案是很多,最重要的就是“System.ini”、“System32.ini”和“Win.ini”。該檔案主要存放使用者所做的選擇以及系統的各種引數。使用者可以通過修改INI檔案,來改變應用程式和系統的很多配置。但自從Windows 95的退出,在Windows系統中引入了登錄檔的概念,INI檔案在Windows系統的地位就開始不斷下滑,這是因為登錄檔的獨特優點,使應用程式和系統都把許多引數和初始化資訊放進了登錄檔中。但在某些場合,INI檔案還擁有其不可替代的地位。由於C#類庫中並不包含讀取ini檔案,用C#讀取ini檔案,必要用到windows的API函式,所以在宣告windows的API函式必須這樣宣告:

         //宣告讀寫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檔案結構

INI檔案是一種按照特點方式排列的文字檔案。每一個INI檔案結構都非常類似,由若干段落(section)組成,在每個帶括號的標題下面,是若干個以單個單詞開頭的關鍵詞(keyword)和一個等號,等號右邊的就是關鍵字對應的值(value)。其一般形式如下:


  1. [Section1]  
  2. KeyWord1 = Valuel 
  3. KeyWord2 = Value2 
  4.  ……  
  5. [Section2]  
  6. KeyWord3 = Value3 
  7. KeyWord4 = Value4  
C#讀取INI檔案類
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Collections.Specialized;  
  6. using System.IO;  
  7. using System.Runtime.InteropServices;  
  8. using System.Windows.Forms;  
  9. namespace Comm  
  10. {  
  11.     /// <summary>
  12.     /// IniFiles的類
  13.     /// </summary>
  14.     publicclass IniFiles  
  15.     {  
  16.         publicstring FileName; //INI檔名
  17.         //string path   =   System.IO.Path.Combine(Application.StartupPath,"pos.ini");
  18.         //宣告讀寫INI檔案的API函式
  19.         [DllImport("kernel32")]  
  20.         privatestaticexternbool WritePrivateProfileString(string section, string key, string val, string filePath);  
  21.         [DllImport("kernel32")]  
  22.         privatestaticexternint GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);  
  23.         //類的建構函式,傳遞INI檔名
  24.         public IniFiles(string AFileName)  
  25.         {  
  26.             // 判斷檔案是否存在
  27.             FileInfo fileInfo = new FileInfo(AFileName);  
  28.             //Todo:搞清列舉的用法
  29.             if ((!fileInfo.Exists))  
  30.             { //|| (FileAttributes.Directory in fileInfo.Attributes))
  31.                 //檔案不存在,建立檔案
  32.                 StreamWriter sw = new StreamWriter(AFileName, false, System.Text.Encoding.Default);  
  33.                 //try
  34.                 //{  
  35.                 //    sw.Write("#表格配置檔案");  
  36.                 //    sw.Close();  
  37.                // }  
  38.                // catch
  39.               //  {  
  40.                //     throw (new ApplicationException("Ini檔案不存在"));  
  41.               //  }  
  42.             }  
  43.             //必須是完全路徑,不能是相對路徑
  44.             FileName = fileInfo.FullName;  
  45.         }  
  46.         //寫INI檔案
  47.         publicvoid WriteString(string Section, string Ident, string Value)  
  48.         {  
  49.             if (!WritePrivateProfileString(Section, Ident, Value, FileName))  
  50.             {  
  51.                 throw (new ApplicationException("寫Ini檔案出錯"));  
  52.             }  
  53.         }  
  54.         //讀取INI檔案指定
  55.         publicstring 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.             string s = Encoding.GetEncoding(0).GetString(Buffer);  
  61.             s = s.Substring(0, bufLen);  
  62.             return s.Trim();  
  63.         }  
  64.         //讀整數
  65.         publicint ReadInteger(string Section, string Ident, int Default)  
  66.         {  
  67.             string intStr = ReadString(Section, Ident, Convert.ToString(Default));  
  68.             try
  69.             {  
  70.                 return Convert.ToInt32(intStr);  
  71.             }  
  72.             catch (Exception ex)  
  73.             {  
  74.                 Console.WriteLine(ex.Message);  
  75.                 return Default;  
  76.             }  
  77.         }  
  78.         //寫整數
  79.         publicvoid WriteInteger(string Section, string Ident, int Value)  
  80.         {  
  81.             WriteString(Section, Ident, Value.ToString());  
  82.         }  
  83.         //讀布林
  84.         publicbool ReadBool(string Section, string Ident, bool Default)  
  85.         {  
  86.             try
  87.             {  
  88.                 return Convert.ToBoolean(ReadString(Section, Ident, Convert.ToString(Default)));  
  89.             }  
  90.             catch (Exception ex)  
  91.             {  
  92.                 Console.WriteLine(ex.Message);  
  93.                 return Default;  
  94.             }  
  95.         }  
  96.         //寫Bool
  97.         publicvoid WriteBool(string Section, string Ident, bool Value)  
  98.         {  
  99.             WriteString(Section, Ident, Convert.ToString(Value));  
  100.         }  
  101.         //從Ini檔案中,將指定的Section名稱中的所有Ident新增到列表中
  102.         publicvoid ReadSection(string Section, StringCollection Idents)  
  103.         {  
  104.             Byte[] Buffer = new Byte[16384];  
  105.             //Idents.Clear();
  106.             int bufLen = GetPrivateProfileString(Section, nullnull, Buffer, Buffer.GetUpperBound(0), FileName);  
  107.             //對Section進行解析
  108.             GetStringsFromBuffer(Buffer, bufLen, Idents);  
  109.         }  
  110.         privatevoid GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings)  
  111.         {  
  112.             Strings.Clear();  
  113.             if (bufLen != 0)  
  114.             {  
  115.                 int start = 0;  
  116.                 for (int i = 0; i < bufLen; i++)  
  117.                 {  
  118.                     if ((Buffer[i] == 0) && ((i - start) > 0))  
  119.                     {  
  120.                         String s = Encoding.GetEncoding(0).GetString(Buffer, start, i - start);  
  121.                         Strings.Add(s);  
  122.                         start = i + 1;  
  123.                     }  
  124.                 }  
  125.             }  
  126.         }  
  127.         //從Ini檔案中,讀取所有的Sections的名稱
  128.         publicvoid ReadSections(StringCollection SectionList)  
  129.         {  
  130.             //Note:必須得用Bytes來實現,StringBuilder只能取到第一個Section
  131.             byte[] Buffer = newbyte[65535];  
  132.             int bufLen = 0;  
  133.             bufLen = GetPrivateProfileString(nullnullnull, Buffer,  
  134.             Buffer.GetUpperBound(0), FileName);  
  135.             GetStringsFromBuffer(Buffer, bufLen, SectionList);  
  136.         }  
  137. 相關推薦

    C# 操作INI檔案

        //補充:        //using System;     //using System.Runtime.InteropServices;     //using System.Text;     //using System.Collections;    

    C#操作Ini檔案

          在Windows系統中,INI檔案是很多,最重要的就是“System.ini”、“System32.ini”和“Win.ini”。該檔案主要存放使用者所做的選擇以及系統的各種引數。使用者可以通過修改INI檔案,來改變應用程式和系統的很多配置。但自從Windows

    C#操作ini檔案

    詳細資訊直接在程式碼裡寫 首先看一下ini檔案的格式 一個鍵對應一個值 而"[網址資訊]"類似於專案名稱,將裡邊的內容分為一塊一塊就是方法中傳入的引數“Section” 對於ini檔案的註釋,必須在空的一行中進行註釋,否則像csdn=www.csdn.net;此為CSDN官方網址 程式碼在讀

    C# 操作INI檔案的函式 INIClass

    C# CODE: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace XXX {     public class INIClass

    c#之操作ini檔案

    原文地址:原文地址 public class Win32API { #region INI檔案操作 /* * 針對INI檔案的API操作方法,其中的節點(Section)、鍵(KEY)都不區分大小寫 *

    C# 操作INI配置檔案

    重構YH是遇到這個一樣問題,就是YH前臺頁面的按鈕要求實現客戶自定義,客戶可以跟隨自己的喜好安排每個按鈕的功能,所以,在每一次客戶登陸是就需要初始化客戶自定義排版,這裡就需要用到初始化檔案——INI。  .ini 檔案是Initialization File的縮寫,即初始化

    操作INI檔案函式

    操作INI檔案的函式主要有:   函式名 功能 備註 GetPrivateProfileInt         &nbs

    c#操作壓縮檔案(ICSharpCode)

     網上轉過來的,經測試很好用。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; usin

    c# 操作xml檔案,新增、刪除節點

    /// <summary> /// 刪除當前選擇節點 /// </summary> /// <param name="sender"></param>

    C/C++ 解析ini檔案

    C/C++ 解析ini檔案 c++版本 /* * inicpp.h * * Created on: 26 Dec 2015 * Author: Fabian Meyer * License: MIT */ #ifndef INICPP_H_ #define

    BCB對如何操作ini檔案

          .ini 檔案是Initialization File的縮寫,即初始化檔案,是windows的系統配置檔案所採用的儲存格式,統管windows的各項配置,在實際開發中, ini檔案的應

    C# 建立INI檔案,寫入並可讀取

      using System.Text; using System.IO; using System.Runtime.InteropServices; namespace HotelSystemORM.Unitl { public class IniFiles {

    python 操作ini檔案

    例子: [ZIP] EngineVersion=0 DATVersion=5127 FileName=dat-5127.zip FilePath=/pub/antivirus/datfiles/4.x/ FileS

    .NET平臺開源專案速覽(16)C#寫PDF檔案庫PDF File Writer介紹

        1年前,我在文章:這些.NET開源專案你知道嗎?.NET平臺開源文件與報表處理元件集合(三)中(第9個專案),給大家推薦了一個開源免費的PDF讀寫元件 PDFSharp,PDFSharp我2年前就看過,用過簡單的例子,不過程式碼沒有寫成專門的文章。最近在查詢資料的時候,又發現一款小巧的寫PDF檔案

    Linux下讀取Ini檔案

    #include "Ini.h" /****************************************************************************** * 功 能:建構函式 * 參 數:無 * 返回值:無 * 備 注: *********************

    VC操作INI檔案INI檔案操作總結,如何操作INI檔案INI檔案使用方法小結

      INI檔案簡介 在我們寫程式時,總有一些配置資訊需要儲存下來,以便在下一次啟動程式完成初始化,這實際上是一種類持久化。將一些資訊寫入INI檔案(initialization file)中,可完成簡單的持久化支援。 Windows提供了API介面用於操作INI檔案,其支援

    C#操作INI文件之Vini.cs的使用

    write 相對路徑 ref true rop except enc ram pat 目錄 概要 Constructor 構造器 VINI(string)

    c#操作pdf的

    1. Aspose. Pdf. Kit是個.NET 元件,用於編輯存在的PDF檔案。你可以利用它新增或移除數字簽名,加密或解密PDF檔案。它支援大量有用的功能,比如PDF圖章建立、新增CJK字型, 新增水印或Logo,解壓或新增圖片和文字,新增書籤,轉換PDF檔案為TIFF

    C#操作txt檔案以及注意事項

    特別注意:讀取亂碼的話,用Encoding.Default即可。(獲取系統的當前ANSI內碼表的編碼)讀取txt檔案   如果你要讀取的檔案內容不是很多,可以使用 File.ReadAllText(filePath) 或指定編碼方式 File.ReadAllText(File

    C#操作MySQL的

    and sfc comm delete class mar htable service clas C#操作MySQL的類 public class MySqlService { private static log4net.ILog