一、背景

由于项目中需要去读取设备的配置信息,配置文件的内容和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文件的内容的更多相关文章

  1. 编写Java程序,在硬盘中选取一个 txt 文件,读取该文档的内容后,追加一段文字“[ 来自新华社 ]”,保存到一个新的 txt 文件内

    查看本章节 查看作业目录 需求说明: 在硬盘中选取一个 txt 文件,读取该文档的内容后,追加一段文字"[ 来自新华社 ]",保存到一个新的 txt 文件内 实现思路: 创建 Sa ...

  2. C#选择多个文件并读取多个文件数据

    原文:C#选择多个文件并读取多个文件数据 版权声明:本文为博主原创文章,转载请附上链接地址. https://blog.csdn.net/ld15102891672/article/details/8 ...

  3. boost::property_tree读取解析ini文件--推荐

    boost::property_tree读取解析ini文件 #include "stdafx.h" #include <iostream> #include <b ...

  4. C++ 中使用boost::property_tree读取解析ini文件

    boost 官网 http://www.boost.org/ 下载页面 http://sourceforge.net/projects/boost/files/boost/1.53.0/ 我下载的是  ...

  5. C语言实现 读取写入ini文件实现(转)

    #include <stdio.h> #include <string.h> /* * 函数名: GetIniKeyString * 入口参数: title * 配置文件中一组 ...

  6. vc读取当前路径和读取配置ini文件

    //获取路径 std::string GetApplicationDir() { HMODULE hModule = GetModuleHandleW(NULL); WCHAR wpath[MAX_P ...

  7. 轮子:读取config.ini文件

    python: 把config.ini文件成map返回 def get_conf(conf_file): conf = {} ll=list(map(lambda x: x.replace('&quo ...

  8. C# 使用文件流来读写ini文件

    背景 之前采用ini文件作为程序的配置文件,觉得这种结构简单明了,配置起来也挺方便.然后操作方式是通过WindowsAPI,然后再网上找到一个基于WindowsAPI封装的help类,用起来倒也顺手. ...

  9. python 内存中写入文件(read读取不到文件解决)

    from io import StringIO a = StringIO.StringIO('title') a.write('content1\n') a.write('content2') a.s ...

随机推荐

  1. ztree中依据后台中传过来的node的id,将这个node的复选框置为不可用

    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");//树对象 var node = treeObj.getNodeByParam(& ...

  2. SQLServer2008 R2安装步骤

    1.解压缩sqlserver_2008_r2.iso到指定的目录,记住这个目录的位置 sqlserver_2008_r2.iso下载位置是:http://download.csdn.net/u0123 ...

  3. CORS with Spring MVC--转

    原文地址:http://dontpanic.42.nl/2015/04/cors-with-spring-mvc.html CORS with Spring MVC   In this blog po ...

  4. 轻松掌握Ubuntu Linux的3D桌面快捷键使用

    视频下载地址: http://115.com/file/be4n23v6#linux3d.rar 轻松掌握Ubuntu Linux的3D桌面快捷键使用 高级3D桌面展示 本文出自 "李晨光原 ...

  5. 16个ASP.NET MVC扩展点【附源码】

    转载于:http://www.cnblogs.com/wupeiqi/p/3570445.html 1.自定义一个HttpModule,并将其中的方法添加到HttpApplication相应的事件中! ...

  6. 轻量级记事本工具:CintaNotes

    本片文章介绍CintaNotes小工具 功能介绍: 方便.快捷的记录笔记: 快捷地从任何地方等截取内容生成笔记: 高效的记事本内容查询: 轻松的标签管理 支持移动设备和电脑同步(估计要收费) 官网下载 ...

  7. vue 实现文本域还剩多少字符

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. 963B:Destruction of a Tree

    You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any ve ...

  9. DEDECMS教程:列表页缩略图随机调用

    如果用过DEDECMS的朋友应该都知道,有些模板列表页面需要用到缩略图,调用内容中的缩略图可以使用系统自带的脚本调用第一张图片.但是,并不是我们所有的内容里都有图片,有时候第一张图片也不一定是适合尺寸 ...

  10. 超好用的谷歌浏览器、Sublime Text、Phpstorm、油猴插件合集

    原文:超好用的谷歌浏览器.Sublime Text.Phpstorm.油猴插件合集 - 『精品软件区』 - 吾爱破解 - LCG - LSG |安卓破解|病毒分析|破解软件|www.52pojie.c ...