Joe McGorry
Joe McGorry

Reputation: 25

Read the first column of a csv file in c#?

Is there an easy way to just read and display the first column of a CSV file in c#? Something like this?

String csv = File.ReadAllLines("@..\..\..\Data.csv).Split(',')[0];
Console.WriteLine(csv);

or do I have to loop over every line in the csv file and just take the first value for each line?

Thanks

Upvotes: 1

Views: 2847

Answers (3)

M.Fakhoury
M.Fakhoury

Reputation: 43

Try this:

public static async Task<HashSet<string>> GetFirstLineAsync(string fileFullname)
{
  try
  {
    var firstLine = await File.OpenText(fileFullname).ReadLineAsync().ConfigureAwait(false);
    return firstLine.Split(';').ToHashSet();
  }
  catch (UnauthorizedAccessException ex)
  {
   // TODO: Handle the System.UnauthorizedAccessException
  }
  catch (DirectoryNotFoundException ex)
  {
   // TODO: Handle the System.IO.DirectoryNotFoundException
  }
  catch (FileNotFoundException ex)
  {
   // TODO: Handle the System.IO.FileNotFoundException
  }
  catch (ArgumentException ex)
  {
   // TODO: Handle the System.ArgumentException
  }
  catch (PathTooLongException ex)
  {
   // TODO: Handle the System.IO.PathTooLongException
  }
  catch (NotSupportedException ex)
  {
   // TODO: Handle the System.NotSupportedException
  }
  catch (ObjectDisposedException ex)
  {
   // TODO: Handle the System.ObjectDisposedException
  }
  catch (InvalidOperationException ex)
  {
    // TODO: Handle the System.InvalidOperationException
  }
  return null;
}

And Call it like this:

var firstLine = await GetFirstLineAsync(@"C:\Temp\Test.csv").ConfigureAwait(false);

Upvotes: 1

smolchanovsky
smolchanovsky

Reputation: 1863

For reading csv files, I recommend using CsvHelper. You can use it like this:

var firstColumn = new List<string>();
using (var fileReader = File.OpenText("@..\..\..\Data.csv"))
using (var csvResult  = new CsvHelper.CsvReader(fileReader))
{
    while (csvResult.Read())
    {
        var field = csvResult.GetField<string>(0);
        firstColumn.Add(field);
    }
}

Upvotes: 2

taylorallen0913
taylorallen0913

Reputation: 95

According to this answer, you can choose which columns of your csv to extract.

var csv = File.ReadAllLines(@"C:..\..\..\Data.csv");
public List<MyMappedCSVFile>() myExtraction = new List<MyMappedCSVFile>();
foreach(string line in csv)
{
  var delimitedLine = line.Split(',');

  myExtraction.Add(new MyMappedCSVFile(delimitedLine[0], delimitedLine[1]));
}

Upvotes: 0

Related Questions