.NET框架中是否有可以读写标准.ini文件的类:
[Section]
<keyname>=<value>
...
Delphi有TIniFile组件,我想知道是否有类似的c# ?
.NET框架中是否有可以读写标准.ini文件的类:
[Section]
<keyname>=<value>
...
Delphi有TIniFile组件,我想知道是否有类似的c# ?
当前回答
我想介绍一个完全用c#创建的IniParser库,所以它不包含任何操作系统的依赖关系,这使得它与Mono兼容。MIT许可的开源软件——所以它可以在任何代码中使用。
你可以在GitHub中查看源代码,它也可以作为NuGet包使用
它是高度可配置的,使用起来非常简单。
很抱歉我不要脸的插播,但我希望它能对那些重新审视这个答案的人有所帮助。
其他回答
前言
首先,阅读MSDN博客上关于INI文件局限性的文章。如果它符合你的需要,请继续读下去。
这是我写的一个简洁的实现,利用原始的Windows P/Invoke,所以它被安装了。net的所有版本的Windows(即Windows 98 - Windows 11)所支持。我在此将其发布到公共领域-您可以在没有归属的情况下自由地使用它。
小班授课
在项目中添加一个名为infilile .cs的新类:
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
// Change this to match your program's normal namespace
namespace MyProg
{
class IniFile // revision 11
{
string Path;
string EXE = Assembly.GetExecutingAssembly().GetName().Name;
[DllImport("kernel32", CharSet = CharSet.Unicode)]
static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);
[DllImport("kernel32", CharSet = CharSet.Unicode)]
static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);
public IniFile(string IniPath = null)
{
Path = new FileInfo(IniPath ?? EXE + ".ini").FullName;
}
public string Read(string Key, string Section = null)
{
var RetVal = new StringBuilder(255);
GetPrivateProfileString(Section ?? EXE, Key, "", RetVal, 255, Path);
return RetVal.ToString();
}
public void Write(string Key, string Value, string Section = null)
{
WritePrivateProfileString(Section ?? EXE, Key, Value, Path);
}
public void DeleteKey(string Key, string Section = null)
{
Write(Key, null, Section ?? EXE);
}
public void DeleteSection(string Section = null)
{
Write(null, null, Section ?? EXE);
}
public bool KeyExists(string Key, string Section = null)
{
return Read(Key, Section).Length > 0;
}
}
}
如何使用
以以下三种方式之一打开INI文件:
// Creates or loads an INI file in the same directory as your executable
// named EXE.ini (where EXE is the name of your executable)
var MyIni = new IniFile();
// Or specify a specific name in the current dir
var MyIni = new IniFile("Settings.ini");
// Or specify a specific name in a specific dir
var MyIni = new IniFile(@"C:\Settings.ini");
你可以这样写一些值:
MyIni.Write("DefaultVolume", "100");
MyIni.Write("HomePage", "http://www.google.com");
创建一个这样的文件:
[MyProg]
DefaultVolume=100
HomePage=http://www.google.com
从INI文件中读取值:
var DefaultVolume = MyIni.Read("DefaultVolume");
var HomePage = MyIni.Read("HomePage");
可选地,您可以设置[Section]的:
MyIni.Write("DefaultVolume", "100", "Audio");
MyIni.Write("HomePage", "http://www.google.com", "Web");
创建一个这样的文件:
[Audio]
DefaultVolume=100
[Web]
HomePage=http://www.google.com
你也可以像这样检查一个键的存在:
if(!MyIni.KeyExists("DefaultVolume", "Audio"))
{
MyIni.Write("DefaultVolume", "100", "Audio");
}
你可以像这样删除一个键:
MyIni.DeleteKey("DefaultVolume", "Audio");
你也可以像这样删除整个section(包括所有键):
MyIni.DeleteSection("Web");
请随时评论任何改进!
下面是我自己的版本,使用正则表达式。这段代码假设每个节名都是唯一的——如果不是这样的话——用List替换Dictionary是有意义的。此函数支持.ini文件注释,从';'字符开始。Section正常启动[Section],键值对也正常出现“key = value”。与节相同的假设-键名是唯一的。
/// <summary>
/// Loads .ini file into dictionary.
/// </summary>
public static Dictionary<String, Dictionary<String, String>> loadIni(String file)
{
Dictionary<String, Dictionary<String, String>> d = new Dictionary<string, Dictionary<string, string>>();
String ini = File.ReadAllText(file);
// Remove comments, preserve linefeeds, if end-user needs to count line number.
ini = Regex.Replace(ini, @"^\s*;.*$", "", RegexOptions.Multiline);
// Pick up all lines from first section to another section
foreach (Match m in Regex.Matches(ini, "(^|[\r\n])\\[([^\r\n]*)\\][\r\n]+(.*?)(\\[([^\r\n]*)\\][\r\n]+|$)", RegexOptions.Singleline))
{
String sectionName = m.Groups[2].Value;
Dictionary<String, String> lines = new Dictionary<String, String>();
// Pick up "key = value" kind of syntax.
foreach (Match l in Regex.Matches(ini, @"^\s*(.*?)\s*=\s*(.*?)\s*$", RegexOptions.Multiline))
{
String key = l.Groups[1].Value;
String value = l.Groups[2].Value;
// Open up quotation if any.
value = Regex.Replace(value, "^\"(.*)\"$", "$1");
if (!lines.ContainsKey(key))
lines[key] = value;
}
if (!d.ContainsKey(sectionName))
d[sectionName] = lines;
}
return d;
}
通常,当您使用c#和. net框架创建应用程序时,您不会使用INI文件。更常见的方法是将设置存储在基于xml的配置文件或注册表中。 但是,如果您的软件与遗留应用程序共享设置,则可能更容易使用其配置文件,而不是将信息复制到其他地方。
. net框架不支持直接使用INI文件。但是,您可以使用带有平台调用服务(P/Invoke)的Windows API函数来写入和读取文件。在本链接中,我们创建了一个表示INI文件的类,并使用Windows API函数来操作它们。 请点击下面的链接。
读取和写入INI文件
如果你只是想要一个简单的阅读器没有部分和任何其他dll这里是一个简单的解决方案:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tool
{
public class Config
{
Dictionary <string, string> values;
public Config (string path)
{
values = File.ReadLines(path)
.Where(line => (!String.IsNullOrWhiteSpace(line) && !line.StartsWith("#")))
.Select(line => line.Split(new char[] { '=' }, 2, 0))
.ToDictionary(parts => parts[0].Trim(), parts => parts.Length>1?parts[1].Trim():null);
}
public string Value (string name, string value=null)
{
if (values!=null && values.ContainsKey(name))
{
return values[name];
}
return value;
}
}
}
使用示例:
file = new Tool.Config (Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\config.ini");
command = file.Value ("command");
action = file.Value ("action");
string value;
//second parameter is default value if no key found with this name
value = file.Value("debug","true");
this.debug = (value.ToLower()=="true" || value== "1");
value = file.Value("plain", "false");
this.plain = (value.ToLower() == "true" || value == "1");
配置文件内容同时(如你所见,支持#符号的行注释):
#command to run
command = php
#default script
action = index.php
#debug mode
#debug = true
#plain text mode
#plain = false
#icon = favico.ico
CodeProject的这篇文章“一个使用c#的INI文件处理类”应该会有所帮助。
作者创建了一个c#类“Ini”,它公开了KERNEL32.dll中的两个函数。这些函数是:WritePrivateProfileString和GetPrivateProfileString。您需要两个命名空间:System.Runtime.InteropServices和System.Text。
使用Ini类的步骤
在项目名称空间定义中添加
using INI;
像这样创建一个INIFile
INIFile ini = new INIFile("C:\\test.ini");
使用IniWriteValue向section中的特定键写入新值,或使用IniReadValue从特定section中的键读取值。
注意:如果你是从头开始,你可以阅读这篇MSDN文章:如何:将应用程序配置文件添加到c#项目。这是配置应用程序的一种更好的方式。