Saboteur
Saboteur

Reputation: 31

C# write out specific cell from CSV file

I am a complete newbie as far as C# goes and I am currently trying to make a program that uses a csv file for source data.

Here's part of my code:

using (var sr = new StreamReader(fileInput))

while ((line = sr.ReadLine()) != null)
      {
      if (line.Contains(mK)) // <---Variable inputted by the user
        {
          Console.WriteLine(""+line);
          myValue = File.ReadAllLines(fileInput).Skip(1).First().Split(',')[0];
         }
        LineNumber++;
     }

The CSV file I am working with has maybe 8 columns each with a type of information. A single line is like one list of stuff.

However I've been sitting by this for 3 days now and I just have no idea how to have the file print out the specific line and column I want.

The thing I have here goes through each line and when it finds the input somewhere in the line, it writes out the line as a whole.

Afterwards I tried to create a var myValue, which would skip the first (Header) row and write the specific column I entered as the number at the end. However, I somehow need to find a way to change the line. Because it seems to always take the first data line only. I checked if it's reading the line number fine with the int LineNumber++ and it is giving me back the number I want. How do I put that number into the code so that it outputs the specific cell I need?

Upvotes: 0

Views: 1761

Answers (2)

blaze_125
blaze_125

Reputation: 2317

Federico already answered the question but, here's something for your other question in regards to your LineNumber variable.

using (var sr = new StreamReader(fileInput))

while ((line = sr.ReadLine()) != null)
      {
        LineNumber++;
        if(LineNumber < 1)//if reading header record
        {
        //skip
        }
        else
        {
        //not reading header line
        //check if the line meets your criteria
          if(line == "my anticipated value")
          {
              line.Split(',')[0];//pull index 0 from the array on strings created by split
          }
        }
     }

Upvotes: 0

Federico Dipuma
Federico Dipuma

Reputation: 18265

Why are you reading again the entire file just to skip one single line? You already have the line you are interested into in the line variable.

Just split it and get the column you need (the first one I suppose):

using(var sr = new StreamReader(fileInput))
while ((line = sr.ReadLine()) != null) {
    if (line.Contains(mK)) // <---Variable inputted by the user
    {
        var value = line.Split(",")[0];
        Console.WriteLine(value);
    }
}

Upvotes: 1

Related Questions