Paul Wilson
Paul Wilson

Reputation: 1

Using C# to search a CSV file and pull the value in the column next to it

I am trying to make a program I am writing (C# in Visual Studio) look up a value in an external CSV file, and pull the value in the next column back in to a label in my WinForm.

My CSV file, which is a test with dummy data, is:

> old,newuser,newpassword
> firstlinetomakesure,firstnewusername,firstnewpassword
> adslusernameplaintext,thisisthenewuser,andthisisthenewpassword
> hello,terion,nadiomn
> somethingdownhere,thisisthelastuser,andthisisthelastpassword 
> 11,12,13
> 21,22,23 
> 31,32,33

I have tried using the solution at the link below, but could only return the value in the second column of the last line.

Search value in csv file using c#

I've been trying to make the program search the "old" column for a value, then pull in the value from the "newuser" column on the matching row. This would then go onto a label in the WinForm.

Any example code or suggestions would be appreciated.

Upvotes: 0

Views: 3446

Answers (4)

Nyerguds
Nyerguds

Reputation: 5629

Here's an interesting one, natively available in .Net, but hidden away in the Microsoft.VisualBasic.FileIO namespace: TextFieldParser. This can read the contents exactly like they are produced by MS Office, and it can even handle line breaks inside values.

public static List<String[]> SplitFile(String filePath, Encoding textEncoding, Char separator)
{
    String fileContents = File.ReadAllText(filePath, textEncoding);
    List<String[]> splitLines = new List<String[]>();
    try
    {
        using (StringReader sr = new StringReader(fileContents))
        using (TextFieldParser tfp = new TextFieldParser(sr))
        {
            tfp.TextFieldType = FieldType.Delimited;
            tfp.Delimiters = new String[] { separator.ToString() };
            while (true)
            {
                String[] curLine = tfp.ReadFields();
                if (curLine == null)
                    break;
                splitLines.Add(curLine);
            }
        }
        return splitLines;
    }
    catch (MalformedLineException mfle)
    {
        throw new FormatException(String.Format("Could not parse line {0} in file {1}!", mfle.LineNumber, filePath));
    }
}

Comes with its own handy MalformedLineException when parsing fails.

You need to add Microsoft.VisualBasic to the project references, of course.

Upvotes: 0

Cinchoo
Cinchoo

Reputation: 6322

Here is another one, Cinchoo ETL - an open source file helper library to load CSV file and find the item as below

string csv = @"old,newuser,newpassword
firstlinetomakesure,firstnewusername,firstnewpassword
adslusernameplaintext,thisisthenewuser,andthisisthenewpassword
hello,terion,nadiomn
somethingdownhere,thisisthelastuser,andthisisthelastpassword 
11,12,13
21,22,23 
31,32,33";

using (var p = new ChoCSVReader(new StringReader(csv))
    .WithFirstLineHeader()
    )
{
    Console.WriteLine(p.Where(rec => rec.old == "hello").Select(rec => rec.newuser).First());
}

Disclaimer: I'm the author of this library.

Upvotes: 0

Akash Kool
Akash Kool

Reputation: 60

Get LinqToExcel Using the Nuget Package Manager Console Copy Code PM> Install-Package LinqToExcel

void PrintArtistAlbums()
{
    string pathToExcelFile = ""
        + @"D:\Code\Blog Projects\BlogSandbox\ArtistAlbums.xlsx";

    string sheetName = "Sheet1";

    var excelFile = new ExcelQueryFactory(pathToExcelFile);
    var artistAlbums = from a in excelFile.Worksheet(sheetName) select a;

    foreach (var a in artistAlbums)
    {
        string artistInfo = "Artist Name: {0}; Album: {1}";
        Console.WriteLine(string.Format(artistInfo, a["Name"], a["Title"]));
    }
}

Upvotes: 0

user2023861
user2023861

Reputation: 8208

Use a CSV library for reading CSV files. I like this one https://joshclose.github.io/CsvHelper/

Reading CSV files is not as straightforward as it seems. The number one difficulty is that values can have commas in them. The steps are simply, make a C# class to hold your data, map it to the data you see in your CSV file, and call the CSV library. That page I linked has enough examples to show you how to do this.

Upvotes: 2

Related Questions