user2636163
user2636163

Reputation: 39

reading a CSV issue

I am trying to read a csv

following is the sample.

"0734306547          ","9780734306548       ","Jane Eyre Pink PP                       ","Bronte Charlotte                        ","FRONT LIST",20/03/2013 0:00:00,0,"PAPERBACK","Y","Pen"

Here is the code i am using read CSV

public void readCSV()
        {
            StreamReader reader = new StreamReader(File.OpenRead(@"C:\abc\21-08-2013\PNZdatafeed.csv"),Encoding.ASCII);
            List<string> ISBN = new List<String>();

            while (!reader.EndOfStream)
            {
                string line = reader.ReadLine();
                if (!String.IsNullOrWhiteSpace(line))
                {
                    string[] values = line.Split(',');
                    if (values[9] == "Pen")
                    {
                        ISBN.Add(values[1]);
                    }
                }
            }
            MessageBox.Show(ISBN.Count().ToString());

        }

I am not able to compare it values if (values[9] == "Pen") because when i debug the code it says values[9] value is \"Pen\""

How do i get rid of the special characters.?

Upvotes: 0

Views: 666

Answers (1)

Joe
Joe

Reputation: 3834

The problem here is that you're splitting the line every time you find , and leaving the data like that. For example, if this is the line you're reading in:

 "A","B","C"

and you split it at commas, you'll get "A", "B", and "C" as your data. According to your description, you don't want quotes around the data.

To throw away quotes around a string:

  1. Check if the leftmost character is ".
  2. If so, check if the rightmost character is ".
  3. If so, remove the leftmost and rightmost characters.

In pseudocode:

 if (data.left(1) == "\"" && data.right(1) == "\"") {
      data = data.trimleft(1).trimright(1)
 }

At this point you might have a few questions (I'm not sure how much experience you have). If any of these apply to you, feel free to ask them, and I'll explain further.

  1. What does "\"" mean?
  2. How do I extract the leftmost/rightmost character of a string?
  3. How do I extract the middle of a string?

Upvotes: 1

Related Questions