如何在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文件。[小节名]关键字=值关键字=值……MFC为用户读取ini文件提供了几个函数,其中常用的几个函数分别如下:读取信息:GetPrivateProfileString和GetPrivateProfileInt写入信息:WritePrivateProfileString运用这几个函数就可以满足常用的对字符串和整数的读写 *** 作了。为了体现MFC的封装性以及方便使用,我们可以定义一个接口,即一个纯虚类。所有的方法都由这个接口继承而来。我们将这个纯虚类命名为CCfgFile,之后我们从这个纯虚类中继承一个类(CIniFile)用来实现对ini文件的读取。以后若是需要一些更高级的方法可以再从CCfgFile继承出其他的类来实现。这样我们就可以利用CIniFile类中定义的函数来 *** 纵ini文件了。在程序中我们需要 *** 作ini文件中一些常用的配置参数读写,我们可以定义一个参数类来实现,如CParam这里需要注意的是在程序中我们可能在很多地方都要实现配置参数的读写,我们不能在每个要使用的地方都通过new关键字来创建一个CParam对象。原因你懂的,呵呵!那么我们可以通过定义CParam的一个静态成员来实现,这个静态成员通过一个静态的成员函数来获取。

namespace Library.File

{

public class Ini

{

// 声明INI文件的写 *** 作函数 WritePrivateProfileString()

[System.Runtime.InteropServices.DllImport("kernel32")]

private static extern long WritePrivateProfileString(string section, string key, string val, string filePath)

// 声明INI文件的读 *** 作函数 GetPrivateProfileString()

[System.Runtime.InteropServices.DllImport("kernel32")]

private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath)

private string sPath = null

public Ini(string path)

{

this.sPath = path

}

public void Writue(string section, string key, string value)

{

// section=配置节,key=键名,value=键值,path=路径

WritePrivateProfileString(section, key, value, sPath)

}

public string ReadValue(string section, string key)

{

// 每次从ini中读取多少字节

System.Text.StringBuilder temp = new System.Text.StringBuilder(255)

// section=配置节,key=键名,temp=上面,path=路径

GetPrivateProfileString(section, key, "", temp, 255, sPath)

return temp.ToString()

}

}

}

开始调用函数。

// 写入ini

Ini ini = new Ini("C:/config.ini")

ini.Writue("Setting", "key1", "HELLO WORLD!")

ini.Writue("Setting", "key2", "HELLO CHINA!")

// 读取ini

Ini ini = new Ini("C:/config.ini")

string str1 = ini.ReadValue("Setting", "key1")

MessageBox.Show(str1)

二,在一些小的应用中,有时候不需要使用数据困这样大规模的数据管理工具,也很少进行数据的查询、修改等 *** 作,而仅用文件来存储数据。这时就需要使用。net中的文件 *** 作对象,如file、streamReader、streamWriter等。

1,使用File对象 *** 作文件

System.IO.File类提供了一系类的静态办法,完成对晚间的常用 *** 作,如新建、删除、拷贝、移动等

2,使用StreamWriter写入文件

在System.IO空间中定义了一个文件写入器对象StreamWriter,使用它可以以一种特定的编码向输出流中(Stream)写入字符。

3,使用SteamReader 读取文件

与streamWrite对应

文章转载自网管之家:http://www.bitscn.com/pdb/dotnet/201003/181956_2.html


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

原文地址: https://outofmemory.cn/tougao/12079698.html

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

发表评论

登录后才能评论

评论列表(0条)

保存