.NET框架中是否有可以读写标准.ini文件的类:
[Section]
<keyname>=<value>
...
Delphi有TIniFile组件,我想知道是否有类似的c# ?
.NET框架中是否有可以读写标准.ini文件的类:
[Section]
<keyname>=<value>
...
Delphi有TIniFile组件,我想知道是否有类似的c# ?
当前回答
这是我的班级,效果非常好:
public static class IniFileManager
{
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section,
string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,
string key, string def, StringBuilder retVal,
int size, string filePath);
[DllImport("kernel32.dll")]
private static extern int GetPrivateProfileSection(string lpAppName,
byte[] lpszReturnBuffer, int nSize, string lpFileName);
/// <summary>
/// Write Data to the INI File
/// </summary>
/// <PARAM name="Section"></PARAM>
/// Section name
/// <PARAM name="Key"></PARAM>
/// Key Name
/// <PARAM name="Value"></PARAM>
/// Value Name
public static void IniWriteValue(string sPath,string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, sPath);
}
/// <summary>
/// Read Data Value From the Ini File
/// </summary>
/// <PARAM name="Section"></PARAM>
/// <PARAM name="Key"></PARAM>
/// <PARAM name="Path"></PARAM>
/// <returns></returns>
public static string IniReadValue(string sPath,string Section, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp,
255, sPath);
return temp.ToString();
}
}
使用是显而易见的,因为它是一个静态类,只需调用IniFileManager。IniWriteValue用于读取section或IniFileManager。IniReadValue用于读取section。
其他回答
前言
首先,阅读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<(string, string)> ini = File.ReadLines(filename)
.Select(s => {
var spl = s.Split('=', 2);
return spl.Length == 2 ? (spl[0], spl[1]) : (s, "");
})
.Select(vt => (vt.Item1.Trim(), vt.Item2.Trim()))
.Where(vt => vt.Item1 != "")
.ToList();
写:
File.WriteAllLines(filename, ini.Select(vt => $"{vt.Item1}={vt.Item2}"));
(如果你不关心重复,使用.ToDictionary()而不是.ToList()更容易访问)
joerage回答中的代码是鼓舞人心的。
不幸的是,它改变了键的字符大小写,并且不处理注释。所以我写了一些足够健壮的东西,可以读取(只)非常脏的INI文件,并允许按原样检索密钥。
它使用一些LINQ,一个嵌套的不区分大小写的字符串字典来存储节,键和值,并一次性读取文件。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class IniReader
{
Dictionary<string, Dictionary<string, string>> ini = new Dictionary<string, Dictionary<string, string>>(StringComparer.InvariantCultureIgnoreCase);
public IniReader(string file)
{
var txt = File.ReadAllText(file);
Dictionary<string, string> currentSection = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
ini[""] = currentSection;
foreach(var line in txt.Split(new[]{"\n"}, StringSplitOptions.RemoveEmptyEntries)
.Where(t => !string.IsNullOrWhiteSpace(t))
.Select(t => t.Trim()))
{
if (line.StartsWith(";"))
continue;
if (line.StartsWith("[") && line.EndsWith("]"))
{
currentSection = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
ini[line.Substring(1, line.LastIndexOf("]") - 1)] = currentSection;
continue;
}
var idx = line.IndexOf("=");
if (idx == -1)
currentSection[line] = "";
else
currentSection[line.Substring(0, idx)] = line.Substring(idx + 1);
}
}
public string GetValue(string key)
{
return GetValue(key, "", "");
}
public string GetValue(string key, string section)
{
return GetValue(key, section, "");
}
public string GetValue(string key, string section, string @default)
{
if (!ini.ContainsKey(section))
return @default;
if (!ini[section].ContainsKey(key))
return @default;
return ini[section][key];
}
public string[] GetKeys(string section)
{
if (!ini.ContainsKey(section))
return new string[0];
return ini[section].Keys.ToArray();
}
public string[] GetSections()
{
return ini.Keys.Where(t => t != "").ToArray();
}
}
通常,当您使用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