跳过读取csv文件的第一行

时间:2017-06-03 03:32:06

标签: c# csv

我是编程的初学者,我很难分析和调试如何跳过阅读csv文件的第一行。我需要一些帮助 我需要我的id以我包含所有内容的形式填充我的组合框 Id的。为了不在浏览中包含标题和 我需要跳过第一行。

    public bool ReadEntrie(int id, ref string name, ref string lastname, ref 
    string phone, ref string mail, ref string website)
    {
        int count = 0;
        CreateConfigFile();
        try
        {
            fs = new FileStream(data_path, FileMode.Open);
            sr = new StreamReader(fs);
            string temp = "";
            bool cond = true;
            while (cond == true)
            {
                if ((temp = sr.ReadLine()) == null)
                {
                    sr.Close();
                    fs.Close();
                    cond = false;
                    if (count == 0)
                        return false;
                }
                if (count == id)
                {
                    string[] stringSplit = temp.Split(',');
                    int _maxIndex = stringSplit.Length;
                    name = stringSplit[0].Trim('"');
                    lastname = stringSplit[1].Trim('"');
                    phone = stringSplit[2].Trim('"');
                    mail = stringSplit[3].Trim('"');
                    website = stringSplit[4].Trim('"');
                }
                count++;
            }
            sr.Close();
            fs.Close();
            return true;
        }
        catch
        {
            return false;
        }
    }

2 个答案:

答案 0 :(得分:1)

@ Somadina的回答是正确的,但我建议一个更好的选择。您可以使用CSV文件解析器库,例如CSV Helpers

您可以从Nuget或Git获取图书馆。 Nuget命令是:

Install-Package CsvHelper

声明以下命名空间:

using CsvHelper;
using CsvHelper.Configuration;

这里使用这样的库时代码看起来有多简单:

class Program
{
    static void Main(string[] args)
    {
        var csv = new CsvReader(File.OpenText("Path_to_your_csv_file"));
        csv.Configuration.IgnoreHeaderWhiteSpace = true;
        csv.Configuration.RegisterClassMap<MyCustomObjectMap>();
        var myCustomObjects = csv.GetRecords<MyCustomObject>();

        foreach (var item in myCustomObjects.ToList())
        {
            // Apply your application logic here.
            Console.WriteLine(item.Name);
        }
    }
}

public class MyCustomObject
{
    // Note: You may want to use a type converter to convert the ID to an integer.
    public string ID { get; set; }
    public string Name { get; set; }
    public string Lastname { get; set; }
    public string Phone { get; set; }
    public string Mail { get; set; }
    public string Website { get; set; }

    public override string ToString()
    {
        return Name.ToString();
    }
}

public sealed class MyCustomObjectMap : CsvClassMap<MyCustomObject>
{
    public MyCustomObjectMap()
    {
        // In the name method, you provide the header text - i.e. the header value set in the first line of the CSV file.
        Map(m => m.ID).Name("id");
        Map(m => m.Name).Name("name");
        Map(m => m.Lastname).Name("lastname");
        Map(m => m.Phone).Name("phone");
        Map(m => m.Mail).Name("mail");
        Map(m => m.Website).Name("website");
    }
}

答案here中的更多细节。

答案 1 :(得分:0)

要跳过第一行,只需替换以下行:

if (count == id)

if (count > 0 && count == id)

对你的方法有更多的想法

由于您使用了ref关键字,因此您阅读的每一行都将覆盖您存储在参数中的先前值。更好的方法是创建一个类来保存所有感兴趣的属性。然后,对于您阅读的每一行,打包该类的实例并将其添加到列表中。方法签名(甚至返回类型)最终会改变。

从您的代码中,该类将如下所示:

public class DataModel
{
    public string Name { get; set; }
    public string LastName { get; set; }
    public string Phone{ get; set; }
    public string Mail { get; set; }
    public string Website{ get; set; }
}

然后你的方法将是这样的:

public IList<DataModel> ReadEntrie(int id, string data_path)
{
    int count = 0;
    CreateConfigFile();
    var fs = new FileStream(data_path, FileMode.Open);
    var sr = new StreamReader(fs);
    try
    {
        var list = new List<DataModel>();
        string temp = "";
        bool cond = true;
        while (cond == true)
        {
            if ((temp = sr.ReadLine()) == null)
            {
                cond = false;
                if (count == 0)
                    throw new Exception("Failed");
            }
            if (count > 0 && count == id)
            {
                string[] stringSplit = temp.Split(',');
                var item = new DataModel();
                item.Name = stringSplit[0].Trim('"');
                item.LastName = stringSplit[1].Trim('"');
                item.Phone = stringSplit[2].Trim('"');
                item.Mail = stringSplit[3].Trim('"');
                item.Website = stringSplit[4].Trim('"');
                // add item to list
                list.Add(item);
            }
            count++;
        }
        return list;
    }
    catch
    {
        throw; // or do whatever you wish
    }
    finally
    {
        sr.Close();
        fs.Close();
    }
}