Search value in csv file using c#
You can create a function to do this task as below:
String GetAddress(String searchName)
{
var strLines=File.ReadLines("filepath.csv");
foreach(var line in strLines)
{
if(line.Split(',')[1].Equals(searchName))
return line.Split(',')[2];
}
return "";
}
you can call the above function as below:
String peterAddress=GetAddress("Peter");
EDIT:
String address="";
Dictionary<String, String> dict_Name_Address = new Dictionary<string, string>();
var lines=File.ReadLines("FileName.csv");
foreach (var line in lines)
{
dict_Name_Address.Add(line.Split(',')[1],line.Split(',')[2]);
}
if(dict_Name_Address.ContainsKey(searchKey))
address = dict_Name_Address[searchKey];
Getting specific row and column value in .csv file in c#
In case CSV file is simple one (no quotations), you can try Linq:
using System.IO;
using System.Linq;
...
public double GetVal(int row, int column) {
return File
.ReadLines(@"c:\MyFile.csv") //TODO: put the right name here
.Where(line => !string.IsNullOrWhiteSpace(line)) // to be on the safe side
.Skip(1) // Skip line with Titles
.Skip(row)
.Select(line => double.Parse(line.Split(',')[column]))
.First();
}
Note, that this code re-reads the file; you may want to read the file once:
string[][] m_Data = File
.ReadLines(@"c:\MyFile.csv")
.Where(line => !string.IsNullOrWhiteSpace(line))
.Skip(1)
.Select(line => line.Split(','))
.ToArray();
...
public double GetVal(int row, int column) => double.Parse(m_Data[row][col]);
C#, Read CSV for repeated cell values in 2 columns, count how many times something appears, add 1 to it and append it to a string for number increment
First, I noticed your counter is totally wrong. I just fixed your counter hope this can solve your problem.
string line;
StreamReader file = new StreamReader(@"C:\LOG.csv");
string headerLine = file.ReadLine() ;
var counter = new List<string>();
while (!string.IsNullOrWhiteSpace( (line = file.ReadLine()) ))
{
var cells = line.Split(','); // use your seprator => , |
var projectFullName = $"{cells[0]}_{cells[1]}"; // eg Toyota_2007
counter.Add(projectFullName);
}
var newName = ProjectName_TextBox.Text + "_" + ProjectBuild_TextBox.Text
var newCount = counter.Where(q=> q == newName).Count() + 1;
string freindlyName = $"{newName}_{newCount.ToString("00")}"; // freindlyName with correct number
file.Close();
UPDATE:
A better counter.
just add this function to your code and use it to get correct count of your records.
public int CountFromLogFile(string projectName, string projectBuild, char seprator ,string csvPath)
{
var isHeader = true;
var counterDic = new Dictionary<string,int>();
foreach (var line in File.ReadLines(csvPath))
{
if (isHeader)
{
isHeader = false;
continue;
}
var cells = line.Split(seprator); // 0 => projectName & 1 => projectBuild
var fName = $"{cells[0]}_{cells[1]}";
if (counterDic.ContainsKey(fName))
counterDic[fName]++;
else
counterDic.Add(fName,0);
}
var qName = $"{projectName}_{projectBuild}";
return counterDic.ContainsKey(qName) ? counterDic[qName] : 0 ;
}
Usage:
var count = CountFromLogFile(ProjectName_TextBox.Text , ProjectBuild_TextBox.Text , ',' , @"C:\LOG.csv");
Parsing CSV files in C#, with header
Let a library handle all the nitty-gritty details for you! :-)
Check out FileHelpers and stay DRY - Don't Repeat Yourself - no need to re-invent the wheel a gazillionth time....
You basically just need to define that shape of your data - the fields in your individual line in the CSV - by means of a public class (and so well-thought out attributes like default values, replacements for NULL values and so forth), point the FileHelpers engine at a file, and bingo - you get back all the entries from that file. One simple operation - great performance!
Related Topics
Prevent C# App from Process Kill
What Does Linq Return When the Results Are Empty
Should the Repository Layer Return Data-Transfer-Objects (Dto)
Xml File Creation Using Xdocument in C#
How to Change Route to Username After Logged In
Dispatcher Invoke(...) VS Begininvoke(...) Confusion
How to Include Subclasses in Swagger API Documentation/ Openapi Specification Using Swashbuckle
How to Create a File and Any Folders, If the Folders Don't Exist
Error Message "Cs5001 Program Does Not Contain a Static 'Main' Method Suitable for an Entry Point"
Why I'm Getting Cs1012: "Too Many Characters in Character Literal" and Cs0019
Xaml Gridview Itemtemplate Not Binding to Control
Project a Can't Reference a Class in Project B
How to Get the Last Four Characters from a String in C#
Only Primitive Types or Enumeration Types Are Supported in This Context