Search code examples
c#csvtoarray

c# csvfile to array


I had a .csv file with many lines and 3 columns (separated by ';') with numbers, which I convert to double array[][] Now I've added to more columns of numbers and get an error:

FormatException -> Input string was not in a correct format

I can't find whats wrong because files are identical (but with 2 more columns) My code:

OpenFileDialog fD = new OpenFileDialog();
fD.Title = "select";
fD.Filter = "csv files|*.csv";
fD.InitialDirectory = @"path here";
if (fD.ShowDialog() == DialogResult.OK)
    MessageBox.Show(fD.FileName.ToString());

double[][] termom = File.ReadLines(fD.FileName)
    .Select(l => l.Split(';')
        .Select(n => double.Parse(n))
        .ToArray())
    .ToArray();

Edit Thanks for help with edit - not very used to commands here. Hope i added file right original improved


Solution

  • Your file res1.csv (providing that it should contain double values only) has some syntax errors, e.g.

    1881081,9;6,315177;352,499964;01,06,1974;350,645

    What is the meaning of 01,06,1974? Shall we ignore commas (treat them as, say, some kind of thousands separator)? Or is it a date (1 June 1974)? Yet another possibility is that , is a deriver, so we have three separate values: 1, 6 and 1974

    In case you want to ignore commas (and thus 01,06,1974 will be 1061974.0), just specify InvariantCulture while parsing:

    double[][] termom = File.ReadLines(fD.FileName)
      .Select(l => l.Split(';')
        .Select(n => double.Parse(n, CultureInfo.InvariantCulture))
        .ToArray())
      .ToArray();
    

    If you want to treat , as a deriver (and thus 01,06,1974 will be [1.0, 6.0, 1974.0])

    double[][] termom = File.ReadLines(fD.FileName)
      .Select(l => l.Split(';', ',') // ',' is a deriver as well as ';'
        .Select(n => double.Parse(n, CultureInfo.InvariantCulture))
        .ToArray())
      .ToArray();