C# Winform 調用系統(tǒng)接口操作 INI 配置文件的代碼
更新時間:2011年05月14日 16:00:44 作者:
封裝了一小段代碼, 調用系統(tǒng)接口, 操作配置文件. 一般用于 .ini 文件, 或者其它鍵值對格式的配置文件
包括了寫入和讀取功能. 寫入的時候, 如果文件不存在會自動創(chuàng)建. 如果對應的鍵已經存在, 則自動覆蓋它的值. 讀取的時候, 如果對應的文件不存在, 或者鍵名不存在, 則返回一個 empty 值. 非常方便 ^_^
// 系統(tǒng)接口類
public static class WinAPI
{
[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 static void ProfileWriteValue(
string section, string key, string value, string path)
{
WritePrivateProfileString(section, key, value, path);
}
// 讀取配置文件的值
public static string ProfileReadValue(
string section, string key, string path)
{
StringBuilder sb = new StringBuilder(255);
GetPrivateProfileString(section, key, "", sb, 255, path);
return sb.ToString().Trim();
}
}
復制代碼 代碼如下:
// 系統(tǒng)接口類
public static class WinAPI
{
[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 static void ProfileWriteValue(
string section, string key, string value, string path)
{
WritePrivateProfileString(section, key, value, path);
}
// 讀取配置文件的值
public static string ProfileReadValue(
string section, string key, string path)
{
StringBuilder sb = new StringBuilder(255);
GetPrivateProfileString(section, key, "", sb, 255, path);
return sb.ToString().Trim();
}
}
相關文章
C#實現導出List數據到xml文件的方法【附demo源碼下載】
這篇文章主要介紹了C#實現導出List數據到xml文件的方法,涉及C#針對list類及xml文件的相關操作技巧,并附帶完整demo源碼供讀者下載參考,需要的朋友可以參考下2016-08-08
C# Environment.CurrentDirectory 靜態(tài)屬性的實現
本文主要介紹了C# Environment.CurrentDirectory 靜態(tài)屬性的實現,它返回當前應用程序的工作目錄路徑,具有一定的參考價值,感興趣的可以了解一下2024-02-02

