.NET框架中是否有可以读写标准.ini文件的类:
[Section]
<keyname>=<value>
...
Delphi有TIniFile组件,我想知道是否有类似的c# ?
.NET框架中是否有可以读写标准.ini文件的类:
[Section]
<keyname>=<value>
...
Delphi有TIniFile组件,我想知道是否有类似的c# ?
当前回答
试试这个方法:
public static Dictionary<string, string> ParseIniDataWithSections(string[] iniData)
{
var dict = new Dictionary<string, string>();
var rows = iniData.Where(t =>
!String.IsNullOrEmpty(t.Trim()) && !t.StartsWith(";") && (t.Contains('[') || t.Contains('=')));
if (rows == null || rows.Count() == 0) return dict;
string section = "";
foreach (string row in rows)
{
string rw = row.TrimStart();
if (rw.StartsWith("["))
section = rw.TrimStart('[').TrimEnd(']');
else
{
int index = rw.IndexOf('=');
dict[section + "-" + rw.Substring(0, index).Trim()] = rw.Substring(index+1).Trim().Trim('"');
}
}
return dict;
}
它创建键为“-”的字典。你可以这样加载它:
var dict = ParseIniDataWithSections(File.ReadAllLines(fileName));
其他回答
我迟到了,但我今天遇到了同样的问题,我写了下面的实现:
using System.Text.RegularExpressions;
static bool match(this string str, string pat, out Match m) =>
(m = Regex.Match(str, pat, RegexOptions.IgnoreCase)).Success;
static void Main()
{
Dictionary<string, Dictionary<string, string>> ini = new Dictionary<string, Dictionary<string, string>>();
string section = "";
foreach (string line in File.ReadAllLines(.........)) // read from file
{
string ln = (line.Contains('#') ? line.Remove(line.IndexOf('#')) : line).Trim();
if (ln.match(@"^[ \t]*\[(?<sec>[\w\-]+)\]", out Match m))
section = m.Groups["sec"].ToString();
else if (ln.match(@"^[ \t]*(?<prop>[\w\-]+)\=(?<val>.*)", out m))
{
if (!ini.ContainsKey(section))
ini[section] = new Dictionary<string, string>();
ini[section][m.Groups["prop"].ToString()] = m.Groups["val"].ToString();
}
}
// access the ini file as follows:
string content = ini["section"]["property"];
}
必须注意的是,这个实现不处理未找到的节或属性。 要实现这一点,您应该扩展Dictionary<,>-类来处理未找到的键。
要序列化Dictionary<string, Dictionary<string, string>>的实例到ini-file,我使用以下代码:
string targetpath = .........;
Dictionary<string, Dictionary<string, string>> ini = ........;
StringBuilder sb = new StringBuilder();
foreach (string section in ini.Keys)
{
sb.AppendLine($"[{section}]");
foreach (string property in ini[section].Keys)
sb.AppendLine($"{property}={ini[section][property]");
}
File.WriteAllText(targetpath, sb.ToString());
. net框架的创建者希望您使用基于xml的配置文件,而不是INI文件。所以不,没有内置的机制来读取它们。
不过,也有第三方的解决方案。
INI处理程序可以作为NuGet包获得,例如INI Parser。 您可以编写自己的INI处理程序,这是一种老式的、费力的方法。它为您提供了对实现的更多控制,可以用于坏的方面,也可以用于好的方面。例如,一个INI文件处理类使用c#, P/Invoke和Win32。
如果您只需要读访问而不需要写访问,并且您正在使用microsoft . extensions . configuration(默认情况下与ASP. extension . configuration捆绑在一起)。你可以使用NuGet包Microsoft.Extensions.Configuration.Ini将ini文件导入到你的配置设置中。
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddIniFile("SomeConfig.ini", optional: false);
Configuration = builder.Build();
}
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#项目。这是配置应用程序的一种更好的方式。
下面是我自己的版本,使用正则表达式。这段代码假设每个节名都是唯一的——如果不是这样的话——用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;
}