Parsing CSV files in C#, with header
Let a library handle all the nitty-gritty details for you! :-)
Check out FileHelpers and stay DRY - Don't Repeat Yourself - no need to re-invent the wheel a gazillionth time....
You basically just need to define that shape of your data - the fields in your individual line in the CSV - by means of a public class (and so well-thought out attributes like default values, replacements for NULL values and so forth), point the FileHelpers engine at a file, and bingo - you get back all the entries from that file. One simple operation - great performance!
C# Reading CSV File | with header Row and Comma Separated Values
Since you mention the option of using CsvHelper - it should be fairly straightforward for you use it to map straight to your POCO. Assuming a simple object:
public class Foo
{
public string Bar1 {get;set;}
public string Bar2 {get;set;}
public string Bar3 {get;set;}
public string Bar4 {get;set;}
public string Bar5 {get;set;}
}
Define a class map
internal sealed class MyCsvMap : ClassMap<Foo>
{
public MyCsvMap()
{
Map(x => x.Bar1).Name("Header 1");
Map(x => x.Bar2).Name("Header 2");
Map(x => x.Bar3).Name("Header 3");
Map(x => x.Bar4).Name("Header 4");
Map(x => x.Bar5).Name("Header5");
}
}
And then simply
using (var sr = new StreamReader(csvFile.FullName))
{
using (var csvReader = new CsvReader(sr))
{
csvReader.Configuration.RegisterClassMap<MyCsvMap>();
return csvReader.GetRecords<Foo>().ToList();
}
}
CsvHelper should automatically deal with your quoted fields - delimiters within double quotes are ignored by the default setting of Configuration.Quote.
How to extract header from csv in c#
If I understood correctly, you need to read the whole file, process all the lines except the header, then write back a different file with the header and the processed lines, right?
If so, the following approach should work:
var allLines = File.ReadAllLines(originalFile);
var headerLine = allLines.First();
var dataLines = allLines.Skip(1);
var processedLines = ProcessLines(dataLines);
File.WriteAllLines(newFile, (new[] {headerLine}.Concat(processedLines)).ToArray());
The ProcessLines
method would accept the original lines as parameter and return a list with the processed lines:
IEnumerable<string> ProcessLines(IEnumerable<string> originalLines)
{
var processedLines = new List<string>();
foreach(var line in originalLines)
{
var processedLine = //generate your processed line here
processedLines.Add(processedLine);
}
return processedLines;
}
Reading dynamic header from csv file
You could try as below to make the pointer on the right place
using (var reader = new StreamReader(file.OpenReadStream()))
{
reader.ReadLine();
// it was not used to read text but adjust the position of pointer, in your case,you need add the codes for 10 times
reader.ReadLine();
reader.ReadLine();
using (var csvReader = new CsvReader(reader, CultureInfo.CurrentCulture))
{
var records = csvReader.GetRecords<TestModel>().ToList();
}
}
Result:
also,open your csv file as below and check if the name contains sapce,it may also cause the error you've shown
Correct:
Wrong:
Reading CSV files using C#
Don't reinvent the wheel. Take advantage of what's already in .NET BCL.
- add a reference to the
Microsoft.VisualBasic
(yes, it says VisualBasic but it works in C# just as well - remember that at the end it is all just IL) - use the
Microsoft.VisualBasic.FileIO.TextFieldParser
class to parse CSV file
Here is the sample code:
using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
//Processing row
string[] fields = parser.ReadFields();
foreach (string field in fields)
{
//TODO: Process field
}
}
}
It works great for me in my C# projects.
Here are some more links/informations:
- MSDN: Read From Comma-Delimited Text Files in Visual Basic
- MSDN: TextFieldParser Class
Parse CSV data based on Headers then load into Array
You can split every line with String.Split method.
Like
var fields = sLine.Split(new char[]{','});
if your values are separated by comma
Related Topics
How to Load Dll (Module Could Not Be Found Hresult: 0X8007007E)
Random Number Generator Only Generating One Random Number
Difference Between a Reference Type and Value Type in C#
Casting VS Using the 'As' Keyword in the Clr
Elevating Process Privilege Programmatically
Difference Between Property and Field in C# 3.0+
What's the Difference Between Invoke() and Begininvoke()
How to Call Stored Procedure in Entity Framework 6 (Code-First)
Pre & Post Increment Operator Behavior in C, C++, Java, & C#
How to Update the Gui from Another Thread
How to Enable Assembly Bind Failure Logging (Fusion) in .Net
Deserialize Json Object into Dynamic Object Using Json.Net
Await' Works, But Calling Task.Result Hangs/Deadlocks