Reputation: 13
So a searched for a solution to this and some people have already asked but I wasn't sure if their answers would work for me? I copied this code and pasted it to one of my class's constructor:
var Lines = File.ReadLines("C:\\Users\\k20\\Source\\Repos\\TS_Webform\\TS_Webform\\Forms\\emails.csv").Select(a => a.Split(';'));
var CSV = from line in Lines select (line.Split(',')).ToArray(); //error on "Split"
I get this error message:
"Error CS1061 'string[]' does not contain a definition for 'Split' and no extension method 'Split' accepting a first argument of type 'string[]' could be found (are you missing a using directive or an assembly reference?)"
When writing to my csv file, the first line is skipped entirely and then line 2 and onward will have 5 elements written as such: [email protected],example,15555555555,1234567890,1234567890
every addition is like this. I'm not sure how the first skipped line will affect my code.
Upvotes: 0
Views: 422
Reputation: 7029
The error is because you are already calling split once before on your first line:
var Lines =
File
.ReadLines("C:\\Users\\k20\\Source\\Repos\\TS_Webform\\TS_Webform\\Forms\\emails.csv")
.Select(a => a.Split(';')); // <--- This is causing your problem.
So Lines
is an IEnumerable<string[]>
. You then try to enumerate over each string[]
and call Split
on it but string[]
has no such function.
In general this is a naive approach to parsing a CSV file. What happens if one of the values contains a comma:
"e.g., like this"
In this case you would end up splitting your value. You know your data so you may be able to say with certainty that this will not be an issue. If so great. If not I would check NuGet for an existing package that can help you with this.
Based on your comments this may suffice:
var csv =
File
.ReadLines("C:\\Users\\k20\\Source\\Repos\\TS_Webform\\TS_Webform\\Forms\\emails.csv")
.Select(line => line.Split(','))
.ToArray();
After this csv
will by type string[][]
. But as I said, if you suspect that your values may contain commas this will not be sufficient. Check one of these NuGet packages.
Upvotes: 0
Reputation: 37070
As I pointed out in the comment, Lines
is an IEnumerable<string[]>
, not an IEnumerable<string>
, because you're calling Split(';')
at the end.
To resolve this, you can either use SelectMany
, which will capture all the items from your first Split(';')
and add them to the Lines
list:
var Lines = File
.ReadLines(@"C:\Users\k20\Source\Repos\TS_Webform\TS_Webform\Forms\emails.csv")
.SelectMany(a => a.Split(';'));
Or, if you know you want just the first item, for example, from the original split, then you could select it using index syntax ([0]
):
var Lines = File
.ReadLines(@"C:\Users\k20\Source\Repos\TS_Webform\TS_Webform\Forms\emails.csv")
.Select(a => a.Split(';')[0]);
Also, consider using a library, like File Helpers for parsing CSV files. Split
can cause some issues if you aren't sure about the contents of the file.
Upvotes: 2