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

C# 对Ini文件读写

2008-07-30 18:15 381 查看
一、INI文件读写类INICLass
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;

namespace IniOperator
{
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);

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(500);
int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath);
return temp.ToString();
}
///
/// 验证文件是否存在
///
/// 布尔值
public bool ExistINIFile()
{
return File.Exists(inipath);
}
}
}

二、应用测试
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace IniOperator
{
public partial class Form1 : Form
{
private INIClass inic;
public Form1()
{
InitializeComponent();
}

private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Ini文件(*.ini)|*.ini|所有文件(*.*)|*.*";
ofd.FilterIndex = 0;
ofd.Title = "打开Ini文件";
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
inic = new INIClass(textBox1.Text);
}
}

private void button1_Click(object sender, EventArgs e)
{

if (inic.ExistINIFile())
{
try
{
inic.IniWriteValue(textBox2.Text, textBox3.Text, textBox4.Text);
this.toolStripStatusLabel1.Text = "写入成功";
}
catch (Exception ex)
{
this.toolStripStatusLabel1.Text = ex.Message;
}
}
}

private void button2_Click(object sender, EventArgs e)
{
try
{
textBox4.Text = inic.IniReadValue(textBox2.Text, textBox3.Text);
this.toolStripStatusLabel1.Text = textBox4.Text;
}
catch (Exception ex)
{
this.toolStripStatusLabel1.Text = ex.Message;
}
}

private void Form1_Load(object sender, EventArgs e)
{
string name = Dns.GetHostName();
this.toolStripStatusLabel1.Text = name;
IPHostEntry me = Dns.GetHostByName(name);
foreach (IPAddress ip in me.AddressList)
{ this.toolStripStatusLabel1.Text = this.toolStripStatusLabel1.Text+" IP:"+ip.ToString(); }
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: