C# - 从文本文件中使用单个键获取多个值

时间:2017-05-10 12:36:38

标签: c# file dictionary io

我存储了多个在文本文件上共享单个键的值。文本文件如下所示:

Brightness 36 , Manual
BacklightCompensation 3 , Manual
ColorEnable 0 , None
Contrast 16 , Manual
Gain 5 , Manual
Gamma 122 , Manual
Hue 0 , Manual
Saturation 100 , Manual
Sharpness 2 , Manual
WhiteBalance 5450 , Auto

现在我想存储int值&每个键的字符串值(例如,亮度)。

C#的新手,无法找到可行的东西。

由于

2 个答案:

答案 0 :(得分:2)

我建议使用自定义类型来存储这些设置:

public enum DisplaySettingType
{
    Manual, Auto, None
}

public class DisplaySetting
{
    public string Name { get; set; }
    public decimal Value { get; set; }
    public DisplaySettingType Type { get; set; }
}

然后,您可以使用string.Split使用以下LINQ查询来获取所有设置:

decimal value = 0;
DisplaySettingType type = DisplaySettingType.None;

IEnumerable<DisplaySetting> settings = File.ReadLines(path)
    .Select(l => l.Trim().Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries))
    .Where(arr => arr.Length >= 3 && decimal.TryParse(arr[1], out value) && Enum.TryParse(arr[2], out type))
    .Select(arr => new DisplaySetting { Name = arr[0], Value = value, Type = type });

答案 1 :(得分:1)

使用正则表达式和一点点linq,你可以做很多事情 在这里,我假设你知道How to read a Text file

优点:如果文件不完美,reg exp将忽略格式错误的行,并且不会抛出错误。

以下是您文件的硬编码版本,请注意,因为它会出现\r。取决于您阅读文件的方式,但不应该是File.ReadLines()

的情况
string input =
@"Brightness 36 , Manual
BacklightCompensation 3 , Manual
ColorEnable 0 , None
Contrast 16 , Manual
Gain 5 , Manual
Gamma 122 , Manual
Hue 0 , Manual
Saturation 100 , Manual
Sharpness 2 , Manual
WhiteBalance 5450 , Auto";

string regEx = @"(.*) (\d+) , (.*)";

var RegexMatch = Regex.Matches(input, regEx).Cast<Match>();

var outputlist = RegexMatch.Select(x => new { setting = x.Groups[1].Value
                                              , value = x.Groups[2].Value
                                              , mode  = x.Groups[3].Value }); 

正则表达式解释:/(.*) (\d+) , (.*)/g

第一捕获组(。*)
  .*匹配任何字符(行终止符除外)
  *量词 - 在零和无限次之间匹配,尽可能多次,根据需要回馈(贪婪)
字面匹配字符(区分大小写)

第二捕获组(\ d +)
\d+匹配一个数字(等于[0-9])
+量词 - 在一次和无限次之间匹配,尽可能多次,根据需要回馈(贪婪)
 ,字面匹配字符,(区分大小写)

第三捕获组(。*)
.*匹配任何字符(行终止符除外)
*量词 - 在零和无限次之间匹配,尽可能多次,根据需要回馈(贪婪)


Disclamer:

永远不要相信输入!即使它是某个其他程序所做的文件,也可能是客户发送的文件。

根据我的经验,你有两种处理不良格式的方法:
逐行阅读,并记录每条坏线 或者忽略它们。你不适合,你不会坐下来!

并且不要告诉自己它不会发生,它会发生!

相关问题