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

Sdílet
Vložit
  • čas přidán 25. 02. 2021
  • 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.buymeacoffee.com/Robertsd...
    📬 Stay in touch! Join our mailing list
    robertsdevtalk.com
    🐦 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.github.io/CsvHelper/
    SpaceX open source REST API (unofficial), lots of fun sample data if you like rockets:
    github.com/r-spacex

Komentáře • 104

  • @RDT
    @RDT  Před 3 lety +5

    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! czcams.com/video/f5bzNh7hVhk/video.html

  • @paulkalus41
    @paulkalus41 Před 2 lety +1

    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 :)

  • @fellypsantos_
    @fellypsantos_ Před rokem

    Thank you so much sir! Finally understood how to use that lib! You're talented to teach us, clear didactic.

  • @DA_7
    @DA_7 Před 6 měsíci

    This has been truly educational and useful. Thank you so much for sharing!

  • @skyhymitch
    @skyhymitch Před 3 lety +4

    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  Před 3 lety +1

      Thanks Mitchell, its always nice to know it has helped someone! We have lots of new content planned. Appreciate the sub!

  • @patrickboehme4556
    @patrickboehme4556 Před 2 lety

    Great tutorial, thank you very much!

  • @briantremelling
    @briantremelling Před 2 lety

    Thanks. Video was easy to understand and got me going.

  • @Sharedbook
    @Sharedbook Před rokem

    The best I've seen!
    Just FLAWLESS!
    Thank you!

    • @RDT
      @RDT  Před rokem

      Wow, thank you! 🙏

  • @rmarikar1
    @rmarikar1 Před 2 lety +1

    Brilliant. Thank you. Such a good teacher!!

    • @RDT
      @RDT  Před 2 lety

      Glad it was helpful 🙏

  • @alexdpaiva83
    @alexdpaiva83 Před 2 lety

    Thank you very much for the tip, we from Brazil are grateful for your video.

    • @RDT
      @RDT  Před 2 lety

      Our pleasure!

  • @ayesamson
    @ayesamson Před 2 lety

    well done. delivered very clearly and easy to follow. cheers, mate!

    • @RDT
      @RDT  Před 2 lety

      No problem!

  • @Amy-ve3ke
    @Amy-ve3ke Před 2 lety

    Need to get this csv thing working !! Thanks

  • @Terrados1337
    @Terrados1337 Před rokem

    This was way more concise than anything google threw at me!
    Thank you very much!

    • @RDT
      @RDT  Před rokem +1

      You’re welcome ☺️ glad it was helpful to you

  • @davidgorenflo9260
    @davidgorenflo9260 Před rokem

    great Tutorial!

  • @Koltayy
    @Koltayy Před 2 lety

    thank you for the tutorial! it helps a lot.

    • @RDT
      @RDT  Před 2 lety

      You're welcome!

  • @glooman2455
    @glooman2455 Před 2 lety

    This video helped me a lot! You've got a new subscriber.

    • @RDT
      @RDT  Před 2 lety

      Happy to hear it was helpful for you. Thanks for the sub!

  • @Sabafbatlett
    @Sabafbatlett Před 6 měsíci

    This is so helpful many thanks mate!

    • @RDT
      @RDT  Před 6 měsíci

      You're welcome!

  • @TheMassijay
    @TheMassijay Před rokem +1

    Thank you, very helpful video! Can you tell me what extension do you use to preview csv files in vscode?

  • @IAmRaj360
    @IAmRaj360 Před rokem +1

    Loved one thanks.it very helpful for me

    • @RDT
      @RDT  Před rokem

      Thanks for your kind comment and support of the channel

  • @hassanOnYoutube
    @hassanOnYoutube Před 2 lety +1

    wonderful video, Love from Pakistan !

  • @alialsaady5
    @alialsaady5 Před rokem

    Thank you for the clear explanation! Do you know how I can change the csv path to the downloads folder

  • @AlbrechtJ
    @AlbrechtJ Před 2 lety

    Thanks for this good tutorial.

    • @RDT
      @RDT  Před 2 lety +1

      Sure! 🙏

  • @matejoo7663
    @matejoo7663 Před 3 lety +1

    great quality!

    • @RDT
      @RDT  Před 3 lety

      Thanks Matejoo , much appreciated

  • @miguelvale7364
    @miguelvale7364 Před 2 lety

    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

  • @udayshastri5288
    @udayshastri5288 Před 10 měsíci

    Great video. What if comma embedded in the one of the column.

  • @LambdaOverride
    @LambdaOverride Před rokem

    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  Před rokem +3

      Thanks for watching, glad it was helpful to you 🙂 The CSV files I used and source code are here: github.com/chrismroberts/csvreader-example

  • @Matzul98
    @Matzul98 Před 10 měsíci +1

    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.

  • @cifuentes678
    @cifuentes678 Před 2 lety +1

    Great tutorial! If I need some help with this, can I request your assistance?

  • @santoshanjani3860
    @santoshanjani3860 Před rokem

    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.

  • @DeepakSharma-wi4wu
    @DeepakSharma-wi4wu Před 2 lety

    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 ?

  • @robertosousa8065
    @robertosousa8065 Před 2 lety

    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.

  • @clsferguson
    @clsferguson Před 3 lety +1

    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  Před 3 lety +1

      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.

  • @durgaagoni8988
    @durgaagoni8988 Před 3 lety

    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  Před 3 lety

      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 Před 3 lety

      @@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 !

  • @rosabenitez7795
    @rosabenitez7795 Před rokem +1

    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  Před rokem

      Hi Rosa, sure - it’s at my GitHub repo github.com/chrismroberts/csvreader-example

  • @Michael-xb5zq
    @Michael-xb5zq Před rokem

    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  Před rokem +1

      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

  • @romanlemeshov5513
    @romanlemeshov5513 Před 2 lety +1

    Great tutorial, thanks! Can you tell, please, how convert "$2.34" to "2.34"( cut currency sign)?

    • @RDT
      @RDT  Před 2 lety

      Could use a regex to match the number part and then use Double.Parse on the resulting string?

  • @_blackmesa
    @_blackmesa Před 2 lety

    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  Před 2 lety

      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 czcams.com/play/PLGWG_rRY_j4MOABOppTH8XHJe8aOTyx2V.html

  • @Gmaaa
    @Gmaaa Před rokem

    Hi my register is ;...;"name "mr" robot"; ...; double quote is erros. How do I adjust to not give an error with this double quote?

  • @WesleiGomesdeSousa
    @WesleiGomesdeSousa Před 2 lety

    Robert, is there a way to work with positional data in text files instead of comma separators?

    • @RDT
      @RDT  Před 2 lety

      Hi Weslei, do you mean tab separated?

    • @getsmartpaul
      @getsmartpaul Před 2 lety

      @@RDT I think he means fixed position: e.g. col1 1-5 col2 6-16 col3 17-25 etc

  • @saeedahamed9347
    @saeedahamed9347 Před rokem

    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

  • @irvirv8243
    @irvirv8243 Před 3 lety +2

    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  Před 3 lety +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 Před 2 lety

      @@RDT thank you so much, I got this problem and this code solved it

  • @jimhat5753
    @jimhat5753 Před rokem

    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  Před rokem

      Hey JIM, here you go: github.com/chrismroberts/csvreader-example/

  • @ILucas24I
    @ILucas24I Před rokem

    I love you

  • @one-g4227
    @one-g4227 Před 2 lety

    How can you read csv with duplicate headers using dynamic class in

    • @RDT
      @RDT  Před 2 lety

      Duplicate column names? You could try using indexes instead. joshclose.github.io/CsvHelper/examples/configuration/class-maps/mapping-duplicate-names/

  • @friendlyfox2189
    @friendlyfox2189 Před 3 lety

    how do you do this with blazor 5.0 with file upload?

    • @RDT
      @RDT  Před 3 lety

      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

  • @grandmagus8618
    @grandmagus8618 Před 3 lety

    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 Před 3 lety

      i dont know specifically about your case, but i think in csvhelper documentation site the map thing was used

    • @RDT
      @RDT  Před 3 lety

      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 Před 3 lety +1

      @@RDT Thank you sir. it was timesaving respone :D

  • @mikeloose9270
    @mikeloose9270 Před 2 lety

    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 Před 2 lety +1

      great video by the way, love the way it is laid out and presented

    • @RDT
      @RDT  Před 2 lety

      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  Před 2 lety

      Thank you!

  • @chrismantonuk
    @chrismantonuk Před 3 lety +1

    Peng music 👍🏻

    • @RDT
      @RDT  Před 3 lety +1

      thanks

  • @anushripatil1059
    @anushripatil1059 Před 3 lety +1

    Hey..can you suggest what will be the changes in code if my csv file have no header

    • @RDT
      @RDT  Před 3 lety

      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 Před 3 lety +1

      @@RDT Thank you so much 😊

    • @anushripatil1059
      @anushripatil1059 Před 3 lety

      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  Před 3 lety +1

      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 Před 3 lety +1

      @@RDT Got it 👍 Thank you

  • @ld8778
    @ld8778 Před 2 lety +1

    Does anyone know how to skip headers? I have two headers that's causing issues with the CsVReader..

    • @RDT
      @RDT  Před 2 lety

      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 Před 2 lety +1

      @@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  Před 2 lety +1

      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 🙂

  • @McSeeMo_
    @McSeeMo_ Před 2 lety

    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}]");
    }
    }

  • @salemal-khalify7205
    @salemal-khalify7205 Před 3 lety +1

    awesome video.
    Could you please try to convert csv files that have double quotes inside.
    Thanks

    • @RDT
      @RDT  Před 3 lety +1

      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 Před 3 lety

      @@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  Před 3 lety +1

      Sure! robertsdevtalk@gmail.com

    • @salemal-khalify7205
      @salemal-khalify7205 Před 3 lety

      @@RDT Already sent!

  • @rohitrockzz2633
    @rohitrockzz2633 Před 2 lety

    How to convert a CSV file into TXT file using c#..
    Pls help

    • @RDT
      @RDT  Před 2 lety

      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 Před 2 lety

      @@RDT please contact asap
      Stucked in a project
      Help
      rohitkumarrairkr@gmail.com