如何在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"的文件。\x0d\x0a其一般形式如下:\x0d\x0a[section1]// 配置节\x0d\x0a//键名 //键值\x0d\x0akeyword1 = valuel\x0d\x0akeyword2 = value2\x0d\x0a??\x0d\x0a[section2]\x0d\x0akeyword3 = value3\x0d\x0akeyword4 = value4\x0d\x0a在Windows系统中,INI文件是很多,最重要的就是"System.ini"、"System32.ini"和"Win.ini"。该文件主要存放用户所做的选择以及系统的各种参数。用户可以通过修改INI文件,来改变应用程序和系统的很多配置。但自从Windows 95的退出,在Windows系统中引入了注册表的概念,INI文件在Windows系统的地位就开始不断下滑,这是因为注册表的独特优点,使应用程序和系统都把许多参数和初始化信息放进了注册表中。以及XML文件的国际标准化给INI文件又一次打击。\x0d\x0a但在某些场合,INI文件还拥有其不可替代的地位。比如绿色软件的规定就是不向注册表和系统中填入新东西。对于软件需要储存的信息就需要存入到文件中了。XML虽然兼容性比较好,但对于仅仅保存几个自定义参数而言就显得大材小用了。这是就可以选择使用快速简单的储存方式:INI文件。\x0d\x0a本文就来探讨一下C#是如何对INI进行读写 *** 作。\x0d\x0a主要思路是调用Win32 API。\x0d\x0a1.引入命名空间\x0d\x0ausingSystem.Runtime.InteropServices\x0d\x0a2.声明(把一个Win32 API函数转成C#函数)\x0d\x0a//声明INI文件的写 *** 作函数 WritePrivateProfileString()\x0d\x0a[DllImport("kernel32")]\x0d\x0aprivate static extern longWritePrivateProfileString(string section, string key, string val, stringfilePath)\x0d\x0a//声明INI文件的读 *** 作函数 GetPrivateProfileString()\x0d\x0a[DllImport("kernel32")]\x0d\x0aprivate static extern intGetPrivateProfileString(string section, string key, string def, StringBuilderretVal, int size, string filePath)\x0d\x0a3.函数\x0d\x0apublic void Writue(string section,string key, string value)\x0d\x0a{\x0d\x0a// section=配置节,key=键名,value=键值,path=路径\x0d\x0aWritePrivateProfileString(section,key, value, sPath)\x0d\x0a}\x0d\x0apublic string ReadValue(stringsection, string key)\x0d\x0a{\x0d\x0a// 每次从ini中读取多少字节\x0d\x0aSystem.Text.StringBuilder temp =new System.Text.StringBuilder(255)\x0d\x0a// section=配置节,key=键名,temp=上面,path=路径\x0d\x0aGetPrivateProfileString(section,key, "", temp, 255, sPath)\x0d\x0areturntemp.ToString()//注意类型的转换\x0d\x0a}\x0d\x0a到此基本功能已经实现了。下面我们将所有的代码重新整合一下:\x0d\x0anamespace Library.File\x0d\x0a{\x0d\x0apublic class Ini\x0d\x0a{\x0d\x0a// 声明INI文件的写 *** 作函数 WritePrivateProfileString()\x0d\x0a[System.Runtime.InteropServices.DllImport("kernel32")]\x0d\x0aprivate static extern longWritePrivateProfileString(string section, string key, string val, stringfilePath)\x0d\x0a// 声明INI文件的读 *** 作函数 GetPrivateProfileString()\x0d\x0a[System.Runtime.InteropServices.DllImport("kernel32")]\x0d\x0aprivate static extern intGetPrivateProfileString(string section, string key, string def,System.Text.StringBuilder retVal, int size, string filePath)\x0d\x0aprivate string sPath = null\x0d\x0apublic Ini(string path)\x0d\x0a{\x0d\x0athis.sPath = path\x0d\x0a}\x0d\x0apublic void Writue(string section,string key, string value)\x0d\x0a{\x0d\x0a// section=配置节,key=键名,value=键值,path=路径\x0d\x0aWritePrivateProfileString(section,key, value, sPath)\x0d\x0a}\x0d\x0apublic string ReadValue(stringsection, string key)\x0d\x0a{\x0d\x0a// 每次从ini中读取多少字节\x0d\x0aSystem.Text.StringBuilder temp =new System.Text.StringBuilder(255)\x0d\x0a// section=配置节,key=键名,temp=上面,path=路径\x0d\x0aGetPrivateProfileString(section,key, "", temp, 255, sPath)\x0d\x0areturn temp.ToString()\x0d\x0a}\x0d\x0a}\x0d\x0a}\x0d\x0a开始调用函数。\x0d\x0a// 写入ini\x0d\x0aIni ini = newIni("C:/config.ini")\x0d\x0aini.Writue("Setting","key1", "HELLO WORLD!")\x0d\x0aini.Writue("Setting","key2", "HELLO CHINA!")\x0d\x0a// 读取ini\x0d\x0aIni ini = newIni("C:/config.ini")\x0d\x0astring str1 =ini.ReadValue("Setting", "key1")\x0d\x0aMessageBox.Show(str1)\x0d\x0a二,在一些小的应用中,有时候不需要使用数据困这样大规模的数据管理工具,也很少进行数据的查询、修改等 *** 作,而仅用文件来存储数据。这时就需要使用。net中的文件 *** 作对象,如file、streamReader、streamWriter等。\x0d\x0a1,使用File对象 *** 作文件\x0d\x0aSystem.IO.File类提供了一系类的静态办法,完成对晚间的常用 *** 作,如新建、删除、拷贝、移动等\x0d\x0a2,使用StreamWriter写入文件\x0d\x0a在System.IO空间中定义了一个文件写入器对象StreamWriter,使用它可以以一种特定的编码向输出流中(Stream)写入字符。\x0d\x0a3,使用SteamReader读取文件\x0d\x0a与streamWrite对应

C++读取ini文件,根据key值取其value

#include <iostream>

#include <string>

#include <fstream>

#include <iomanip.h>

using namespace std

int read_file(char *file, char *key) {

ifstream file_op(file, ios::in)

if (!file_op) {

cout<<"Can not open file"<<endl

return EXIT_FAILURE

}

string line

while (getline(file_op, line) ) {

int i = line.find(key, 0)//从0位开始找

if (i==0) {//找到了key值

int k = line.find("=", 0)//找等于号

string value=line.substr(k+1)//取等于号后边的值

cout<<value<<endl

}

}

file_op.close()

return 0

}

int main() {

int i = read_file("D:\\TEST.ini", "APVersion")

return i

}


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

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

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

发表评论

登录后才能评论

评论列表(0条)

保存