Тёмный

The BEST Way to Read a CSV File in C# | CsvHelper Tutorial 

Roberts Dev Talk
Подписаться 21 тыс.
Просмотров 60 тыс.
50% 1

In this tutorial I'll show you how to read a CSV file into your C# .NET app using the excellent CsvHelper library. I'll go through 3 methods to read your CSV file: dynamic objects, Property Attributes and ClassMap.
The example here is a .NET Core app, but CsvHelper is a .NET Standard library, so it works seamlessly across .NET Core, .NET Framework and Xamarin.
☕️ Don’t forget, developers run on coffee! 😀
www.buymeacoff...
📬 Stay in touch! Join our mailing list
robertsdevtalk...
🐦 Follow us on Twitter:
/ robertsdevtalk
If you need to create a CSV file (export), we have a video here for you:
• Create CSV file in C# ...
CsvHelper homepage:
joshclose.gith...
SpaceX open source REST API (unofficial), lots of fun sample data if you like rockets:
github.com/r-s...

Опубликовано:

 

21 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 104   
@RDT
@RDT 3 года назад
We've now made an updated video that addresses some of your questions about handling semicolon delimiters and CSV files with no header row, check it out! ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-f5bzNh7hVhk.html
@DA_7
@DA_7 10 месяцев назад
This has been truly educational and useful. Thank you so much for sharing!
@skyhymitch
@skyhymitch 3 года назад
Keep making videos! As simple as CSV readers seem to be this concept has eluded me. Until now... You've got a new subscriber.
@RDT
@RDT 3 года назад
Thanks Mitchell, its always nice to know it has helped someone! We have lots of new content planned. Appreciate the sub!
@bigoper
@bigoper Год назад
The best I've seen! Just FLAWLESS! Thank you!
@RDT
@RDT Год назад
Wow, thank you! 🙏
@Terrados1337
@Terrados1337 Год назад
This was way more concise than anything google threw at me! Thank you very much!
@RDT
@RDT Год назад
You’re welcome ☺️ glad it was helpful to you
@fellypsantos_
@fellypsantos_ Год назад
Thank you so much sir! Finally understood how to use that lib! You're talented to teach us, clear didactic.
@rmarikar1
@rmarikar1 2 года назад
Brilliant. Thank you. Such a good teacher!!
@RDT
@RDT 2 года назад
Glad it was helpful 🙏
@alexdpaiva83
@alexdpaiva83 3 года назад
Thank you very much for the tip, we from Brazil are grateful for your video.
@RDT
@RDT 3 года назад
Our pleasure!
@IAmRaj360
@IAmRaj360 2 года назад
Loved one thanks.it very helpful for me
@RDT
@RDT 2 года назад
Thanks for your kind comment and support of the channel
@Sabafbatlett
@Sabafbatlett 10 месяцев назад
This is so helpful many thanks mate!
@RDT
@RDT 10 месяцев назад
You're welcome!
@udayshastri5288
@udayshastri5288 Год назад
Great video. What if comma embedded in the one of the column.
@alialsaady5
@alialsaady5 Год назад
Thank you for the clear explanation! Do you know how I can change the csv path to the downloads folder
@rosabenitez7795
@rosabenitez7795 Год назад
Great video, quick question, where can I find the CSV used for this example?, Rocket launches I think is called, sorry for the trouble, and keep up the good work!👍🏼
@RDT
@RDT Год назад
Hi Rosa, sure - it’s at my GitHub repo github.com/chrismroberts/csvreader-example
@Amy-ve3ke
@Amy-ve3ke 2 года назад
Need to get this csv thing working !! Thanks
@paulkalus41
@paulkalus41 2 года назад
Hey, thanks for this video. It was really informative and helped me out/solved my issue where my csv had a mixture of comma only and comma with quoted data eg 22, 5 , "abc", 6 , "def" . Thanks Great video :)
@briantremelling
@briantremelling 3 года назад
Thanks. Video was easy to understand and got me going.
@davidgorenflo9260
@davidgorenflo9260 2 года назад
great Tutorial!
@TheMassijay
@TheMassijay Год назад
Thank you, very helpful video! Can you tell me what extension do you use to preview csv files in vscode?
@hassanOnYoutube
@hassanOnYoutube 2 года назад
wonderful video, Love from Pakistan !
@patrickboehme4556
@patrickboehme4556 2 года назад
Great tutorial, thank you very much!
@glooman2455
@glooman2455 3 года назад
This video helped me a lot! You've got a new subscriber.
@RDT
@RDT 3 года назад
Happy to hear it was helpful for you. Thanks for the sub!
@Matzul98
@Matzul98 Год назад
How can I deal with column name changes? If over time column names change and maybe their order. Or some are removed. Then I need some backwards compatibility between old reports in my app and new reports with the ever changing new format. When I download different formats that must map to the same class. 1. If the column header is dynamic in name then I can use regex. 2. If some columns are removed in the future I can use nullable properties.
@santoshanjani3860
@santoshanjani3860 Год назад
Hi Robert, This content is owesome. Thanks for your help. I have one query: Currently my import code using MemoryStream and this CsvReader, to import CSV file. It is fine for small size file but when it reaches 40 MB the application crashes. I m using blazor tech. Someone said that import it in small batches one by one. But I don't know how. Can u please help me.
@ayesamson
@ayesamson 2 года назад
well done. delivered very clearly and easy to follow. cheers, mate!
@RDT
@RDT 2 года назад
No problem!
@SrDividendos
@SrDividendos 2 года назад
Great video! Very direct to the point and easy to follow. Only one question: Is there a place where I can download this CSV file you're using? I cheked the description of the video and couldn't find it.
@RDT
@RDT 2 года назад
Thanks for watching, glad it was helpful to you 🙂 The CSV files I used and source code are here: github.com/chrismroberts/csvreader-example
@cifuentes678
@cifuentes678 3 года назад
Great tutorial! If I need some help with this, can I request your assistance?
@miguelvale7364
@miguelvale7364 2 года назад
Hi Robert, nice videos you have here. Im using CSVHelper and ran into a problem. How can I make it read a string like this (This "is" a string). CSVHelper is breaking when getting double quotes in a string and i can't even handle anything because im only passing the file path. Thanks
@clsferguson
@clsferguson 3 года назад
This video helped me. I am learning C#. So as a project I have taken on to help me do this, I am trying to make an app that can take any datalog type CSV file, and plot the data on a livechart cartesian chart. But one thing i am trying to figure out, I want to be able to load any csv file with any number of columns. how can I create a dynamic class that can accommodate this?
@RDT
@RDT 3 года назад
Really happy it was helpful to you! If you use the dynamic keyword when calling GetRecords (e.g. GetRecords()) the library sorts out creating the dynamic objects for you. So for example if you had a CSV file with a column called "quantity", you'd get an object back that would have a quantity property on. The issue with using dynamics is that CsvHelper doesn't know what type the property should be, so just gives you a string, which you'd have to parse manually.
@jimhat5753
@jimhat5753 2 года назад
HI! Great talk, BUT do you have the software someplace so I can download it? Trying to copy it while you talk is very hard. Thanks! JIM
@RDT
@RDT 2 года назад
Hey JIM, here you go: github.com/chrismroberts/csvreader-example/
@robertosousa8065
@robertosousa8065 2 года назад
Hi Roberts, I'm with a problem. I have a csv file with simple information, 1 column with a Name, 1 column with a Adress and 1 column with 1 ModbusFuction Name. I did like your tutorial, indeed I added the csv file to the directory of my visual studio project. I need to use this information forward in the project, so it's important to read correctly all the data so I can compare the names and adresses so I can do something, adding the information to a list is simple and effective, the problem is that one exception is launched when I run the program: "header with name 'Name'[0] was not found." .. I imagine that is because csv files begin in index 1 right ? Is there any command or solution so I can discard the reading of the index 0 ? Or some command that will start the reading at index 1 ? I was reading the documentation of the CsvHelper and I did not find any concrete solution. I thought that the Mapping solved this problem.
@matejoo7663
@matejoo7663 3 года назад
great quality!
@RDT
@RDT 3 года назад
Thanks Matejoo , much appreciated
@AlbrechtJ
@AlbrechtJ 3 года назад
Thanks for this good tutorial.
@RDT
@RDT 3 года назад
Sure! 🙏
@irvirv8243
@irvirv8243 3 года назад
Hello Roberts Dev Talk, What if all of our fields of the CSV are separated by ";" how can we get rid of it to create the database? I mean something like id;contract;phoneNumber; ... and the data is 2;332321;7541233; ... P.S I really like the video.
@RDT
@RDT 3 года назад
When you construct your CsvReader you can pass in a CsvConfiguration object instead of CultureInfo. CsvConfiguration has a Delimiter property, which you can set to “;” For example var config = new CsvConfiguration(CultureInfo.InvariantCulture) config.Delimiter = “;” using (var reader = new CsvReader(streamreader, config)) Glad you liked the video!
@savs4657
@savs4657 3 года назад
@@RDT thank you so much, I got this problem and this code solved it
@Michael-xb5zq
@Michael-xb5zq 2 года назад
I've used powershell for years and im just now starting to try and learn other languages. It honestly baffles me how difficult it is to do such simple things like writing to a file or importing a csv. Powershell has cmdlets for everything and all the real complexities are abstracted away. I'm finding learning another language to be really difficult. Especially since i have no teacher and im just learning little bits and pieces from youtube and stackoverflow.
@RDT
@RDT 2 года назад
The irony being some of those cmdlets are probably written with .NET 😀 A good friend of mine does a lot of Python development and it always amazes me how easy it is to perform tasks like CSV processing, PDF generation, image processing etc in Python, when a lot of that is missing from .NET, or only available as commercial libraries
@Gmaaa
@Gmaaa Год назад
Hi my register is ;...;"name "mr" robot"; ...; double quote is erros. How do I adjust to not give an error with this double quote?
@romanlemeshov5513
@romanlemeshov5513 3 года назад
Great tutorial, thanks! Can you tell, please, how convert "$2.34" to "2.34"( cut currency sign)?
@RDT
@RDT 3 года назад
Could use a regex to match the number part and then use Double.Parse on the resulting string?
@DeepakSharma-wi4wu
@DeepakSharma-wi4wu 2 года назад
I have files that header names are not consistent. Sometimes an extra '_' or year is added anywhere. PrepareHeaderForMatch = args => args.Header.Replace("_", " "), but it doesn't work. even if I just set the header value to lowercase and then when I read csv headers it still shows me the original column names of the file. Any idea what am doing wrong here ?
@saeedahamed9347
@saeedahamed9347 Год назад
its showing error" You must call read on the reader before accessing its data." like this ,and which data type should i use i want to read the data that is in japanese language
@durgaagoni8988
@durgaagoni8988 3 года назад
Hi Robert, your video is informative. Can you please tell me which version of visual code you are using and what other dlls you installed and can I try with CSOM to update the records to sharepoint list. Your information is appreciated 😊
@RDT
@RDT 3 года назад
Hi Durga. Thank you for the kind comment. Just to check, are you wanting to see an example of a CSV import to SharePoint using CSOM? If so, we can add that video to the upcoming schedule? For the CSV example here we used VS Code with the out of the box .NET core and installed the CSVHelper library (dotnet add package CSVHelper)
@durgaagoni8988
@durgaagoni8988 3 года назад
@@RDT thanks for the quick response Robert 😊 Yes I want it specifically for sharepoint list. I’m trying to create list items based on the data present in the csv file using C# CSOM console application Please help me if possible !
@one-g4227
@one-g4227 3 года назад
How can you read csv with duplicate headers using dynamic class in
@RDT
@RDT 2 года назад
Duplicate column names? You could try using indexes instead. joshclose.github.io/CsvHelper/examples/configuration/class-maps/mapping-duplicate-names/
@mateusloubach
@mateusloubach 2 года назад
I'm rather new to the .Net scene, so my question is a bit easy to resolve. - I was wondering if we can rely on a console app and insert it into an API to run the code while receiving requests from an online interface (or webpage). would that be possible?
@RDT
@RDT 2 года назад
Hi Matt, do you mean have someone upload a CSV from a webpage, and then have a console app process the CSV and post to an API? Console app is a bit short lived and not really suited - you might want to do something with Worker Services, these are background processes designed to run over the long term. You could put your CSV into a queue from the API and then process from the worker service. I've made a playlist on background services in .NET ru-vid.com/group/PLGWG_rRY_j4MOABOppTH8XHJe8aOTyx2V
@anushripatil1059
@anushripatil1059 3 года назад
Hey..can you suggest what will be the changes in code if my csv file have no header
@RDT
@RDT 3 года назад
Sure. Instead of .Name(...) in your map (or the [Name(...)] attribute), use Index(n) with the zero based index of the column See joshclose.github.io/CsvHelper/examples/configuration/class-maps/mapping-by-index/
@anushripatil1059
@anushripatil1059 3 года назад
@@RDT Thank you so much 😊
@anushripatil1059
@anushripatil1059 3 года назад
Hey Robert, One more thing I want to asked that, my CSV file is updating in every 10 second..i.e. new data added into in in every 10 second..so is this code applicable for that..to retrieve particular data from file
@RDT
@RDT 3 года назад
Is the file itself updated or a new file created? As far as I know StreamReader will only give you file state at the time it is called (not tested it though). Might be worth having a look at the FileSystemWatcher class and subscribe to updates on the file? docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=net-5.0
@anushripatil1059
@anushripatil1059 3 года назад
@@RDT Got it 👍 Thank you
@WesleiGomesdeSousa
@WesleiGomesdeSousa 3 года назад
Robert, is there a way to work with positional data in text files instead of comma separators?
@RDT
@RDT 3 года назад
Hi Weslei, do you mean tab separated?
@getsmartpaul
@getsmartpaul 2 года назад
@@RDT I think he means fixed position: e.g. col1 1-5 col2 6-16 col3 17-25 etc
@ld8778
@ld8778 3 года назад
Does anyone know how to skip headers? I have two headers that's causing issues with the CsVReader..
@RDT
@RDT 2 года назад
Hi, do you mean duplicate column names? You could try using indexes instead joshclose.github.io/CsvHelper/examples/configuration/class-maps/mapping-duplicate-names/
@ld8778
@ld8778 2 года назад
@@RDT hi sorry. No. I thought I meant headers, but what I meant was rows of unnecessary stuff until it reaches the headers. I.e. row 1 and 2 have random symbols and numbers .... row 3 starts the headers. I was hoping I could skip those unnecessary rows and just start at headers. Doesn't look like I can
@RDT
@RDT 2 года назад
I see, good question! There are some useful ideas here possibly? github.com/JoshClose/CsvHelper/issues/890 … but I haven’t tried it yet. I’m on vacation but will have a look when I get back and maybe make a follow up video as I can see a few questions building up 🙂
@chrismantonuk
@chrismantonuk 3 года назад
Peng music 👍🏻
@RDT
@RDT 3 года назад
thanks
@McSeeMo_
@McSeeMo_ 2 года назад
I cant make it work with a MemoryStream =( using (var MemoryStreamReader = new StreamReader(memoryStream, System.Text.Encoding.UTF8, true)) { var wholeText = MemoryStreamReader.ReadToEnd(); using (var csvReader = new CsvReader(MemoryStreamReader, CultureInfo.InvariantCulture)) { var records = csvReader.GetRecords().ToList(); _logger.LogInformation($"Finished downloading file [rom [{remoteFilePath}]"); } }
@mikeloose9270
@mikeloose9270 3 года назад
Hi, any idea how to handle this error when trying to add the CsvHelper package? error: There are no versions available for the package 'CsvHelper'. Using Visual Studio Code and SDK net5.0
@mikeloose9270
@mikeloose9270 3 года назад
great video by the way, love the way it is laid out and presented
@RDT
@RDT 3 года назад
Hmm, thats strange.. have you tried specifying a package version? I've just tried with a net5.0 project and it pulled version 27.1.1
@RDT
@RDT 3 года назад
Thank you!
@grandmagus8618
@grandmagus8618 3 года назад
what if you dont have column names . how will you determine headernames can u tell us little solution please. I believe it has something to do with CsvConfiguration but I am not sure
@raanabaniamerian428
@raanabaniamerian428 3 года назад
i dont know specifically about your case, but i think in csvhelper documentation site the map thing was used
@RDT
@RDT 3 года назад
If you don't have column names you can use column index instead. So you set HasHeaderRecord in CsvConfiguration to false, and then instead of using .Name(..) on the Map function or in your class attributes, you just use Index(n) instead. So for example in a ClassMap: Map(m => m.Column1).Index(0) Or using attributes: [Index(0)] public string Column1 { get; set; } Hope that helps!
@grandmagus8618
@grandmagus8618 3 года назад
@@RDT Thank you sir. it was timesaving respone :D
@salemal-khalify7205
@salemal-khalify7205 3 года назад
awesome video. Could you please try to convert csv files that have double quotes inside. Thanks
@RDT
@RDT 3 года назад
Thanks for your question Salem, do you have an example of the kind of file you mean? Perhaps we can cover in a future video
@salemal-khalify7205
@salemal-khalify7205 3 года назад
@@RDT Thanks for your reply. Yes I do have. It's a type of file that the values are separated by ""the value"" ; ""the value""; something like that , I can send a copy of that file to you indeed.
@RDT
@RDT 3 года назад
Sure! robertsdevtalk@gmail.com
@salemal-khalify7205
@salemal-khalify7205 3 года назад
@@RDT Already sent!
@friendlyfox2189
@friendlyfox2189 3 года назад
how do you do this with blazor 5.0 with file upload?
@RDT
@RDT 3 года назад
I'm still learning the ins and outs of Blazor - hope to make some videos on it soon. But IBrowserFile has an OpenReadStream method on it that you may be able to plug into a StreamReader/TextReader for the CsvReader constructor Source: docs.microsoft.com/en-us/aspnet/core/blazor/file-uploads?view=aspnetcore-5.0#file-streams docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.forms.ibrowserfile.openreadstream?view=aspnetcore-5.0
@rohitrockzz2633
@rohitrockzz2633 3 года назад
How to convert a CSV file into TXT file using c#.. Pls help
@RDT
@RDT 3 года назад
Hi rohit, CSV files are just plain text so theres no conversion needed (other than changing the file extension) - what sort of conversion were you thinking of?
@rohitrockzz2633
@rohitrockzz2633 3 года назад
@@RDT please contact asap Stucked in a project Help rohitkumarrairkr@gmail.com
@ILucas24I
@ILucas24I 2 года назад
I love you
@Koltayy
@Koltayy 2 года назад
thank you for the tutorial! it helps a lot.
@RDT
@RDT 2 года назад
You're welcome!
Далее
Intro to the CsvHelper Library for C#
27:12
Просмотров 27 тыс.
Coding Gem #1.4: Parsing CSV Data as Objects in C#
14:33
#kikakim
00:17
Просмотров 7 млн
Paint Projects
00:17
Просмотров 3,5 млн
Coding Gem #1.3: Parsing CSV Data as Lists in C#
24:31
How To Read And Write To  CSV Files In C#
33:06
ASP.NET Core Crash Course - C# App in One Hour
1:00:44
Просмотров 1,6 млн
10 C# Libraries To Save You Time And Energy
33:59
Просмотров 207 тыс.
C# Read CSV - Tutorial
12:21
Просмотров 7 тыс.
#kikakim
00:17
Просмотров 7 млн