您的位置:首页 > 编程语言 > C#

C#调用win32 API读写INI文件

2014-06-27 18:07 489 查看

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace INI
{
class ClassINI:IDisposable
{
[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 ref Val, int size, string filePath);

private bool bDisposed = false;
private string _FilePath = string.Empty;
public string FilePath
{
get
{
if (_FilePath == null)
return string.Empty;
else
return _FilePath;
}
set
{
if (_FilePath != value)
_FilePath = value;
}
}
///<summary>
///構造函數
///</summary>
///<param name="path">檔案路徑</param>
public ClassINI(string path)
{
_FilePath = path;
}
///<summary>
///析構函數
///</summary>
~ClassINI()
{
Dispose(false);
}

///<summary>
///釋放資源(程序設計師呼叫)
///</summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);    //要求系統不要呼叫指定物件的完成項
}
///<summary>
///釋放資源(給系統呼叫的)
///</summary>
protected virtual void Dispose(bool isDisposing)
{
if (bDisposed)
{
return;
}
if (isDisposing)
{

}
bDisposed = true;
}

///<summary>
///設定KeyValue值
///</summary>
///<param name="IN_Section">Section</param>
///<param name="IN_Key">Key</param>
///<param name="IN_Value">Value</param>
public void setKeyValue(string IN_Section,string IN_Key,string IN_Value)
{
WritePrivateProfileString(IN_Section, IN_Key, IN_Value, this._FilePath);
}

///<summary>
///取得Key相對的Value值
///</summary>
///<param name="IN_Section">Section</param>
///<param name="IN_Key">Key</param>
public string getKeyValue(string IN_Section, string IN_Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(IN_Section, IN_Key, "", temp, 255, this._FilePath);
return temp.ToString();
}

///<summary>
///取得key相對的value值,若無,則使用預設值(DefaulValue)
///</summary>
///<param name="Section">Section</param>
///<param name="Key">Key</param>
///<param name="DefaultValue">DefaultValue</param>
public string getKeyValue(string Section, string Key, string DefaultValue)
{
StringBuilder sbResult = null;

try
{
sbResult = new StringBuilder(255);
GetPrivateProfileString(Section, Key, "", sbResult, 255, this._FilePath);
return (sbResult.Length > 0) ? sbResult.ToString() : DefaultValue;
}
catch
{
return string.Empty;
}
}
}
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c#