C#中选中指定文件并读取类似ini文件的内容
一、背景
由于项目中需要去读取设备的配置信息,配置文件的内容和INI配置文件的格式类似,所以可以按照INI文件的方式来处理。涉及如何打开一个文件,获取打开的文件的路径问题,并读取选中的文件里边的内容。
二、参考资料
http://www.cnblogs.com/helloworldtoyou/p/5910556.html
http://www.cnblogs.com/wangsaiming/archive/2011/04/25/2028601.html
http://www.cnblogs.com/zzyyll2/archive/2007/11/06/950584.html
三、如何去打开文件
实现效果如下图所示,打开选中的文件,通过增加OpenFileDialog控件则可以打开文件。

程序如下,其中FileName为选中的文件的路径,
private void Openfilebutton_Click(object sender, EventArgs e)
{
OpenFileDialog fileEds = new OpenFileDialog(); //定义新的文件打开位置软件
fileEds.Filter = "EDS文件|*.eds"; //设置文件后缀过滤
if (fileEds.ShowDialog() == DialogResult.OK) //如果有选择打开文件
{
GloableVar.filepath = fileEds.FileName; //获取到选中的文件的路径
WzCan_DeviceExploer.ProFile.LoadProfile(); //去加载处理选中的文件的内容
textBox1.Text = ProFile.G_BAUDRATE; //显示获取到的文件里边的内容
FiletextBox.Text = fileEds.FileName; //显示打开的文件的路径
}
}
四、如何去读取INI文件
首先了解下INI文件的格式如下:
[SECTION 1]
text1=300
text2=0xFF
[SECTION 2]
text3=Hello
程序中使用定义了一个全局变量获取到选中的文件的路径GloableVar.filepath,使用WzCan_DeviceExploer.ProFile.LoadProfile()是去加载处理选中的文件的内容,调用该函数使用别人写好的两个类来进行读取,只要增加这两个类,访问里边的成员函数即可对文件的内容进行读取和写入。
ProFile.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WzCan_DeviceExploer
{
class ProFile
{
public static void LoadProfile()
{
_file = new IniFile(GloableVar.filepath); //要读取文件的位置
G_BAUDRATE = _file.ReadString("DeviceInfo", "VendorNumber", ""); //读文件里边内容
}
public static void SaveProfile()
{
string strPath = AppDomain.CurrentDomain.BaseDirectory;
_file = new IniFile(strPath + "Cfg.ini");
_file.WriteString("CONFIG", "BaudRate", G_BAUDRATE); //写数据
}
private static IniFile _file;//内置了一个对象
public static string G_BAUDRATE = "";//给ini文件赋新值
}
}
EdsFile.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace WzCan_DeviceExploer
{
public abstract class CustomIniFile
{
public CustomIniFile(string AFileName)
{
FFileName = AFileName;
}
private string FFileName;
public string FileName
{
get { return FFileName; }
}
public virtual bool SectionExists(string Section)
{
List<string> vStrings = new List<string>();
ReadSections(vStrings);
return vStrings.Contains(Section);
}
public virtual bool ValueExists(string Section, string Ident)
{
List<string> vStrings = new List<string>();
ReadSection(Section, vStrings);
return vStrings.Contains(Ident);
}
public abstract string ReadString(string Section, string Ident, string Default);
public abstract bool WriteString(string Section, string Ident, string Value);
public abstract bool ReadSectionValues(string Section, List<string> Strings);
public abstract bool ReadSection(string Section, List<string> Strings);
public abstract bool ReadSections(List<string> Strings);
public abstract bool EraseSection(string Section);
public abstract bool DeleteKey(string Section, string Ident);
public abstract bool UpdateFile();
}
/// <summary>
/// 存储本地INI文件的类。
/// </summary>
public class IniFile : CustomIniFile
{
[DllImport("kernel32")]
private static extern uint GetPrivateProfileString(
string lpAppName, // points to section name
string lpKeyName, // points to key name
string lpDefault, // points to default string
byte[] lpReturnedString, // points to destination buffer
uint nSize, // size of destination buffer
string lpFileName // points to initialization filename
);
[DllImport("kernel32")]
private static extern bool WritePrivateProfileString(
string lpAppName, // pointer to section name
string lpKeyName, // pointer to key name
string lpString, // pointer to string to add
string lpFileName // pointer to initialization filename
);
/// <summary>
/// 构造IniFile实例。
/// <param name="AFileName">指定文件名</param>
/// </summary>
public IniFile(string AFileName)
: base(AFileName)
{
}
/// <summary>
/// 析够IniFile实例。
/// </summary>
~IniFile()
{
UpdateFile();
}
/// <summary>
/// 读取字符串值。
/// <param name="Ident">指定变量标识。</param>
/// <param name="Section">指定所在区域。</param>
/// <param name="Default">指定默认值。</param>
/// <returns>返回读取的字符串。如果读取失败则返回该值。</returns>
/// </summary>
public override string ReadString(string Section, string Ident, string Default)
{
byte[] vBuffer = new byte[2048];
uint vCount = GetPrivateProfileString(Section,
Ident, Default, vBuffer, (uint)vBuffer.Length, FileName);
return Encoding.Default.GetString(vBuffer, 0, (int)vCount);
}
/// <summary>
/// 写入字符串值。
/// </summary>
/// <param name="Section">指定所在区域。</param>
/// <param name="Ident">指定变量标识。</param>
/// <param name="Value">所要写入的变量值。</param>
/// <returns>返回写入是否成功。</returns>
public override bool WriteString(string Section, string Ident, string Value)
{
return WritePrivateProfileString(Section, Ident, Value, FileName);
}
/// <summary>
/// 获得区域的完整文本。(变量名=值格式)。
/// </summary>
/// <param name="Section">指定区域标识。</param>
/// <param name="Strings">输出处理结果。</param>
/// <returns>返回读取是否成功。</returns>
public override bool ReadSectionValues(string Section, List<string> Strings)
{
List<string> vIdentList = new List<string>();
if (!ReadSection(Section, vIdentList)) return false;
foreach (string vIdent in vIdentList)
Strings.Add(string.Format("{0}={1}", vIdent, ReadString(Section, vIdent, "")));
return true;
}
/// <summary>
/// 读取区域变量名列表。
/// </summary>
/// <param name="Section">指定区域名。</param>
/// <param name="Strings">指定输出列表。</param>
/// <returns>返回获取是否成功。</returns>
public override bool ReadSection(string Section, List<string> Strings)
{
byte[] vBuffer = new byte[16384];
uint vLength = GetPrivateProfileString(Section, null, null, vBuffer,
(uint)vBuffer.Length, FileName);
int j = 0;
for (int i = 0; i < vLength; i++)
if (vBuffer[i] == 0)
{
Strings.Add(Encoding.Default.GetString(vBuffer, j, i - j));
j = i + 1;
}
return true;
}
/// <summary>
/// 读取区域名列表。
/// </summary>
/// <param name="Strings">指定输出列表。</param>
/// <returns></returns>
public override bool ReadSections(List<string> Strings)
{
byte[] vBuffer = new byte[16384];
uint vLength = GetPrivateProfileString(null, null, null, vBuffer,
(uint)vBuffer.Length, FileName);
int j = 0;
for (int i = 0; i < vLength; i++)
if (vBuffer[i] == 0)
{
Strings.Add(Encoding.Default.GetString(vBuffer, j, i - j));
j = i + 1;
}
return true;
}
/// <summary>
/// 删除指定区域。
/// </summary>
/// <param name="Section">指定区域名。</param>
/// <returns>返回删除是否成功。</returns>
public override bool EraseSection(string Section)
{
return WritePrivateProfileString(Section, null, null, FileName);
}
/// <summary>
/// 删除指定变量。
/// </summary>
/// <param name="Section">变量所在区域。</param>
/// <param name="Ident">变量标识。</param>
/// <returns>返回删除是否成功。</returns>
public override bool DeleteKey(string Section, string Ident)
{
return WritePrivateProfileString(Section, Ident, null, FileName);
}
/// <summary>
/// 更新文件。
/// </summary>
/// <returns>返回更新是否成功。</returns>
public override bool UpdateFile()
{
return WritePrivateProfileString(null, null, null, FileName);
}
}
}
by 羊羊得亿
2017-07-10 ShenZhen
C#中选中指定文件并读取类似ini文件的内容的更多相关文章
- 编写Java程序,在硬盘中选取一个 txt 文件,读取该文档的内容后,追加一段文字“[ 来自新华社 ]”,保存到一个新的 txt 文件内
查看本章节 查看作业目录 需求说明: 在硬盘中选取一个 txt 文件,读取该文档的内容后,追加一段文字"[ 来自新华社 ]",保存到一个新的 txt 文件内 实现思路: 创建 Sa ...
- C#选择多个文件并读取多个文件数据
原文:C#选择多个文件并读取多个文件数据 版权声明:本文为博主原创文章,转载请附上链接地址. https://blog.csdn.net/ld15102891672/article/details/8 ...
- boost::property_tree读取解析ini文件--推荐
boost::property_tree读取解析ini文件 #include "stdafx.h" #include <iostream> #include <b ...
- C++ 中使用boost::property_tree读取解析ini文件
boost 官网 http://www.boost.org/ 下载页面 http://sourceforge.net/projects/boost/files/boost/1.53.0/ 我下载的是 ...
- C语言实现 读取写入ini文件实现(转)
#include <stdio.h> #include <string.h> /* * 函数名: GetIniKeyString * 入口参数: title * 配置文件中一组 ...
- vc读取当前路径和读取配置ini文件
//获取路径 std::string GetApplicationDir() { HMODULE hModule = GetModuleHandleW(NULL); WCHAR wpath[MAX_P ...
- 轮子:读取config.ini文件
python: 把config.ini文件成map返回 def get_conf(conf_file): conf = {} ll=list(map(lambda x: x.replace('&quo ...
- C# 使用文件流来读写ini文件
背景 之前采用ini文件作为程序的配置文件,觉得这种结构简单明了,配置起来也挺方便.然后操作方式是通过WindowsAPI,然后再网上找到一个基于WindowsAPI封装的help类,用起来倒也顺手. ...
- python 内存中写入文件(read读取不到文件解决)
from io import StringIO a = StringIO.StringIO('title') a.write('content1\n') a.write('content2') a.s ...
随机推荐
- 关于HttpClient模拟浏览器请求的參数乱码问题解决方式
转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/44407297 http://www.llwjy.com/blogdetail/9 ...
- 《AndroidStudio每日一贴》7. 怎样将本地变更文件移到其他的changelist?
操作方法: 进入Version Control -> Local Changes ,会显示本地变更列表分组. 假设你想将某个changelist中的文件转移到其他的changelist, 选中此 ...
- 暑假集训-WHUST 2015 Summer Contest #0.2
ID Origin Title 10 / 55 Problem A Gym 100625A Administrative Difficulties 4 / 6 Problem B Gym 1006 ...
- 分享一下js正则中惰性与贪婪
首先引入一个介绍比较详细的网站 http://www.cnblogs.com/yuaima/p/5258513.html http://www.jb51.net/article/31491.htm 接 ...
- Ubuntu16.04 “有线未托管”有线网络不可用问题解决
Ubuntu16.04 “有线未托管”问题解决 电脑上安装的Ubuntu16.04 是通过先安装Ubuntu Server后在通过命令 sudo tasksel 安装的Gnome桌面环境,安装完成后发 ...
- 手把手教你安装Navicat——靠谱的Navicat安装教程
Navicat是一款轻量级的用于MySQL连接和管理的工具,非常好用,使用起来方便,简洁.下面讲讲其安装的过程. 1.进入navicat官网,选择Navicat for MySQL,然后点击进行下载即 ...
- Swift学习笔记(7)--控制流
1.For循环 //1.条件递增 for var index = 0; index < 3; ++index { println("index is \(index)") } ...
- android 4.4最新官方源代码下载
国内网络,日夜不休花了一个多月才下载成功android标准源代码,有些开发同人须要.已上传到网盘,分享给大家 微云地址: http://url.cn/PkkSzC 百度云盘地址(更新) http:// ...
- Java 实现策略(Strategy)模式
策略模式:行为型模式 将同一行为,不同的处理算法分别封装起来.让它们之间能够互相替换 1. 定义一个超类型接口,及 行为方法 2. 定义不同的实现类,实现该行为的 不同的算法 /** * 策略模式:针 ...
- Android学习笔记进阶19 之给图片加边框
//设置颜色 public void setColour(int color){ co = color; } //设置边框宽度 public void setBorderWidth(int width ...