16

I've used streamreader to read in a .csv file, then i need to split the values and put them into a dictionary. so far i have:

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Dictionary<string, string> dict = new Dictionary<string, string>();   
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        using (StreamReader reader = new StreamReader("textwords0.csv"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                string[] parts = line.Split(',');
                dict.Add(parts[0], parts[1]);
            }
        }
    }

I keep getting the error "cannot convert from 'string[]' to 'string'" but cant work out how to fix it.

Thanks in advance!

update: ...I accidentally left the csv file open and its working now, sorry for wasting time guys thought i had a different spreadsheet open, some very useful advice though thanks for all the help!

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
jesusjuice
  • 163
  • 1
  • 1
  • 8

2 Answers2

45

If you're using .NET 4.0, the following is really succinct and should accomplish the same thing:

var dict = File.ReadLines("textwords0.csv").Select(line => line.Split(',')).ToDictionary(line => line[0], line => line[1]);
Shiva
  • 20,575
  • 14
  • 82
  • 112
Taylor Southwick
  • 1,456
  • 13
  • 14
  • 2
    not sure this would work if you have data with ',' in them. you need csv parser here. – nakhli Mar 20 '12 at 17:05
  • 4
    this is fragile as the value could be wrapped in quotes if it contains a comma `("this is, a value")` - the value will be split in half – James Shuttler Mar 20 '12 at 17:06
  • 1
    That's true about it not checking if the comma is in a quote or the data, but @jesusjuice doesn't seem worried about that. – Taylor Southwick Mar 20 '12 at 17:14
  • 1
    You could try using a regex like the following: var rgx = new System.Text.RegularExpressions.Regex("\"(.*?)\"|,"); rgx.Split("open,\"drive, over the , moon\",kriston"); – ermagana Aug 23 '13 at 16:07
  • This fails if the CSV file has fields that contain commas enclosed in quotes, which is a very common scenario. Ex: `"This is 1st column, that also has a comma inside, so excel encloses column value in quotes",This is 2nd column no comma inside.` – Shiva Sep 06 '15 at 01:26
0

the error is actually because of the ',' you are inputting. It needs an "array" of characters to split from. Here is an example method of splitting using string.split.

string[] parts = line.Split(new string[] { "," }, StringSplitOptions.None);

Hope this helps. this is presuming this is the line the error is coming from as you havn't specified.

Skintkingle
  • 1,579
  • 3
  • 16
  • 28
  • apparently its line 33 which is the last }. I'm fairly new to programming in general so finding this slightly confusing. Thanks! – jesusjuice Mar 20 '12 at 17:35