从文本文件返回值:C#
Returning values from text file : C#
我有一个 .txt 文件,其中包含有关我通过另一个项目添加的车辆的信息。我想读取文本文件,检索每个 VIN 号码,并在加载表单时将实际号码本身放在组合框中。
txt 文件中每辆车的信息如下所示:
型号:'model'
制造商:'manufacturer'
车辆识别号:'VIN number'
这是我的:
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]);
}
}
}
}
一种解决方案是使用这样的通用函数:
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()
);
我有一个 .txt 文件,其中包含有关我通过另一个项目添加的车辆的信息。我想读取文本文件,检索每个 VIN 号码,并在加载表单时将实际号码本身放在组合框中。 txt 文件中每辆车的信息如下所示:
型号:'model'
制造商:'manufacturer'
车辆识别号:'VIN number'
这是我的:
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]);
}
}
}
}
一种解决方案是使用这样的通用函数:
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()
);