我想从文本文件中读取设置。
string MySettingsFile = "Settings.txt";
通常,文件有4行。
SettingA:Alpha1
SettingB:Bravo2
SettingC:Charlie1
SettingD:Delta6
我想在它自己的变量中获取每一行,就像这样:
string MyAlpa = "Alpha1";
string MyBravo = "Bravo2";
string MyCharlie = "Charlie1";
string MyDelta = "Delta6";
通常,我只是在循环中读取各行,读取每一行并随即设置字符串。 但是,如果缺少第4行,而我正在寻找冒号之后的行的一部分,那么如果我像这样检查它,则会收到错误消息...
MyDelta = MyDeltaSubstring(MyDelta.LastIndexOf(':') + 1);
在尝试获取SubString之前,是否有一种方法“检查特定行的存在”(这样就不会出现错误),例如 如果尝试了该功能的单独尝试,然后捕获,最后返回我想要的字符串或单词“ Missing”(如果缺少该行(然后由于没有更多行而停止))?
function DoesLineExist(int X, string myFile)
{
string MyString;
try ()
{
// read line X from file myFile
// get everything AFTER the ":" and put it in MyString
// ??? //
}
catch (ArgumentException null)
{
MyString = "Missing";
}
catch (ArgumentException e)
{
MyString = "Missing";
}
finally
{
MyString = ? // whatever we got From Line X (after ":")
}
return MyString; // only if line is missing
}
是否有更好的方法? ReadAllLines还是什么?
答案 0 :(得分:2)
您需要先验证该行是否存在,然后再次检查该行包含键/值对设置是否存在,然后将键/值对投影到字典中,然后通过其键将每个设置获取到变量中密钥名称。
在这里,我创建一个控制台应用程序供您演示。
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> dictSettings = new Dictionary<string, string>();
string MyAlpa = "";
string MyBravo = "";
string MyCharlie = "";
string MyDelta = "";
var lines = File.ReadAllLines(@"C:\Users\xxx\source\repos\ConsoleApp4\ConsoleApp4\Files\Sample.txt");
for (var i = 0; i < lines.Length; i += 1)
{
var line = lines[i];
//DoesLineExist(line);
if (!string.IsNullOrEmpty(line) && line.Contains(":"))
{
string settingKey = line.Split(':')[0];
string settingValue = line.Split(':')[1];
dictSettings.Add(settingKey, settingValue);
}
}
MyAlpa = dictSettings.ContainsKey("SettingA") ? dictSettings["SettingA"] : "";
MyBravo = dictSettings.ContainsKey("SettingB") ? dictSettings["SettingB"] : "";
MyCharlie = dictSettings.ContainsKey("SettingC") ? dictSettings["SettingC"] : "";
MyDelta = dictSettings.ContainsKey("SettingD") ? dictSettings["SettingD"] : "";
Console.WriteLine(MyAlpa);
Console.WriteLine(MyBravo);
Console.WriteLine(MyCharlie);
Console.WriteLine(MyDelta);
Console.ReadLine();
}
//private static void DoesLineExist(string line)
//{
// if (!string.IsNullOrEmpty(line) && line.Contains(":"))
// {
// string settingKey = line.Split(':')[0];
// string settingValue = line.Split(':')[1];
// dictSettings.Add(settingKey, settingValue);
// }
//}
}
输入:
SettingA:Alpha1
SettingB:Bravo2
SettingC:Charlie1
输出:
输入:
SettingA:Alpha1
SettingC:Charlie1
SettingD:
输出:
答案 1 :(得分:0)
以下是构建字典或列表对象的几种不同方法,我们将在以后使用。选择简单是那些唯一的关键字,还是某些SettingB
具有多个值。如果该关系是一对一,则Dictionary可能是一种解决方案。授予您访问ContainsKey
var regexDictionary = Regex.Matches( File.ReadAllText(path)
, "(?<key>.+):(?<value>.+)")
.OfType<Match>()
.Where(m => m.Success)
.ToDictionary(m => m.Groups["key"].Value.Trim(),
m => m.Groups["value"].Value.Trim());
var ObjList = File.ReadAllLines(path)
.Select(line => line.Split(':'))
.Select(x => new MyObject {
prop1 = x[0],
prop2 = x[1]
// etc
})
var linQDictionary = File.ReadAllLines(path)
.Select(line => line.Split(':'))
.ToDictionary(
c => x[0],
c => x[1]
);
该键在词典中是否存在?
if (!dictionary .ContainsKey("SettingB"))
{
Console.WriteLine("For key = \"SettingB\", value = {0}.", dictionary["SettingB"]);
}
在对象列表中:
if (ObjList .Any(x=> x.prop1 == "SettingZ" ))
{
// Select the object.
}