使用C#搜索CSV文件并在其旁边的列中提取值

我正在尝试创建我正在编写的程序(Visual Studio中的C#)在外部CSV文件中查找值,并将下一列中的值拉回到WinForm中的标签中。

我的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 

我尝试在下面的链接中使用解决方案,但只能返回最后一行第二列中的值。

使用c#在csv文件中搜索值

我一直在尝试让程序在“旧”列中搜索值,然后从匹配行的“newuser”列中提取值。 然后这将进入WinForm中的标签。

任何示例代码或建议将不胜感激。

使用CSV库读取CSV文件。 我喜欢这个https://joshclose.github.io/CsvHelper/

读取CSV文件并不像看起来那么简单。 第一个难点是值可以包含逗号。 步骤很简单,创建一个C#类来保存您的数据,将其映射到您在CSV文件中看到的数据,然后调用CSV库。 我链接的页面有足够的示例向您展示如何执行此操作。

使用Nuget包管理器控制台获取LinqToExcel复制代码PM>安装包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"])); } } 

这是另一个, Cinchoo ETL – 一个开源文件助手库,用于加载CSV文件并找到如下项目

 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()); } 

免责声明:我是这个图书馆的作者。

这是一个有趣的,可以在.Net中使用,但隐藏在Microsoft.VisualBasic.FileIO命名空间中: TextFieldParser 。 这可以读取与MS Office生成的内容完全相同的内容,甚至可以处理值内的换行符。

 public static List SplitFile(String filePath, Encoding textEncoding, Char separator) { String fileContents = File.ReadAllText(filePath, textEncoding); List splitLines = new List(); 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)); } } 

解析失败时,自带方便的MalformedLineException

当然,您需要将Microsoft.VisualBasic添加到项目引用中。