CSV Reader Issue
public class FlashcardService
{
// Using a library called CsvHelper to store and read flashcards from the CSV file
private readonly string _filePath = Path.Combine(Environment.CurrentDirectory, "Data", "flashcards.csv");
public List<Flashcard> LoadFlashcards()
{
// CsvReader allows for opening and reading the CSV file
using (var reader = new StreamReader(_filePath)) // Open file for reading
{
// Create a CsvReader instance using the StreamReader
var csvReader = new CsvReader((reader);
// Reads all records from the CSV and maps them to Flashcard objects
return csvReader.GetRecords<Flashcard>().ToList();
}
}
26 Replies
$code
To post C# code type the following:
```cs
// code here
```
Get an example by typing
$codegif
in chat
For longer snippets, use: https://paste.mod.gg/so, what issues are you having?
Im trying to read from a csv file using StreamReader but I keep recieving the error:
FlashcardService.cs(16, 44): [CS1503] Argument 1: cannot convert from 'System.IO.StreamReader' to 'CsvHelper.IParser'
hm, would that be on
var csvReader = new CsvReader((reader)
perhaps?
also, note that your number of parenthesis on that line are unbalanacedYes
yeah i fixed that part
ah so, the constructor for
CsvReader
that takes a StreamReader
also takes a culturesorry i dont know what a culture is haha
something like...
ohh okay so do i directly state the path in streamreader instead of storing that path in a variable?
that doesnt matter
look at the second row
oh and prefer the shorter using syntax that I use here over the body one you used
ahh i see thanks
and don't forget to add
using
to your csv reader
that must also be disposedwhat does the invariant culture mean?
so a
Culture
is an object that describes how to handle regional differences to things such as number separators etc
like, in the US they use 5.11
for numbers
but in sweden, we do 5,11
ohh right that makes sense
so CSV helper lets you specify a culture
the "InvariantCulture" is a fixed culture that mostly resembles the US standards
its good for data files
since for data, even us crazy swedes prefer
5.11
:Dokay yeah thanks
where can I learn more about these functions?
what functions?
CsvReader
?yeah stuff like that and also StreamReader
I'd recommend the official documentation for CsvHelper: https://joshclose.github.io/CsvHelper/getting-started/
Thank you
https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=net-8.0
the official docs for dotnet are very good
yeah theyre a bit hard to read haha
thanks though
they really aint once you get used to it
compared to most other languages, dotnets documentation is amazing 😛
okay ill try reading those