C# 簡單讀寫ini文件幫助類 INIHelp


軟件里需要讀取一些初始化信息,

決定用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         }

 

結果:

 

 

 

參考:http://www.cnblogs.com/wangsaiming/archive/2011/04/25/2028601.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM