我正在尝试读取具有以下格式的 ini 文件:
SETTING=VALUE
SETTING2=VALUE2
我目前有以下代码:
string cache = sr.ReadToEnd();
string[] splitCache = cache.Split(new string[] {"\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
这给了我一个设置列表,但是,我想做的是将其读入字典。 我的问题是,有没有办法做到这一点,而无需迭代整个数组并手动填充字典?
好吧,你可以使用 LINQ 并执行以下操作
Dictionary<string, string> ini = (from entry in splitCache
let key = entry.Substring(0, entry.FirstIndexOf("="))
let value = entry.Substring(entry.FirstIndexOf("="))
select new { key, value }).ToDictionary(e => e.key, e => e.value);
正如 Binary Worrier 在评论中指出的那样,这种方法与其他答案建议的简单循环相比没有优势。
编辑: 上面的块的较短版本是
Dictionary<string, string> ini = splitCache.ToDictionary(
entry => entry.Substring(0, entry.FirstIndexOf("="),
entry => entry.Substring(entry.FirstIndexOf("="));
迭代有什么问题?
var lines = File.ReadAllLines("pathtoyourfile.ini");
var dict = new Dictionary<string, string>();
foreach(var s in lines)
{
var split = s.Split("=");
dict.Add(split[0], split[1]);
}
INI 文件有点棘手,所以我不建议您自己创建。 我编写了Nini,它是一个配置库,包括一个非常快的解析器。
示例 INI 文件:
; This is a comment
[My Section]
key 1 = value 1
key 2 = value 2
[Pets]
dog = rover
cat = muffy
相同的 C# 代码:
// Load the file
IniDocument doc = new IniDocument ("test.ini");
// Print the data from the keys
Console.WriteLine ("Key 1: " + doc.Get ("My Section", "key 1"));
Console.WriteLine ("Key 2: " + doc.Get ("Pets", "dog"));
// Create a new section
doc.SetSection ("Movies");
// Set new values in the section
doc.SetKey ("Movies", "horror", "Scream");
doc.SetKey ("Movies", "comedy", "Dumb and Dumber");
// Remove a section or values from a section
doc.RemoveSection ("My Section");
doc.RemoveKey ("Pets", "dog");
// Save the changes
doc.Save("test.ini");
尝试这样
[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString")]
public static extern int GetPrivateProfileString(string SectionName, string KeyName, string Default, StringBuilder Return_StringBuilder_Name, int Size, string FileName);
并像这样调用函数
GetPrivateProfileString(Section_Name, "SETTING", "0", StringBuilder_Name, 10, "filename.ini");
可以从
StringBuilder_Name
访问值。
为什么不将文件作为单独的行读取,然后在第一个
=
上分开循环遍历它们?
var dict = new Dictionary<string,string>();
foreach (var line in File.ReadAllLines(filename)) {
var parts = line.Split('=', 2); // Maximum of 2 parts, so '=' in value ignored.
dict.Add(parts[0], parts[1]);
}
(在.NET 4中将
ReadAllLines
替换为ReadLines
,以避免创建数组,ReadLines
返回IEnumerable<String>
并延迟读取文件。)
这里我从setting.ini文件获取连接字符串数据
public class IniFileReader
{
private readonly Dictionary<string, Dictionary<string, string>> data;
private string currentSection;
public IniFileReader(string path)
{
data = new Dictionary<string, Dictionary<string, string>>();
foreach (var line in File.ReadAllLines(path))
{
if (string.IsNullOrWhiteSpace(line) || line.StartsWith(";")) continue;
if (line.StartsWith("[") && line.EndsWith("]"))
{
// Set the current section and initialize it in the dictionary
currentSection = line[1..^1].Trim();
data[currentSection] = new Dictionary<string, string>();
}
else if (line.Contains('=') && currentSection != null)
{
// Split the line at the first '=' character
var splitIndex = line.IndexOf('=');
string key = line.Substring(0, splitIndex).Trim();
string value = line.Substring(splitIndex + 1).Trim();
// Add the key-value pair to the current section
data[currentSection][key] = value;
}
}
}
public string GetValue(string section, string key)
{
return data.TryGetValue(section, out var sectionData) && sectionData.TryGetValue(key, out var value)
? value
: null;
}
}
public static string getConnectionString()
{
try
{
IniFileReader iniReader = new IniFileReader("C:\\Users\\Gaurav\\Documents\\Settings.ini");
// Fetch connection details from the ini file
string server = iniReader.GetValue("SER", "SRVR");
string database = iniReader.GetValue("CONNECT", "DB");
string username = iniReader.GetValue("SERUNM", "UNM");
string password = iniReader.GetValue("SERPW", "PW");
// Construct connection string with ini data
string connectionString = $"Data Source={server};Integrated Security=true;Initial Catalog={database};TrustServerCertificate=True;MultipleActiveResultSets=true;";
return connectionString;
} catch (Exception e)
{
throw new Exception("something went wrong while getting the connection string from .ini :: " + e.Message.ToString());
}
}