跳过CSV中的第一个拆分字符

弗留

我输入了这样的csv文件:

 |Name|Surname|Age|
 |ABCD|DCBA|11|
 |QAZ|WSX|23|

当我尝试将csv文件上传到我的datagridview表时,我的第一列为空,因为函数正在读取第一个|split char。

如何跳过每一行的第一个分割字符?

部分代码:

file.ReadLine();
string line = "";
try
{
    while ((line = file.ReadLine()) != null)
    {
        string[] splitArray = line.Split('|');
        Listing.Add(new List(splitArray[0], splitArray[1], splitArray[2]));
        count++;
    }
}
catch
{
    MessageBox.Show("Nothing to do here...");
}
file.Close();
再见StackExchange

不理会第一个索引,使用splitArray[1]splitArray[2]splitArray[3](忽略splitArray[0]):

file.ReadLine();
string line = "";
try
{
    while ((line = file.ReadLine()) != null)
    {
        string[] splitArray = line.Split('|');
        Listing.Add(new List(splitArray[1], splitArray[2], splitArray[3]));
        count++;
    }
}
catch
{
    MessageBox.Show("Nothing to do here...");
}
file.Close();

正如其他人指出的,为什么不使用CsvHelper

您可以通过一个非常简单的配置来完成此操作:

public struct Listing
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
}

using (var file = File.OpenText("test.txt"))
{
    using (var csv = new CsvHelper.CsvReader(file))
    {
        csv.Configuration.Delimiter = "|";
        var records = csv.GetRecords<Listing>().ToList();

        foreach (var record in records)
        {
            Console.WriteLine("Name: {0}, Surname: {1}, Age: {2}", record.Name, record.Surname, record.Age);
        }
    }
}

在这里,您可以看到一些示例输出:

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章