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!
CSV parser/reader for C#?
FileHelpers Open Source Library.
.NET Csv Parser
You shouldn't reinvent the wheel.
You can try the CSVHelper library https://joshclose.github.io/CsvHelper/
One line of code to achieve what you are trying in many lines:
var records = csv.GetRecords<dynamic>();
You can find documentation here.
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
Uploading and parsing a csv file in C#/Core MVC
Your first file stream is still open in your first using and you try to read it again with TextFieldParser
private Dictionary<string, string[]> LoadData(IFormFile file)
{
// Verify that the user selected a file
if (file != null && file.Length > 0)
{
string wwwPath = this.environment.WebRootPath;
// string contentPath = this.environment.ContentRootPath;
string path = Path.Combine(wwwPath, "WeeklySchedules");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fileName = Path.GetFileName(file.FileName);
using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
{
file.CopyTo(stream);
}
// System.Threading.Thread.Sleep(1000);
using (TextFieldParser parser = new TextFieldParser(Path.Combine(path, fileName)))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
Dictionary<string, string[]> parsedData = new Dictionary<string, string[]>();
while (!parser.EndOfData)
{
// Process row
string[] fields = parser.ReadFields();
int count = 0;
if (count++ == 0)
{
continue;
}
var pickup = fields[0];
var pickupDate = fields[1];
var dropoff = fields[2];
var dropoffDate = fields[3];
var driver = fields[7];
var pickupTime = DateTime.Parse(pickupDate).ToLongTimeString();
// string[] data =
}
}
}
return null;
}
Very simple C# CSV reader
If there is only ever one line then do something like this:
using System;
using System.IO;
class Program
{
static void Main()
{
String[] values = File.ReadAllText(@"d:\test.csv").Split(',');
}
}
Parse an advanced CSV file
I've had good results using CSV Reader for .Net: http://www.codeproject.com/KB/database/CsvReader.aspx.
Reading CSV files in C#
Take a look at A Fast CSV Reader on CodeProject.
Related Topics
Can Attributes Be Added Dynamically in C#
C# Error: "An Object Reference Is Required For the Non-Static Field, Method, or Property"
Calling Stored Procedure With Return Value
Anyone Know a Good Workaround For the Lack of an Enum Generic Constraint
How to Create and Use Resources in .Net
Unit Testing Private Methods in C#
How to Strip Non-Ascii Characters from a String In C#
Make an Installation Program For C# Applications and Include .Net Framework Installer into the Setup
How to Clone a Range of Array Elements to a New Array
What Is the { Get; Set; } Syntax in C#
How to Automatically Increment the File Build Version When Using Visual Studio
How to Read Appsettings Values from a .Json File in ASP.NET Core
How to Use Optional Parameters in C#
How to Increase the Max Upload File Size in Asp.Net
Problem With Converting Int to String in Linq to Entities