我有一个.txt文件,其中包含我通过其他项目添加的车辆信息。我想读取文本文件,检索每个VIN编号,并在加载表单时将实际数字本身放在组合框中。 txt文件中每个车辆的信息如下:
型号:'型号'
制造商:'制造商'
VIN号码:' VIN号码'
这就是我所拥有的:
using (StreamReader reader = new StreamReader(@"D:\carCenter\carCenter\bin\Debug\Vehicles.txt"))
{
string[] lines = File.ReadAllLines(@"D:\carCenter\carCenter\bin\Debug\Vehicles.txt");
foreach(string line in lines)
{
if (line.Contains("VIN"))
{
Char colon = ':';
string[] vins = line.Split(new string[] {"VIN Number: "}, StringSplitOptions.None);
for (int i = 0; i < 1; i++)
{
foreach(var vin in vins)
{
vinComboBox.Items.Add(vins[i]);
}
}
}
}
答案 0 :(得分:2)
一种解决方案是拥有这样的通用功能:
private String GetDataToRightOfLastColon(String line)
{
line = line.Trim();
var indexOfLastColon = line.LastIndexOf(':');
/* If line does not contain a ':' character,
or ':' is the last non-space character in line,
throw an exception. */
if ((indexOfLastColon == -1) || (indexOfLastColon == (line.Length - 1)))
throw new ArgumentException(
String.Format("The line '{0}' does not have the correct format.", line));
return line.Substring(indexOfLastColon + 1).Trim();
}
接下来,通过LINQ应用该功能来处理文本文件并填充组合框:
vinComboBox.Items.AddRange(
File
.ReadAllLines(@"D:\carCenter\carCenter\bin\Debug\Vehicles.txt")
.Where(line => line.Trim().StartsWith("VIN"))
.Select(line => GetDataToRightOfLastColon(line))
.ToArray()
);