Reputation: 2413
I'm getting an issue with adding a Double
to a List<double>
from a CSV
file. Now I've done this before, with the exact same file, and added it to a Double Array
.
Here is my code that works with an array
:
double[] ch1Array = new double[arraySize];
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fileName = Path.Combine(filePath, openFileDialog1.FileName);
var reader = new StreamReader(File.OpenRead(fileName));
while(!reader.EndOfStream)
{
var line = reader.ReadLine(); //Get through the column titles
var values = line.Split(',');
if (dataSize > 0)
{
try
{
ch1Array[dataSize] = Convert.ToDouble(values[1]);
//etc...
This code works perfectly and the only thing I change is that I am not using an Array
anymore and instead am using a List<double>
:
List<double> ch1Array = new List<double>();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//Create stream reader and open file
string fileName = Path.Combine(mainFilePath, openFileDialog1.FileName);
var reader = new StreamReader(File.OpenRead(fileName));
int counter = 0;
//Read document until end of stream
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
try
{
ch1Array.Add(Convert.ToDouble(values[1]));
//etc..
Now I am assuming I am using the List
wrong (it's the first time I have used Lists
). Once the program gets to that section (it compiles and runs fine) it tells me I have an error and that my input string was not in the correct format. But since I can use the variable values[1]
in other contexts as a Double
I don't know what I am doing that is throwing the error.
Can anyone tell me what I am doing wrong?
EDIT: Here is the exception thrown:
Upvotes: 0
Views: 114
Reputation: 56566
The problem is that you are not parsing the CSV file correctly. It looks something like this:
"Some value","3276",Something
When you split on ,
, you end up with values[1]
being "3276"
(with the string having double quotes in it, not just 3276
), which cannot be parsed as a number. I recommend you use an existing CSV library, e.g. FileHelpers or google for something else.
Another problem with splitting on ,
is if a value contains a comma, e.g.:
"Some, value","3276",Something
Will be split into "Some
, value"
, "3276"
, and Something
. You'd then be trying to parse value"
, which obviously won't work. For this reason I wouldn't recommend just doing a Replace
to remove the quotes from your number.
Upvotes: 3
Reputation: 66499
You said your message box was showing the value to be "3276". This means you're trying to do Convert.ToDouble("\"3276\"")
which will throw the exception you're getting.
Change the following line:
Convert.ToDouble(values[1])
To:
Convert.ToDouble(values[1].Replace("\"",""));
Upvotes: 1