Get line number when reading a file - c#

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

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

C# Split with contains

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];
}
}
}

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

Reading and changing a file

I'm reading a file using C# and class TextReader
TextReader reader = new StreamReader(stream);
string line;
while ((line = reader.ReadLine()) != null)
{
if (someCondition)
{
// I want to change "line" and save it into the file I'm reading from
}
}
In a code there is a question: how do I save a changed line to a file I'm reading from and continue reading?
Fast and dirty solution would be:
TextReader reader = new StreamReader(stream);
string line;
StringBuilder sb = new StringBuilder();
while ((line = reader.ReadLine()) != null)
{
if (someCondition)
{
//Change variable line as you wish.
}
sb.Append(line);
}
using (StreamWriter sw = new StreamWriter("filePath"))
{
sw.Write(sb.ToString());
}
or
TextReader reader = new StreamReader(stream);
string line;
String newLines[];
int index = 0;
while ((line = reader.ReadLine()) != null)
{
if (someCondition)
{
//Change variable line as you wish.
}
newLines[index] = line;
index++;
}
using (StreamWriter sw = new StreamWriter("filePath"))
{
foreach (string l in newLines)
{
sw.WriteLine(l);
}
}
If memory is too important you can try this too:
TextReader reader = new StreamReader(stream);
string line;
while ((line = reader.ReadLine()) != null)
{
if (someCondition)
{
//Change variable line as you wish.
}
using (StreamWriter sw = new StreamWriter("filePath"))
{
sw.WriteLine(line);
}
}
The easiest thing is to write a new file, then when finished, replace the old file with the new file. This way you only do writes in one file.
If you try to read/write in the same file, you will run into problems when the content you want to insert is not the exact same size as the content it is replacing.
There is nothing magic about text files. They are just a stream of bytes representing characters in a text encoding. There are no line concept in the file, just separators in the form of newline characters.
If the file is not too large, you should simply rewrite the whole file:
var lines = File.ReadAllLines(path)
.Where(l => someCondition);
File.WriteAllLines(path, lines);
A very simple solution
void Main()
{
var lines = File.ReadAllLines("D:\\temp\\file.txt");
for(int x = 0; x < lines.Length; x++)
{
// Of course this is an example of the condtion
// you should implement your checks
if(lines[x].Contains("CONDITION"))
{
lines[x] = lines[x].Replace("CONDITION", "CONDITION2");
}
}
File.WriteAllLines("D:\\temp\\file.txt", lines);
}
The drawback is the memory usage caused by the in memory lines, but, if we stay around 50MB, it should be handled effortlessly by modern PC.

Categories

Resources