2

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

5
  • 2
    Check your input data. Something cannot be parsed to a double Commented Jul 4, 2016 at 10:08
  • 3
    It's impossible to help without seeing the original file and the new file. Commented Jul 4, 2016 at 10:08
  • You may have blank rows or null data (no numbers between the semicolons) which give the exception. It is not a good idea to attempt to read the entire file with one line of code. Write code that is more robust. Commented Jul 4, 2016 at 10:19
  • Can you provide us a sample of your .csv file? Commented Jul 4, 2016 at 10:23
  • @Tim Schmelter added both files Commented Jul 4, 2016 at 10:51

1 Answer 1

3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

dang it converted some parts in excell first - seems like 5 elements were treated as date\time thx it works now

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.