操作ini配置文件设计一个最基本的可视化数据库系统

时间:2023-03-09 18:42:52
操作ini配置文件设计一个最基本的可视化数据库系统

对于很多小项目来说,不需要搭建专门的数据库系统(例如用SQLite搭建本地数据库),这时可以用ini配置文件实现一个最基本的数据库,实现数据库最基本的增删改查功能。

ini配置文件的用法参考我以前写的文章:http://www.cnblogs.com/xh6300/p/5895759.html

这种配置文件的结构如下:

[section1]

key1=value1

key2=value2

[section2]

key3=value3

key4=value4

……

具体配置文件如下:

操作ini配置文件设计一个最基本的可视化数据库系统

如果要想让这个数据库可视化,在winform中用若干个ComboBox控件是合适的选择。简略界面如下:

操作ini配置文件设计一个最基本的可视化数据库系统

要达到这一目的需要实现的功能如下:

① 需要将广东省、江苏省、北京市这3个section添加到cmb_address控件的Items中。

② 当选择不同的section时,需将该section名下所有条目的key值添加到cmb_name控件的Items中;当切换cmb_address的选项时,cmb_name的内容也会随之切换。

③ 当点击“删除”时,将删除当前section名下选定的那条“key=value”记录。

④ 当点击“修改”时,将使用tbx_value的值修改当前选中的section和key所对应的value值。

至于数据库的“增”和“查”功能,那是ini配置文件的最基本的操作,用对应的SetValue()和GetValue()方法就能轻易实现,在此不再赘述。

1、将所有section添加到一个List列表中的代码实现:

 public void GetAllSections(string iniFileName, out List<string> SectionsList)
{
SectionsList = new List<string>();
string fileText = ""; try
{
StreamReader sr = new StreamReader(iniFileName, Encoding.Default);
fileText = sr.ReadToEnd();
sr.Close();//这一句一定要加 }
catch (Exception)
{
MessageBox.Show("文件" + iniFileName + "不存在或错误!");
return;
} try
{
string[] _split = fileText.Split(new Char[] { '[' }); //由于上面是用“[”分割的,因此下面的i从1开始
for (int i = ; i < _split.Count(); i++)
{
string[] split_temp = _split[i].Split(new Char[] { ']' }); if (split_temp[].Trim() != "")
{
SectionsList.Add(split_temp[].Trim());
}
} }
catch (Exception)
{
//这里我就什么也不做,这是坠吼的!
}
}

2、获得指定section下的所有key值,并将它们添加到List列表中的代码实现:

 public void GetAllKeys(string iniFileName, out List<string> keysList, int Section_index)
{
keysList = new List<string>();
string fileText = ""; try
{
StreamReader sr = new StreamReader(iniFileName, Encoding.Default);
fileText = sr.ReadToEnd();
sr.Close();//这一句一定要加 }
catch (Exception)
{
MessageBox.Show("文件" + iniFileName + "不存在或错误!");
return;
} try
{
//先把所有的[section]去掉
string[] _split = fileText.Split(new Char[] { '[' });
string[] split_temp = _split[Section_index + ].Split(new Char[] { ']' }); string text_key_value = split_temp[];//获得section索引为Section_index下的key和value的文本 text_key_value = text_key_value.Replace("\r\n", "?");//将换行符换成?,便于后面进一步分割
string[] KeyLists_temp = text_key_value.Split(new char[] { '?' });//按‘?’分割,注意可能会有空字符串数组元素 //将分割出来的每一个非空key加入到keysList里面去
for (int i = ; i < KeyLists_temp.Count(); i++)
{
if (KeyLists_temp[i].Trim() != "")
{
string _key = KeyLists_temp[i].Split(new char[] { '=' })[];
if (_key.Trim() != "")
{
keysList.Add(_key.Trim());
}
}
} }
catch (Exception)
{
MessageBox.Show("文件" + iniFileName + "不存在或错误!");
} }

3、将List中的值添加到ComboBox控件的Item中的代码实现:

 public void AddList_ToCmb(List<string> _infoList, ComboBox _cmbBox)
{
for (int i = ; i < _infoList.Count; i++)
{
_cmbBox.Items.Add(_infoList[i]);
}
}

整个程序完整代码如下:

 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles; namespace test1
{
public partial class CustomManage : Form
{
public CustomManage()
{
InitializeComponent();
this.StartPosition = FormStartPosition.CenterScreen;
} private void customManage_Load(object sender, EventArgs e)
{
List<string> _listSections = new List<string>();
List<string> _listKeys = new List<string>(); GetAllSections("companyInfo.ini", out _listSections);
AddList_ToCmb(_listSections, cmb_address); GetAllKeys("companyInfo.ini", out _listKeys, );
AddList_ToCmb(_listKeys, cmb_name);
} private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//清空原有数据
int index = cmb_address.SelectedIndex;
cmb_name.Items.Clear();
cmb_name.Text = ""; //重新获得对应section下的key值的列表,并添加到cmb_Name中
List<string> _nameList = new List<string>();
GetAllKeys("companyInfo.ini", out _nameList, index);
AddList_ToCmb(_nameList, cmb_name);
} //删除条目
private void button4_Click(object sender, EventArgs e)
{
string _fileName = "companyInfo.ini";
try
{
StreamReader sr = new StreamReader(_fileName, Encoding.Default);
string str = sr.ReadToEnd();
sr.Close(); //该删除方式有缺陷,要求“=”两侧不能有空格,否则会删除失败(以后可以考虑用正则匹配一下)
string _deleteItem = cmb_name.Text + "=" + GetValue(_fileName, cmb_address.Text, cmb_name.Text);
str = str.Replace(_deleteItem, "");
StreamWriter sw = new StreamWriter(_fileName, false, Encoding.Default); sw.Write(str);
sw.Flush();
sw.Close(); MessageBox.Show("删除成功!"); }
catch (Exception)
{
MessageBox.Show("文件" + _fileName + "不存在或错误!");
}
} //修改条目
private void button1_Click(object sender, EventArgs e)
{
string _fileName = "companyInfo.ini";
SetValue(_fileName, cmb_address.Text.Trim(), cmb_name.Text.Trim(), tbx_value.Text.Trim()); MessageBox.Show("修改成功!");
} /// <summary> 获得所有的section
///
/// </summary>
/// <param name="iniFileName"></param>
/// <param name="SectionsList"></param>
public void GetAllSections(string iniFileName, out List<string> SectionsList)
{
SectionsList = new List<string>();
string fileText = ""; try
{
StreamReader sr = new StreamReader(iniFileName, Encoding.Default);
fileText = sr.ReadToEnd();
sr.Close();//这一句一定要加 }
catch (Exception)
{
MessageBox.Show("文件" + iniFileName + "不存在或错误!");
return;
} try
{
string[] _split = fileText.Split(new Char[] { '[' }); //由于上面是用“[”分割的,因此下面的i从1开始
for (int i = ; i < _split.Count(); i++)
{
string[] split_temp = _split[i].Split(new Char[] { ']' }); if (split_temp[].Trim() != "")
{
SectionsList.Add(split_temp[].Trim());
}
} }
catch (Exception)
{
//这里我就什么也不做,这是坠吼的!
}
} /// <summary> 获得指定section下的所有key值
///
/// </summary>
/// <param name="iniFileName"></param>
/// <param name="keysList"></param>
/// <param name="Section_index"></param>
public void GetAllKeys(string iniFileName, out List<string> keysList, int Section_index)
{
keysList = new List<string>();
string fileText = ""; try
{
StreamReader sr = new StreamReader(iniFileName, Encoding.Default);
fileText = sr.ReadToEnd();
sr.Close();//这一句一定要加 }
catch (Exception)
{
MessageBox.Show("文件" + iniFileName + "不存在或错误!");
return;
} try
{
//先把所有的[section]去掉
string[] _split = fileText.Split(new Char[] { '[' });
string[] split_temp = _split[Section_index + ].Split(new Char[] { ']' }); string text_key_value = split_temp[];//获得section索引为Section_index下的key和value的文本 text_key_value = text_key_value.Replace("\r\n", "?");//将换行符换成?,便于后面进一步分割
string[] KeyLists_temp = text_key_value.Split(new char[] { '?' });//按‘?’分割,注意可能会有空字符串数组元素 //将分割出来的每一个非空key加入到keysList里面去
for (int i = ; i < KeyLists_temp.Count(); i++)
{
if (KeyLists_temp[i].Trim() != "")
{
string _key = KeyLists_temp[i].Split(new char[] { '=' })[];
if (_key.Trim() != "")
{
keysList.Add(_key.Trim());
}
}
} }
catch (Exception)
{
MessageBox.Show("文件" + iniFileName + "不存在或错误!");
}
} /// <summary> 将字符串List中的值添加到ComboBox控件的Item中。
///
/// </summary>
/// <param name="_infoList"></param>
/// <param name="_cmbBox"></param>
public void AddList_ToCmb(List<string> _infoList, ComboBox _cmbBox)
{
for (int i = ; i < _infoList.Count; i++)
{
_cmbBox.Items.Add(_infoList[i]);
}
} #region 读、写ini配置文件的方法 [DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string defVal,
StringBuilder retVal, int size, string filePath); [DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); public string GetValue(string parasFileName, string section, string key)
{
var sb = new StringBuilder();
string strPath = Environment.CurrentDirectory + "\\" + parasFileName;
int i = GetPrivateProfileString(section, key, "该文件不存在", sb, , strPath);
return sb.ToString();
} public void SetValue(string parasFileName, string section, string key, string value)
{
//获得当前路径,当前是在Debug路径下
string strPath = Environment.CurrentDirectory + "\\" + parasFileName;
WritePrivateProfileString(section, key, value, strPath);
} #endregion }
}

注:上面的完整代码为了减少代码量便于阅读,有些功能的实现写得不够完善,具体使用的时候需要自行改进。