C# Split with contains - c#

I have a few trouble with my project.
My string is
11713,Julia's_Candy,Julia's Candy
1713,Julia's_Head,Julia's Head
Now I am using my code like this string line;
using (StreamReader file = new StreamReader(#"db.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(("1713"+",")))
{
label1.Text = line.Split(',')[2];
}
}
}
I want Julia's Head to be print out but it have the same number that including in 11713,Julia's_Candy,Julia's Candy.And its print Julia's Candy
So I want to ask that how can I fix this code for more accurate.
Thank you

If you split first, you can use the first column as an Id column and search for exact match:
string line;
using (StreamReader file = new StreamReader(#"db.txt"))
{
while ((line = file.ReadLine()) != null)
{
var values = line.Split(",");
if (values[0] == "1713")
{
label1.Text = values[2];
}
}
}

Related

StreamReader ReadLine() for CSV files

I am trying to use this code to create a list. It is failing at the NewCrime Convert step. Not sure how to use the stream reader. It is my first time and I usually use SQL so I have attempted to do the same thing I would do reading SQL here.
List MasterCrimeList;
public List<Crime.Crime> GetList()
{
MasterCrimeList = new List<Crime.Crime>();
try
{
string path = #"F:\\FanshaweCollegeClasses\\Winter2020\\CLAYS_FINAL_EXAM_2020\\VANHEESfinalEXAM\\SacramentocrimeJanuary2006.csv";
if (File.Exists(path))
{
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s;
while ((s = sr.ReadLine()) != null)
{
Crime.Crime NewCrime = new Crime.Crime(Convert.ToString(s[0]),//CrimeDateTime
Convert.ToString(s[1]),//CrimeAddress
Convert.ToInt32(Convert.ToString(s[2])),//CrimeDistrict
Convert.ToString(s[3]),//CrimeBeat
Convert.ToInt32(Convert.ToString(s[4])),//CrimeGrid
Convert.ToString(s[5]),//CrimeDescription
Convert.ToInt32(Convert.ToString(s[6])),//ncicCode
decimal.Parse(Convert.ToString(s[7])),//Latitude DECIMAL
decimal.Parse(Convert.ToString(s[8])));//Longitude DECIMAL
MasterCrimeList.Add(NewCrime);
}
}
}
}
When doing s[0] you're reading only one char of the whole line. What you should do is to split each line based on how the values are stored using Split(), and then you can access each value as an array. If it's a csv file:
string s;
while ((s = sr.ReadLine()) != null)
{
string[] lineValues = s.Split(new char[]{','});
string firstValue = lineValues[0];
string secondValue = lineValues[1];
...
}

C# How do I compare a string to a specific line in a file?

Let's say I have a string "Toast" and I want to check to see if line "n" of a text file contains that string. How do I go about this? I know "n"
Simple solution:
using(var reader = new StreamReader("MyFile.txt"))
{
string line;
int lineNumber = 0;
while((line = reader.ReadLine()) != null)
{
lineNumber++;
if (line.Contains("Toast"))
{
Console.WriteLine($"Found 'Toast' on line {lineNumber}");
}
}
}

Get line number when reading a file

I am reading all lines in a text file using C# 7 as follows:
using (StreamReader reader = File.OpenText(file)) {
String line;
while ((line = reader.ReadLine()) != null) {
}
}
For each line I also need to get the line number.
StreamReader does not seem to have a method for getting the line number.
What is the best way to do this?
I'd just create an integer to keep track of the line number myself.
using (StreamReader reader = File.OpenText(file)) {
var lineNumber = 0;
String line;
while ((line = reader.ReadLine()) != null) {
...
lineNumber++;
}
}
Microsoft also uses such a variable to count the lines in one of the examples: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-read-a-text-file-one-line-at-a-time
You should use your own local variable for it, like that:
using (StreamReader reader = File.OpenText(file)) {
String line;
int lineNum=0;
while ((line = reader.ReadLine()) != null) {
++lineNum;
}
}
In addition to the other solutions here, I like to use File.ReadAllLines(string) to create a string[] result and then for (int i = 0; i < result.Length; i++)....
you can compute line number by your self:
using (StreamReader reader = File.OpenText(file)) {
String line;
int n = 0;
while ((line = reader.ReadLine()) != null) {
n++;
}
}
I know this is already solved and old but I want to share an alternative. The code just returns the line number where it founds a part of the string given, to have the exact one just replace "Contains" with "Equals".
public int GetLineNumber(string lineToFind) {
int lineNum = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while ((line = file.ReadLine()) != null) {
lineNum++;
if (line.Contains(lineToFind)) {
return lineNum;
}
}
file.Close();
return -1;
}

find a line and read/display the next line in text document C#

I have this code so far. It looks through a text document and displays lines with the word word in them. I want to make it skip that line and display the next one in the text document, how do I do that?
e.g. it looks thought the text document and finds a line with the word "word" in it and then displays the line that comes after it no other line
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("test.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains("word"))
{
Console.WriteLine(line);
}
}
file.Close();
If you're trying to write the line following an occurence of word in a line, try this:
int counter = 0;
bool writeNextLine = false;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("test.txt");
while ((line = file.ReadLine()) != null)
{
if (writeNextLine)
{
Console.WriteLine(line);
}
writeNextLine = line.Contains("word");
counter++;
}
file.Close();
Something like this will show all the lines except empty lines and lines with the word "word"
using (var rdr = new StreamReader(#"C:\Users\Gebruiker\Desktop\text.txt"))
{
while (!(rdr.EndOfStream))
{
var line = rdr.ReadLine();
if (!(line.Contains("word")) && (line != String.Empty))
{
Console.WriteLine(line);
}
}
}
Console.ReadKey();
This should display all lines after those that contain "word".
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("test.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains("word"))
{
if ((line = file.ReadLine()) != null)
Console.WriteLine(line);
}
counter++;
}
file.Close();

Extract data from text file

I need to extract some data from a text file and insert to columns in excel sheet. I know how to do this if the rows and the length of the string is known.
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader("test.txt")
{
string line;
while ((line = sr.ReadLine()) != null)
{
listSNR.Items.Add(line.Substring (78,4));
}
}
}
But the particular text file is complex and the starting index or the length cannot be provided. But the starting word (PCPU01) of the row is known.
Eg: PCPU01,T2716,0.00,0.01,0.00,0.00
output:
T2716 0 0.01 0 0
In that case can somebody please let me know how to extract the texts?
using(System.IO.StreamReader sr = new System.IO.StreamReader("test.txt"))
{
string line;
while((line = sr.ReadLine()) != null)
{
string[] split = line.Split(',');
//...
}
}
split[0] will return "PCPU01", split[1] "T2716" and so on.
You can split one string into an array of strings, separated by a given character. This way, you could split the source string by a comma and use the resulting strings to build your output. Example:
string source = "PCPU01,T2716,0.00,0.01,0.00,0.00";
string[] parts = source.Split(',');
StringBuilder result = new StringBuilder();
result.Append(parts[1]); // The second element in the array, i.e. T2716
result.Append(" ");
result.Append(parts[2]); // 0.00
... // And so on...
return result.ToString() // return a string, not a StringBuilder
I hope this helps a little bit. You might have to tweak it to your needs. But this is a higher level code that gives you general idea of extracting data off a notepad.
DialogResult result = openFileDialog.ShowDialog();
Collection<Info> _infoCollection = new Collection<Info>();
Collection<string> listOfSubDomains = new Collection<string>();
string[] row;
string line;
// READ THE FILE AND STORE IT IN INFO OBJECT AND STORE TAHT INFO OBJECT IN COLLECTION
try
{
using (StreamReader reader = new StreamReader(openFileDialog.FileName))
{
while((line = reader.ReadLine()) != null)
{
Info _info = new Info();
row = line.Split(' ');
_info.FirstName = row[0];
_info.LastName = row[1];
_info.Email = row[2];
_info.Id = Convert.ToInt32(row[3]);
_infoCollection.Add(_info);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
thanks for the answers. What i wanted is to identify the particular line in the text file and split the line into columns. So i was able to do this by calling a GetLine method:
string line15=GetLine(#"test.txt",15);
public string GetLine(string fileName, int line)
{
using (System.IO.StreamReader ssr = new System.IO.StreamReader("test.txt"))
//using (var ssr = new StreamReader("test.txt"))
{
for (int i = 1; i < line; i++)
ssr.ReadLine();
return ssr.ReadLine();
}
}
Then i splitted this line by using the delimiter (,)
This was my approach in C#. It takes a string input (which you can get out of a text file) and an int with which line you want to get. It then separates the string at a given seperator char to a list which in turn is then read out. If the given line number is lower than the count of the created list, the entry is given back.
public string GetLine(string multiline,int line)
{
List<string> lines = new List<string>();
lines = multiline.Split('\n').ToList<string>();
return lines.Count >= line ? lines[line] : "";
}

Categories

Resources