Created
March 28, 2021 21:31
-
-
Save rahulrathore44/718675a06d3e9f7d5cb5558c444daf8e to your computer and use it in GitHub Desktop.
[CsvHelper] Reading the Data From CSV File
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using CsvHelper; | |
using CsvHelper.Configuration; | |
using System; | |
using System.Collections.Generic; | |
using System.Globalization; | |
using System.IO; | |
namespace CsvDataReading | |
{ | |
public class CsvDataReader<T> | |
{ | |
public string FilePath { get; } | |
public CsvDataReader(string filePath) | |
{ | |
FilePath = filePath; | |
} | |
public List<T> GetCsvData() | |
{ | |
List<T> dataList = new List<T>(); | |
CsvConfiguration config = new CsvConfiguration(CultureInfo.InvariantCulture) | |
{ | |
HasHeaderRecord = true, | |
Delimiter = ",", | |
LeaveOpen = false | |
}; | |
StreamReader reader = new StreamReader(FilePath); | |
using (CsvReader csv = new CsvReader(reader, config)) | |
{ | |
var data = csv.GetRecords<T>().GetEnumerator(); | |
while (data.MoveNext()) | |
{ | |
dataList.Add(data.Current); | |
} | |
} | |
return dataList; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
namespace CsvDataReading | |
{ | |
public class JobDetails | |
{ | |
public string jobId { get; set; } | |
public string jobTitle { get; set; } | |
public string jobDescription { get; set; } | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
using System; | |
namespace CsvDataReading | |
{ | |
[TestClass] | |
public class UnitTest1 | |
{ | |
[TestMethod] | |
public void TestMethod1() | |
{ | |
CsvDataReader<JobDetails> csvDataReader = new CsvDataReader<JobDetails>(@"C:\Users\RATHR1\source\repos\CsvDataReading\CsvDataReading\JobDetails.csv"); | |
var data = csvDataReader.GetCsvData(); | |
Console.WriteLine(data); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment