Read CSV (text) file using csvreader in .Net

nabilabolo
 
on Dec 02, 2022 06:20 AM
401 Views

Hi,

I have to read csv file using csvreader in c#. The function able to read the first data but then after read the first data seems like it went out of the while(package.read()) loop.

My csv file data that i want to read start from line 8. I able to read line 8 when want to read line 9 it out of while loop.

App.config

<appSettings>
    <add key="ClientSettingsProvider.ServiceUri" value="" />
    <add key="inputFileBuild" value="C:\\Users\\source\\repos\\ReadStagingAll\\Test.csv" />
</appSettings>

 Program.cs

string inputFileBuild = ConfigurationManager.AppSettings["inputFileBuild"].ToString();
Console.WriteLine("Reading Excel File:" + inputFileBuild);

//run the excel reader library
//create a new Excel package in a memorystream
using (var stream = new StreamReader(inputFileBuild)) {
    using (var package = new CsvReader(stream, CultureInfo.InvariantCulture))
    {
          int x = 0; 

          while (package.Read()) {
               if (x > 7)
               {
                   var Name = package.GetField<string>(0);
                   var Age = package.GetField<string>(1);
                   var Address = package.GetField<string>(2);
                                
                   Console.WriteLine(Name + "|" + Age + "|" + Address + "|" + "\n");

                }
                x++;
           }
     }
}
conn.Close();
Console.WriteLine("The database has been closed!");

conn.Dispose();
Console.WriteLine("The database connection has been disposed!");
Console.WriteLine("Connection State: " + conn.State.ToString());
Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Dec 02, 2022 07:07 AM

Use the code.

string inputFileBuild = ConfigurationManager.AppSettings["inputFileBuild"].ToString();
Console.WriteLine("Reading Excel File:" + inputFileBuild);
 
//run the excel reader library
//create a new Excel package in a memorystream
using (var stream = new StreamReader(inputFileBuild)) {
    using (var package = new CsvReader(stream, CultureInfo.InvariantCulture))
    {
          int x = 0;
 
          while (package.Read()) 
          {
               if (x >= 7)
               {
                   var Name = package.GetField<string>(0);
                   var Age = package.GetField<string>(1);
                   var Address = package.GetField<string>(2);
                                 
                   Console.WriteLine(Name + "|" + Age + "|" + Address + "|" + "\n");
 
                }
                x++;
           }
     }
}
conn.Close();
Console.WriteLine("The database has been closed!");
 
conn.Dispose();
Console.WriteLine("The database connection has been disposed!");
Console.WriteLine("Connection State: " + conn.State.ToString());