INI格式文件操作 |
您所在的位置:网站首页 › ini文件怎么删除 › INI格式文件操作 |
晚上忙着忙着,不知道自己在忙些啥,看看这看看那的,新进一家公司,做的东西,以前都没有接触过的,上班的时候需要用到INI文件来记录一些信息。我这个呢是没有加密的,当然加一个加密的,或者转成字节都可以,这样子就安全点。随便整理下这些老生常谈的东西,博客园也有例子。具体网址我不记得了,上班的时候看的。贴点代码,更新下博客。 下面是INIFileHepler类 /// /// 写入INI文件 /// /// 节点名称[如[TypeName]] /// 键 /// 值 /// 文件路径 /// [DllImport("kernel32")] public static extern long WritePrivateProfileString(string section, string key, string val, string filepath); /// /// 读取INI文件 /// /// 节点名称 /// 键 /// 值 /// stringbulider对象 /// 字节大小 /// 文件路径 /// [DllImport("kernel32")] public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);记得导入命名空间: using System.Runtime.InteropServices;然后是操作类FileManage public class FileManage {public FileManage(string path) { strFilePath = path; } private string strSec = ""; //INI文件名 private string strFilePath; /// /// 写入 /// /// 写入key /// 写入value public void Write(string key, string value) { try { //根据INI文件名设置要写入INI文件的节点名称 //此处的节点名称完全可以根据实际需要进行配置 strSec = Path.GetFileNameWithoutExtension(strFilePath); INIFileHepler.WritePrivateProfileString(strSec, key, value, strFilePath); } catch { throw new Exception("配置文件不存在或权限不足导致无法写入"); } } /// /// 读取 /// /// /// public string Read(string key) { if (File.Exists(strFilePath))//读取时先要判读INI文件是否存在 {strSec = Path.GetFileNameWithoutExtension(strFilePath); return ContentValue(strSec, key);} else {throw new Exception("配置文件不存在"); } } /// /// 自定义读取INI文件中的内容方法 /// /// 键 /// 值 /// private string ContentValue(string Section, string key) {StringBuilder temp = new StringBuilder(1024); INIFileHepler.GetPrivateProfileString(Section, key, "", temp, 1024, strFilePath); return temp.ToString(); } }有这些最后就是调用的问题啦。。 private string strFilePath = Application.StartupPath + "\\FileConfig.ini";//获取INI文件路径//写入 private void button1_Click(object sender, EventArgs e) { FileManage file = new FileManage(strFilePath); file.Write(label1.Text, textBox1.Text); file.Write(label2.Text, textBox2.Text); MessageBox.Show("写入完毕"); } //读取 private void button2_Click(object sender, EventArgs e) { FileManage file = new FileManage(strFilePath); StringBuilder str = new StringBuilder(); str.AppendLine(file.Read(label1.Text)); str.AppendLine(file.Read(label2.Text)); MessageBox.Show(str.ToString()); } 看看运行效果: 很简单的小玩意。。但是作用也很大。。比如自动登录功能,记录配置信息啥的。。挺方便的。。当然这个也可以选择xml来记录的。。这个东西看个人喜好了。 夜深了。。又是一夜。。明天继续折腾。 ______________________________________________________________________________ 源码: INI文件操作 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |