using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
namespace inifile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//textBox1.Text = readfile();
//writefile("ttt");
string a = textBox1.Text;
writefile(a);
}
public static string readfile()
{
string iniserver;
string inidatabase;
string iniuid;
string inipsw;
ReadIniFile file = new ReadIniFile(@"D:test.INI");
string inifilename = file.FileName();
bool isexist = file.ExistINIFile();
string strConn = "";
if (file.ExistINIFile())
{
iniserver = file.GetString("sql", "server");
inidatabase = file.GetString("sql", "database");
iniuid = file.GetString("sql", "uid");
inipsw = file.GetString("sql", "psw");
strConn = "server=" + iniserver + ";uid=" + iniuid + ";pwd=" + inipsw + ";database=" + inidatabase + ";";
}
else
{
MessageBox.Show("配置文件不存在!");
}
return strConn;
}
public static void writefile(string test)
{
ReadIniFile file = new ReadIniFile(@"D:test.INI");
string inifilename = file.FileName();
bool isexist = file.ExistINIFile();
string yyy = test;
if (file.ExistINIFile())
{
file.WriteInt("kkkk", "age", 12);
file.WriteInt("kkkk", "page", 37);
file.WriteString("ffff", "mayname", yyy);
}
else
{
MessageBox.Show("配置文件不存在!");
}
}
}
class ReadIniFile
{
public string fileName;
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(
string lpAppName,// 指向包含 Section 名称的字符串地址
string lpKeyName,// 指向包含 Key 名称的字符串地址
string lpDefault,// 如果 Key 值没有找到,则返回缺省的字符串的地址
StringBuilder lpReturnedString,// 返回字符串的缓冲区地址
int nSize,// 缓冲区的长度
string lpFileName
);
[DllImport("kernel32")]
private static extern bool WritePrivateProfileString(
string lpAppName,
string lpKeyName,
string lpString,
string lpFileName
);
public ReadIniFile(string filename)
{
this.fileName = filename;
}
public string GetString(string section, string key)
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(section, key, "", temp, 1024, this.fileName);
return temp.ToString();
}
public bool ExistINIFile()
{
return File.Exists(this.fileName);
}
public string FileName()
{
return this.fileName;
}
public void WriteInt(string section, string key, int iVal)
{
WritePrivateProfileString(section, key, iVal.ToString(), fileName);
}
public void WriteString(string section, string key, string strVal)
{
WritePrivateProfileString(section, key, strVal, fileName);
}
public void DelKey(string section, string key)
{
WritePrivateProfileString(section, key, null, fileName);
}
public void DelSection(string section)
{
WritePrivateProfileString(section, null, null, fileName);
}
}
}