C#操作Win32 API函數(shù)
C#語言有很多值得學習的地方,這里我們主要介紹C#操作Win32 API函數(shù),包括介紹section:INI文件中的段落名稱等方面。
C#操作Win32 API函數(shù)
C#并不像C++,擁有屬于自己的類庫。C#使用的類庫是.Net框架為所有.Net程序開發(fā)提供的一個共有的類庫——.Net FrameWork SDK。雖然.Net FrameWork SDK內(nèi)容十分龐大,功能也非常強大,但還不能面面俱到,至少它并沒有提供直接操作INI文件所需要的相關的類。在本文中,C#操作Win32 API函數(shù)——WritePrivateProfileString()和GetPrivateProfileString()函數(shù)。這二個函數(shù)都位于“kernel32.dll”文件中。
我們知道在C#中使用的類庫都是托管代碼(Managed Code)文件,而Win32的API函數(shù)所處的文件,都是非托管代碼(Unmanaged Code)文件。這就導致了在C#中不可能直接使用這些非托管代碼文件中的函數(shù)。好在.Net框架為了保持對下的兼容,也為了充分利用以前的資源,提出了互操作,通過互操作可以實現(xiàn)對Win32的API函數(shù)的調(diào)用?;ゲ僮鞑粌H適用于Win32的API函數(shù),還可以用來訪問托管的COM對象。C#中對 Win32的API函數(shù)的互操作是通過命名空間“System.Runtime.InteropServices”中的“DllImport”特征類來實現(xiàn)的。它的主要作用是指示此屬性化方法是作為非托管DLL的輸出實現(xiàn)的。下面代碼就是在C#利用命名空間 “System.Runtime.InteropServices”中的“DllImport”特征類申明上面二個Win32的API函數(shù):
C#操作Win32 API函數(shù):
- [ DllImport ( "kernel32" ) ]
- private static extern long WritePrivateProfileString ( string
- section ,
- string key , string val , string filePath ) ;
參數(shù)說明:section:INI文件中的段落;key:INI文件中的關鍵字;val:INI文件中關鍵字的數(shù)值;filePath:INI文件的完整的路徑和名稱。
C#申明INI文件的讀操作函數(shù)GetPrivateProfileString():
- [ DllImport ( "kernel32" ) ]
- private static extern int GetPrivateProfileString ( string section ,
- string key , string def , StringBuilder retVal ,
- int size , string filePath ) ;
參數(shù)說明:section:INI文件中的段落名稱;key:INI文件中的關鍵字;def:無法讀取時候時候的缺省數(shù)值;retVal:讀取數(shù)值;size:數(shù)值的大小;filePath:INI文件的完整路徑和名稱。
下面是一個讀寫INI文件的類
- public class INIClass
- {
- public string inipath;
- [DllImport("kernel32")]
- private static extern long WritePrivateProfileString
(string section,string key,string val,string filePath);- [DllImport("kernel32")]
- private static extern int GetPrivateProfileString
(string section,string key,string def,StringBuilder retVal,int size,string filePath);- ///
- /// 構造方法
- ///
- /// 文件路徑
- public INIClass(string INIPath)
- {
- inipath = INIPath;
- }
- ///
- /// 寫入INI文件
- ///
- /// 項目名稱(如 [TypeName] )
- /// 鍵
- /// 值
- public void IniWriteValue(string Section,string Key,string Value)
- {
- WritePrivateProfileString(Section,Key,Value,this.inipath);
- }
- ///
- /// 讀出INI文件
- ///
- /// 項目名稱(如 [TypeName] )
- /// 鍵
- public string IniReadValue(string Section,string Key)
- {
- StringBuilder temp = new StringBuilder(500);
- int i = GetPrivateProfileString(Section,Key,"",temp,500,this.inipath);
- return temp.ToString();
- }
- ///
- /// 驗證文件是否存在
- ///
- /// 布爾值
- public bool ExistINIFile()
- {
- return File.Exists(inipath);
- }
- }
【編輯推薦】