C# 如何从跳过第一行的.txt文件中读取数据
如何从C# 如何从跳过第一行的.txt文件中读取数据,c#,C#,如何从.txt文件中读取数据? 我的数据文件如下所示 我找到了OpenFileDialog类,并使用下面的代码成功地阅读了第一行,但我不知道如何跳过第一行并从第二行开始阅读 StreamReader sr = new StreamReader(openFileDialog.FileName); string line = sr.ReadLine(); string[] names = line.Split(','); int counter = 0; foreach (String s in
.txt
文件中读取数据?
我的数据文件如下所示
我找到了OpenFileDialog
类,并使用下面的代码成功地阅读了第一行,但我不知道如何跳过第一行并从第二行开始阅读
StreamReader sr = new StreamReader(openFileDialog.FileName);
string line = sr.ReadLine();
string[] names = line.Split(',');
int counter = 0;
foreach (String s in names)
{
DataAttribute attribute;
if (counter!=names.Length-1)
{
attribute = new DataAttribute(s);
}
else
{
attribute = new DataDecision(s);
}
counter++;
}
只需使用
ReadAllLines
,并跳过方法,如:
var AllExceptFirstLine = File.ReadAllLines(FileName).Skip(1).ToList();
您可以尝试使用Linq,Skip
;假设您需要自定义类的数组Weather
using System.Linq;
...
Weather[] records = File
.ReadLines(openFileDialog.FileName)
.Skip(1) // Skip 1st line
.Select(line => line.Split(',')) // Convert each line starting from the 2nd
.Select(items => new Weather() { // into custom Weather classes
Outlook = items[0], //TODO: add necessary conversions if required
Temperature = items[1],
Humidity = items[2],
Wind = items[3],
Decision = items[4]
})
.ToArray(); // organized as an array
您只需重复
line=sr.ReadLine()代码>。ReadLine()
函数会在每次调用时自动增加行数 使用类和外部lib将有助于将数据解析为可用对象
对于不需要映射的简单Csv(Csv头匹配属性,不需要复杂类型或转换),您可以简单地:
public class Weather {
public string Outlook {get;set;}
public string Temperature{get;set;}
public string Humidity{get;set;}
public string Wind{get;set;}
public string Decision{get;set;}
}
void Main()
{
var records = new List<Weather>();
using (var reader = new StreamReader("path\\to\\file.csv"))
using (var csv = new CsvReader(reader))
{
var records = csv.GetRecords<Weather>();
}
}
公共类天气{
公共字符串Outlook{get;set;}
公共字符串温度{get;set;}
公共字符串{get;set;}
公共字符串Wind{get;set;}
公共字符串决策{get;set;}
}
void Main()
{
var记录=新列表();
使用(var reader=new StreamReader(“path\\to\\file.csv”))
使用(var csv=新的CsvReader(读卡器))
{
var records=csv.GetRecords();
}
}
决定跳过第一行还是第一列。是的,跳过第一行,我的错。我想从第二行开始读取,因为第一行是我要创建的对象的名称,每隔一行是这些对象的值。调用readline两次?我使用linq跳过调用readalllines…只需访问您需要的数据<代码>字符串[]行=sr.ReadAllLines();字符串[]columnNames=行[0]。拆分(',');对于(inti=1;i
这是一个Csv。我建议使用外部库来读/写csv。像CSV助手这样,整个东西都可以轻松构建。就像使用(texReader(Path))使用(CsvReader)MyList=CsvReader.GetRecords()
。类似配置的一行有标题、逗号或;作为分隔符。bam完成了。解释一下为什么操作码不起作用也很有用。伟大的解决方案,以及!ToList()做什么?AllExceptFirstLine成为列表?@Dicanio,没错。跳过返回一个Ienumerable,因此我们可能需要将其转换为ListThank,但我会将其更改为ToArray(),因为我必须知道每个记录的坐标。嗯,刚刚意识到每个记录都是一个字母,如何在这种情况下使用Split()?从这一点上处理错误、错误类型、丢失数据,对于Wind strong,从字符串到枚举的转换也同样简单。Weather只是一个例子,它将是决策树,因此为每种情况创建类是毫无意义的,很抱歉之前没有解释它。@Dicanio,没问题,它还可以做动态
只需删除类并csv.GetRecords()代码>;我不是为他们工作,这是免费的。我之所以提供这个建议,是因为它确实有助于完成工作。您想要保存数据。我稍后会使用它,因为我的团队想要csv加载选项,但不是现在。谢谢:D