一、背景

由于项目中需要去读取设备的配置信息,配置文件的内容和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. CF 558A(Lala Land and Apple Trees-暴力)

    A. Lala Land and Apple Trees time limit per test 1 second memory limit per test 256 megabytes input ...

  2. Install the IIS 6.0 Management Compatibility Components in Windows 7 or in Windows Vista from Control Panel

    https://technet.microsoft.com/en-us/library/bb397374(v=exchg.80).aspx Install the IIS 6.0 Management ...

  3. hdoj--1342--Lotto(dfs)

    Lotto Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Subm ...

  4. orm 通用方法——QueryModelCount条件查询记录数

    定义代码: /** * 描述:根据条件查询对象数 * 作者:Tianqi * 日期:2014-09-17 * param:model 对象实例 * param:cond 查询条件 * return:i ...

  5. .net数字转换成汉字大写

    public class Num2Rmb { private String[] hanArr={"零","壹","贰","叁&qu ...

  6. Windows安全攻略:教你完全修复系统漏洞

    Windows安全攻略:教你完全修复系统漏洞 首发:http://safe.it168.com/a2012/0709/1369/000001369740.shtml 目前互联网上的病毒集团越来越猖狂, ...

  7. linux 10201 ocfs RAC 安装+升级到10205

    准备环境的时 ,要4个对外IP,2个对内IP 不超过2T,,一般都用OCFS 高端存储适合用ASM linux10G安装的时候,安装的机器时间要小于等于(如果是等于要严格等于)第二个机器的时间(只有l ...

  8. 在hive执行创建表的命令,遇到异常com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Specified key was too long; max key length is 767 bytes

    今天在练习hive的操作时,在创建数据表时,遇到了异常 FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.ex ...

  9. 如何获取repeater某行第一列的值

    <div> <asp:Repeater ID="Repeater1" runat="server" DataMember="Defa ...

  10. [Python] Slicing Lists

    In addition to accessing individual elements from a list we can use Python's slicing notation to acc ...