Search code examples
c#loopscsvread-writecsvreader

Why CSVReader only read few files?


I have 22 .csv files that I want to read and write into 1 .csv file This is my internal class

 internal class Record
{
    [Name("RptDt")]
    public string Date { get; set; }
    [Name("Entity")]
    public string Entity { get; set; }
    [Name("ProdFamily")]
    public string ProdFamily { get; set; }
    [Name("ProdGroup")]
    public string ProdGroup { get; set; }
    [Name("ProdType1")]
    public string ProdType1 { get; set; }
    [Name("ProdTypo")]
    public string ProdTypo { get; set; }
    [Name("ProdType")]
    public string Buy { get; set; }
    [Name("Principal")]
    public string Principal { get; set; }
}

This is the write and read code

string[] files = Directory.GetFiles(fbd.SelectedPath, "*.csv", SearchOption.AllDirectories);
string numberFile = files.Length.ToString();                                        
            using (var writer = new StreamWriter(SaveTxt.Text + "\\Result_" + MonthCB.Text + "_" + YearCB.Text + ".csv"))
            using (var csvOut = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                for (int i = 0; i < Int16.Parse(numberFile); i++)
                {
                    using (var reader = new StreamReader(files[i]))
                    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                    {
                        var records = csv.GetRecords<Record>();
                        csvOut.WriteRecords(records);
                    }
                }
            }

However, the code only write data from the first 2 .csv file. How should I solve this problem?


Solution

  • I have found the answer. I create a new .csv file for each input. Before this I edit from the actual file, so the size become bigger and the line also been counted even the data not exist. Now, it works just fine.