如何在C#中读写INI文件

如何在C#中读写INI文件,第1张

INI文件就是扩展名为 ini 的文件 在Windows系统中 INI文件是很多 最重要的就是 System ini System ini 和 Win ini 该文件主要存放用户所做的选择以及系统的各种参数 用户可以通过修改INI文件 来改变应用程序和系统的很多配置 但自从Windows 的退出 在Windows系统滑大中引入了注册表的概念 INI文件在Windows系统的地位就开始不断下滑 这是因为注册表的独特优点 使应用程序和系统都把许多参数和初始化信息放进了注册表中 但在某些场合 INI文件还拥有其不可替代的地位 本文就来探讨一下C#是如何对INI进行读写 *** 作 INI文件的结构 INI文件是一种按照特点方式排列的文本文件 每一个INI文件构成都非常类似 由若干段落(section)组迟老成 在每个带括号的标题下面 是若干个以单个单词开头的关键词(keyword)和一个等号 等号右边的就是关键字对应的值(value) 其一般形式如下

[Section ] KeyWord = Valuel KeyWord = Value  …… [Section ] KeyWord = Value KeyWord = Value

C#和Win API函数 C#并不像C++ 拥有属于自己的类库 C#使用的类库是 Net框架为所有 Net程序开发提供的一个共有的类库—— Net FrameWork SDK 虽然 Net FrameWork SDK内容十分庞大 功能也非常强大 但还不能面面俱到 至少它并没有提供直接 *** 作INI文件所需要的相关的类 在本文中 C# *** 作INI文件使用的是Windows系统自带Win 的API函数——WritePrivateProfileString()和GetPrivateProfileString()函数 这二个函数都位于 kernel dll 文件中 我们知道在C#中使用的类库都是托管代码(Managed Code)文件 而Win 的API函数所处的文件 都是非托管代码(Unmanaged Code)文件 这就导致了在C#中不可能直接使用这些非托管代码文件中的函数 好在 Net框架为了保持对下的兼容 也为了充分利用以前的资源 提出了互 *** 作 通过互 *** 作可以实现对Win 的API函数的调用 互 *** 作不仅适用于Win 的API函数 还可以用来访问托管的对象 C#中对Win 的API函数的互 *** 作是通过命名空间 System Runtime InteropServices 中的 DllImport 特征类来实现的 它的主要作用是指示此属性化方法是作为非托管DLL的输出实现的 下面代码就是在C#利用命名空间 System Runtime InteropServices 中的 DllImport 特征类申明上面二个Win 的API函数 C#申明INI文件的写 *** 作函数WritePrivateProfileString() [ DllImport ( kernel ) ] private static extern long WritePrivateProfileString ( string section string key string val string filePath ) 参数说明 section INI文件中的段落 key INI文件中的关键字 val INI文件中关键字的数值 filePath INI文件的完整的路径和名称 C#申明INI文件的读 *** 作函数GetPrivateProfileString() [ DllImport ( kernel ) ] private static extern int GetPrivateProfileString ( string section string key string def StringBuilder retVal int size string filePath ) 参数说明 section INI文件中的段落信旦竖名称 key INI文件中的关键字 def 无法读取时候时候的缺省数值 retVal 读取数值 size 数值的大小 filePath INI文件的完整路径和名称 下面是一个读写INI文件的类

public class INIClass { public string inipath[DllImport( kernel )] private static extern long WritePrivateProfileString(string section string key string val string filePath)[DllImport( kernel )] 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( )int i = GetPrivateProfileString(Section Key temp this inipath)return temp ToString()} /// /// 验证文件是否存在 /// /// 布尔值 public bool ExistINIFile() { return File Exists(inipath)} }

C#对INI文件进行写 *** 作 对INI文件进行写 *** 作 是通过组件button 的 Click 事件来实现的 这里有一点应该注意 当在调用WritePrivateProfileString()对INI文件进行写 *** 作的时候 如果此时在INI文件中存在和要写入的信息相同的段落名称和关键字 则将覆盖此INI信息 下面是button 组件的 Click 事件对应的代码清单

private void button _Click ( object sender System EventArgs e )

{

string FileName = textBox Text

string section = textBox Text

string key = textBox Text

string keyValue = textBox Text

WritePrivateProfileString ( section key keyValue FileName )

MessageBox Show  ( 成功写入INI文件! 信息 )

}

C#对INI文件进行读 *** 作 正确读取INI的必须满足三个前提 INI文件的全路径 段落名称和关键字名称 否则就无法正确读取 你可以设定读取不成功后的缺省数值 在下面的程序中 为了直观设定的是 无法读取对应数值! 字符串 读取INI文件是通过button 组件的 Click 事件来实现的 下面是其对应的代码清单

private void button _Click ( object sender System EventArgs e )

{

StringBuilder temp = new StringBuilder ( )

string FileName = textBox Text

string section = textBox Text

string key = textBox Text

int i = GetPrivateProfileString ( section key 无法读取对应数值!

temp FileName )

//显示读取的数值

textBox Text = temp ToString  ( )

}

using System

using System Drawing

using System Collections

using System ComponentModel

using System Windows Forms

using System Data

using System Runtime InteropServices

using System Text

namespace C_ *** 作INI文件__写 *** 作

{

public class Form : System Windows Forms Form

{

private System Windows Forms Button button

private System Windows Forms TextBox textBox

private System Windows Forms Button button

private System Windows Forms TextBox textBox

private System Windows Forms TextBox textBox

private System Windows Forms TextBox textBox

private System Windows Forms Label label

private System Windows Forms Label label

private System Windows Forms Label label

private System Windows Forms Button button

private System Windows Forms OpenFileDialog openFileDialog

private System ComponentModel Container ponents = null

public Form ( )

{

InitializeComponent ( )

}

protected override void Dispose (  bool disposing  )

{

if (  disposing  )

{

if  ( ponents != null ) 

{

ponents Dispose ( )

}

}

base Dispose (  disposing  )

}

[ DllImport ( kernel ) ]

private static extern long WritePrivateProfileString ( string

section

string key string val string filePath )

[ DllImport ( kernel ) ]

private static extern int GetPrivateProfileString ( string section

string key string def StringBuilder retVal

int size string filePath )

private void InitializeComponent ( )

{

this button = new System Windows Forms Button ( )

this textBox = new System Windows Forms TextBox ( )

this button = new System Windows Forms Button ( )

this textBox = new System Windows Forms TextBox ( )

this textBox = new System Windows Forms TextBox ( )

this textBox = new System Windows Forms TextBox ( )

this label = new System Windows Forms Label ( )

this label = new System Windows Forms Label ( )

this label = new System Windows Forms Label ( )

this button = new System Windows Forms Button ( )

this openFileDialog = new

System Windows Forms OpenFileDialog ( )

this SuspendLayout ( )

this button FlatStyle = System Windows Forms FlatStyle Flat

this button Location = new System Drawing Point ( )

this button Name = button

this button Size = new System Drawing Size ( )

this button TabIndex =

this button Text = 选择INI文件

this button Click += new System EventHandler ( this button _Click )

this textBox Location = new System Drawing Point ( )

this textBox Name = textBox

this textBox Size = new System Drawing Size ( )

this textBox TabIndex =

this textBox Text =

this button FlatStyle = System Windows Forms FlatStyle Flat

this button Location = new System Drawing Point ( )

this button Name = button

this button Size = new System Drawing Size ( )

this button TabIndex =

this button Text = 写入INI文件

this button Click += new System EventHandler ( this button _Click )

this textBox Location = new System Drawing Point ( )

this textBox Name = textBox

this textBox Size = new System Drawing Size ( )

this textBox TabIndex =

this textBox Text =

this textBox Location = new System Drawing Point ( )

this textBox Name = textBox

this textBox Size = new System Drawing Size ( )

this textBox TabIndex =

this textBox Text =

this textBox Location = new System Drawing Point ( )

this textBox Name = textBox

this textBox Size = new System Drawing Size ( )

this textBox TabIndex =

this textBox Text =

this label Location = new System Drawing Point ( )

this label Name = label

this label TabIndex =

this label Text = 段落名称

this label Location = new System Drawing Point ( )

this label Name = label

this label TabIndex =

this label Text = 关键字

this label Location = new System Drawing Point ( )

this label Name = label

this label TabIndex =

this label Text = 关键字数值

this button FlatStyle = System Windows Forms FlatStyle Flat

this button Location = new System Drawing Point ( )

this button Name = button

this button Size = new System Drawing Size ( )

this button TabIndex =

this button Text = 读取INI数值

this button Click += new System EventHandler ( this button _Click )

this openFileDialog Filter = INI 文件|* ini

this AutoScaleBaseSize = new System Drawing Size ( )

this ClientSize = new System Drawing Size ( )

this Controls AddRange ( new System Windows Forms Control [ ] {

this button

this textBox

this textBox

this textBox

this button

this textBox

this button

this label

this label

this label } )

this MaximizeBox = false

this Name = Form

this Text = C# *** 作INI文件 写 *** 作

this ResumeLayout ( false )

}

[STAThread]

static void Main ( ) 

{

Application Run ( new Form ( )  )

}

private void button _Click ( object sender System EventArgs e )

{

openFileDialog ShowDialog ( )

textBox Text = openFileDialog FileName

}

//写入INI文件

private void button _Click ( object sender System EventArgs e )

{

string FileName = textBox Text

string section = textBox Text

string key = textBox Text

string keyValue = textBox Text

WritePrivateProfileString ( section key keyValue FileName )

MessageBox Show  ( 成功写入INI文件! 信息 )

}

//读取指定INI文件的特定段落中的关键字的数值

private void button _Click ( object sender System EventArgs e )

{

this Controls AddRange ( new System Windows Forms Control [ ] {

this button

this textBox

this textBox

this textBox

this button

this textBox

this button

this label

this label

this label } )

this MaximizeBox = false

this Name = Form

this Text = C# *** 作INI文件 写 *** 作

this ResumeLayout ( false )

}

[STAThread]

static void Main ( ) 

{

Application Run ( new Form ( )  )

}

private void button _Click ( object sender System EventArgs e )

{

openFileDialog ShowDialog ( )

textBox Text = openFileDialog FileName

}

//写入INI文件

private void button _Click ( object sender System EventArgs e )

{

string FileName = textBox Text

string section = textBox Text

string key = textBox Text

string keyValue = textBox Text

WritePrivateProfileString ( section key keyValue FileName )

MessageBox Show  ( 成功写入INI文件! 信息 )

}

//读取指定INI文件的特定段落中的关键字的数值

private void button _Click ( object sender System EventArgs e )

{

StringBuilder temp = new StringBuilder ( )

string FileName = textBox Text

string section = textBox Text

string key = textBox Text

int i = GetPrivateProfileString ( section key

无法读取对应数值! emp FileName )

//显示读取的数值

textBox Text = temp ToString  ( )

}

}

}

总结

通过上面的这些介绍 可以看成C# *** 作INI文件的过程 其实就是C#调用Win 的API函数的过程 掌握了如何在C#申明Win 的API函数 再来 *** 作INI就显得非常简单

lishixinzhi/Article/program/ASP/201311/21793

INI文件的结构

INI文件是一种按照特点方式排列的文本做颂迅文件。每一个INI文件构成都非常类似,由若干段落(section)组成,在每个带括号的标题樱晌下面,是若干个以单个单词开头的关键词(keyword)和一个等号,等号右边的就是关键字对应的值(value)。其一般形式如下:

[Section1]

KeyWord1 = Valuel

KeyWord2 = Value2

……

[Section2]

KeyWord3 = Value3

KeyWord4 = Value4

C#和Win32 API函数

C#并不像C++,拥有属于自己的类库。C#使用的类库是.Net框架为所有.Net程序开发提供的一个共有的类库——.Net FrameWork SDK。虽然.Net FrameWork SDK内容十分庞大,功能也非常强大,但还不能面面俱到,至少它并没有提供直接 *** 作INI文件所纯此需要的相关的类。在本文中,C# *** 作INI文件使用的是Windows系统自带Win32的API函数——WritePrivateProfileString()和GetPrivateProfileString()函数。这二个函数都位于“kernel32.dll”文件中。

我们知道在C#中使用的类库都是托管代码(Managed Code)文件,而Win32的API函数所处的文件,都是非托管代码(Unmanaged Code)文件。这就导致了在C#中不可能直接使用这些非托管代码文件中的函数。好在.Net框架为了保持对下的兼容,也为了充分利用以前的资源,提出了互 *** 作,通过互 *** 作可以实现对Win32的API函数的调用。互 *** 作不仅适用于Win32的API函数,还可以用来访问托管的COM对象。C#中对Win32的API函数的互 *** 作是通过命名空间“System.Runtime.InteropServices”中的“DllImport”特征类来实现的。它的主要作用是指示此属性化方法是作为非托管DLL的输出实现的。下面代码就是在C#利用命名空间“System.Runtime.InteropServices”中的“DllImport”特征类申明上面二个Win32的API函数:

C#申明INI文件的写 *** 作函数WritePrivateProfileString():

[ DllImport ( "kernel32" ) ]

private static extern long WritePrivateProfileString ( string

section ,

string key , string val , string filePath )

参数说明:section:INI文件中的段落;key:INI文件中的关键字;val:INI文件中关键字的数值;filePath:INI文件的完整的路径和名称。

C#申明INI文件的读 *** 作函数GetPrivateProfileString():

[ DllImport ( "kernel32" ) ]

private static extern int GetPrivateProfileString ( string section ,

string key , string def , StringBuilder retVal ,

int size , string filePath )

参数说明:section:INI文件中的段落名称;key:INI文件中的关键字;def:无法读取时候时候的缺省数值;retVal:读取数值;size:数值的大小;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)

/// <summary>

/// 构造方法

/// </summary>

/// <param name="INIPath">文件路径</param>

public INIClass(string INIPath)

{

inipath = INIPath

}

/// <summary>

/// 写入INI文件

/// </summary>

/// <param name="Section">项目名称(如 [TypeName] )</param>

/// <param name="Key">键</param>

/// <param name="Value">值</param>

public void IniWriteValue(string Section,string Key,string Value)

{

WritePrivateProfileString(Section,Key,Value,this.inipath)

}

/// <summary>

/// 读出INI文件

/// </summary>

/// <param name="Section">项目名称(如 [TypeName] )</param>

/// <param name="Key">键</param>

public string IniReadValue(string Section,string Key)

{

StringBuilder temp = new StringBuilder(500)

int i = GetPrivateProfileString(Section,Key,"",temp,500,this.inipath)

return temp.ToString()

}

/// <summary>

/// 验证文件是否存在

/// </summary>

/// <returns>布尔值</returns>

public bool ExistINIFile()

{

return File.Exists(inipath)

}

}

android编程iniini文件读写的方法为:

一.将信息写入.INI文件中

1.所用的WINAPI函数原型为:

BOOL WritePrivateProfileString(

LPCTSTR lpAppName,

LPCTSTR lpKeyName,

LPCTSTR lpString,

LPCTSTR lpFileName

)

其中各参数的意义:

LPCTSTR lpAppName 是INI文件中的一个字段名.

LPCTSTR lpKeyName 是lpAppName下的一个键名,通俗讲就是变量名.

PCTSTR lpString 是键值,也就是变量的值,不过必须为LPCTSTR型或CString型的.

LPCTSTR lpFileName 是完整的INI文件名.

2.具体使用方法:设现有一名学生,需把他的姓段并中名和年龄写入 c:/stud/student.ini 文件中.

CString strName,strTemp

int nAge

strName="张三"

nAge=12

::WritePrivateProfileString("StudentInfo","Name",strName,"c://stud//student.ini")

此时c:/stud/student.ini文件中的内容如下:

[StudentInfo]

Name=张三

.要将学生的年龄保存下来,只需将整型的值变为字符型即可:

strTemp.Format("%d",nAge)

::WritePrivateProfileString("StudentInfo","Age",strTemp,"c://stud//student.ini")

二.将信息从INI文件中读入程序中的变量.

1.所用的WINAPI函数原型为:

DWORD GetPrivateProfileString(

LPCTSTR lpAppName,

LPCTSTR lpKeyName,

LPCTSTR lpDefault,

LPTSTR lpReturnedString,

DWORD nSize,

LPCTSTR lpFileName

)

其中各参数的意义:

前二个参数与 WritePrivateProfileString中的意义一样.

lpDefault : 如果INI文件中没有前两个参数指定的字段名或键名,则将此值赋给变量.

lpReturnedString : 接收INI文件中的值的CString对象,即目的缓存器.

nSize : 目的缓蔽衡存器的大小.

lpFileName : 是完整的INI文件名.

2.具体使用方法:现要将上一步中写入的学生的信息读入程序中.

CString strStudName

int nStudAge

GetPrivateProfileString("StudentInfo","Name","默认姓名",strStudName.GetBuffer(MAX_PATH),MAX_PATH,"c://stud//student.ini")

执行后 strStudName 的值为:"张三握山",若前两个参数有误,其值为:"默认姓名".

3.读入整型值要用另一个WINAPI函数:

UINT GetPrivateProfileInt(

LPCTSTR lpAppName,

LPCTSTR lpKeyName,

INT nDefault,

LPCTSTR lpFileName

)

这里的参数意义与上相同.使用方法如下:

nStudAge=GetPrivateProfileInt("StudentInfo","Age",10,"c://stud//student.ini")

三.循环写入多个值,设现有一程序,要将最近使用的几个文件名保存下来,具体程序如下:

1.写入:

CString strTemp,strTempA

int i

int nCount=6

file://共有6个文件名需要保存

for(i=0i {strTemp.Format("%d",i)

strTempA=文件名

file://文件名可以从数组,列表框等处取得.

::WritePrivateProfileString("UseFileName","FileName"+strTemp,strTempA,"c://usefile//usefile.ini")

}

strTemp.Format("%d",nCount)

::WritePrivateProfileString("FileCount","Count",strTemp,"c://usefile//usefile.ini")

2.读出:

nCount=::GetPrivateProfileInt("FileCount","Count",0,"c://usefile//usefile.ini")

for(i=0i {strTemp.Format("%d",i)

strTemp="FileName"+strTemp

::GetPrivateProfileString("CurrentIni",strTemp,"default.fil", strTempA.GetBuffer(MAX_PATH),MAX_PATH,"c://usefile//usefile.ini")

file://使用strTempA中的内容.

}

补充四点:

1.INI文件的路径必须完整,文件名前面的各级目录必须存在,否则写入不成功,该函数返回 FALSE 值.

2.文件名的路径中必须为 // ,因为在VC++中, // 才表示一个 / .

3.也可将INI文件放在程序所在目录,此时 lpFileName 参数为: ".//student.ini".

4.从网页中粘贴源代码时,最好先粘贴至记事本中,再往VC中粘贴,否则易造成编译错误,开始时我也十分不解,好好的代码怎么就不对呢?后来才找到这个方法.还有一些代码中使用了全角字符如:<,\等,也会

造成编译错误.


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12192494.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存