Simple way to read select lines from a file - c#

There are 100 Lines in my .txt file. This code will read every line, Line by line. How do I change the outcome to only read line 3, line 4, and line 5 respectively?
string[] lines = System.IO.File.ReadAllLines(#"C:\Horoscope\iso_8859-1.txt");
foreach (string line in lines)
{
// Use a tab to indent each line of the file.
Console.WriteLine("\t" + line);
}

You can use System.IO.StreamReader to read the file line by line
int counter = 1;
string line;
// Read the file line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(#"C:\Horoscope\iso_8859-1.txt");
while((line = file.ReadLine()) != null)
{
if(counter > 5)
{
// No need to continue
break;
}
else if(counter >= 3)
{
System.Console.WriteLine(line);
}
counter++;
}
file.Close();

Related

How do I read a file for a specific line

I'm making a console application and I need to be able to write, search and delete entries from within text files, I can write files into a notepad file but that's basically it, this is what I have to read the file:
public static void SearchDetails()
{
Console.WriteLine("Enter ID Number");
string myfile = System.IO.File.ReadAllText(#"C:\\file.txt");
System.Console.WriteLine(myfile);
}
This brings up all the text in the file but I need to be able to search for a specific number within the file and then brings up the next three lines below it. How to I get it to read the input so that it matches with a number in the text file and then bring up the next 3 lines?
So you can do whatever you want with the results but something like this is what you want
// Read the file and display next three lines
System.IO.StreamReader file = new System.IO.StreamReader("c:\\file.txt");
string line;
int lineCnt = 3;
while((line = file.ReadLine()) != null)
{
if (line.Contains(myID) & !bGet)
{
bool bGet = true;
}
if (bGet && lineCnt > 0)
{
bool bGet = true;
Console.WriteLine (line);
lineCnt--;
}
if(lineCnt == 0) {break;}
}
file.Close();
// Suspend the screen.
Console.ReadLine();
Considering you question and comments to answer, the final answer would be:
public static void SearchDetails()
{
Console.WriteLine("Enter ID Number");
int Id = 0;
int.TryParse(Console.ReadLine(), out Id);
string[] lines = System.IO.File.ReadAllLines(#"C:\\file.txt");
List<string> IdLines = lines.Where((x, i) => i % 4 == 0).ToList();
int IdLine = IdLines.IndexOf(Id);
if (IdLine != -1)
{ //then result found
//Id is what user searched for or
// string Id = lines[IdLine*4];
//string[] results = lines.Where((x, i) => i > IdLine * 4 && i < IdLine * 4 + 4).ToArray();
for(int i=IdLine*4;i<IdLine*4+4;i++)
System.Console.WriteLine(lines[i]);
}
else
{
Console.WriteLine("no results!");
}
}

I want to read text files from a folder?

In the code Below:
I read from just one text file, but i want to read from multiple files in a folder and then assign the variables and create a new instance of appointment for each file??
public bool Load()
{
DateTime start = new DateTime(2000,01,01);
int length = 0;
string screenDiscription = "";
string line;
int i = 1;
StreamReader sr = new StreamReader("Appointments.txt");
if (!File.Exists("Appointments.txt"))
{
return true;
}
while ((line = sr.ReadLine()) != null)
{
if (i % 4 == 1)
{
start = DateTime.ParseExact(line, "dd/MM/yyyy HHmm", CultureInfo.CreateSpecificCulture("en-GB"));
}
if (i % 4 == 2)
{
length = int.Parse(line);
}
if (i % 4 == 3)
{
screenDiscription = line;
apps.Add(new Appointment(start, length, screenDiscription));
}
i++;
}
sr.Close();
return true;
}
To get the all the files in a directory use the function System.IO.Directory.GetFiles("directoryPath");
Read this page for the documentation
https://msdn.microsoft.com/en-us/library/system.io.directory(v=vs.110).aspx

How to skip multiple iterations in a while loop

I'm reading a text file line by line in a While loop. When I reach a specific line I want to skip the the current and the next 3 iterations.
I guess I can do it using a counter and things like that. But I was wondering if there is a more elegant way?
using (var sr = new StreamReader(source))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line == "Section 1-1")
{
// skip the next 3 iterations (lines)
}
}
}
Have a for loop to execute sr.ReadLine 3 times and discard the result like:
using (var sr = new StreamReader(source))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line == "Section 1-1")
{
for (int i = 0; i < 3; i++)
{
sr.ReadLine();
}
}
}
}
You should check for sr.ReadLine returning null or if the stream has come to an end.
You can use File.ReadAllLines with method extesions:
public static IEnumerable<string> SkipLines(string file, string line, int count)
{
var enumerable = File.ReadLines(file).GetEnumerator();
while (enumerable.MoveNext())
{
var currentLine = enumerable.Current;
if (currentLine == line)
{
var currentCount = 0;
while(enumerable.MoveNext() && currentCount < count)
{
currentCount += 1;
}
}
yield return currentLine;
}
}
usage:
foreach (var line in SkipLines(source, "Section 1-1", 3))
{
// your line
}
Keep in mind: ReadLines is lazy - not all lines are loaded into memory at once.
Make yourself a function that discards a given number of lines (DiscardLines) and use it:
string line;
while ((line = sr.ReadLine()) != null)
{
if (line == "Section 1-1")
{
DiscardLines(sr, 3);
}
}
That keeps the main loop very simple. The counter is now hidden in DiscardLines.
using (var sr = new StreamReader(source))
{
string line;
int linesToSkip = 0;
while ((line = sr.ReadLine()) != null)
{
if (linesToSkip > 0)
{
linesToSkip -= 1;
continue;
}
if (line == "Section 1-1")
{
// skip the next 3 iterations (lines)
linesToSkip = 3;
}
}
}

Use the output(StreamReader) line as file name(rename)

I am trying to use the output("line")as a new file name(files already exist, just rename).
e.g. "A,tampqer,n:.jpg"
but it looks like:
e.g. line ="A\tampqer\tn:\t\t"
I get an error: illegal character for the file name.
int counter = 0;
string line;
// Read the file and display it line by line.
StreamReader file = new StreamReader(#"C:\\german-czech.txt");
while ((line = file.ReadLine()) != null)
{
//replace /t doesnt work
for (int i = 0; i < line.Length; i++)
{
if (line[i] == '\t')
{
line.Replace(line[i], ',');
}
}
//Console.WriteLine(string.Format(line, #"\\t").ToString());
Console.WriteLine( line);
counter++;
if (counter == 100)
break;
}
file.Close();
And guess what the content of the "line" is still the same ... can anyone help me up with this little problem ?
what else did I try ?
line.Replace(System.Environment.NewLine, ",");
string.empty...
"\n"
Best regards
You need
line = line.Replace(line[i], ',');
It doesn't change it in place. It returns a new string.
You also don't need to transverse the string one by one. Replace will replace every occurrence in the string. So instead of your:
//replace /t doesnt work
for (int i = 0; i < line.Length; i++)
{
if (line[i] == '\t')
{
line.Replace(line[i], ',');
}
}
Just have:
line = line.Replace("\t", ',');
(This is correcting your code. But I think mrzli in his comment got the real error.)

Counting the number of words from a file

A word in this context is defined is a letter or a number. However, something like \n is not considered a word.
Below in my code I am trying to count the number of words in a file but at the for loop's local variable declaration I get the error Null Reference exception.
I am not sure why I get this error. I get the variable Line equal to null which shouldn't happen because the text file DOES have one word "hello world" in it..
StreamReader sr = new StreamReader(filePath);
while (sr.ReadLine()!=null)
{
Line =sr.ReadLine();
for (**int i = 1**; i < (Line.Length+1); i++)
{
if (Char.IsLetterOrDigit(Line[i]) == true && Char.IsLetterOrDigit(Line[i - 1]) == true)
{
if (LetterRecent == false)
{
wordCount = wordCount + 1;
}
LetterRecent = true;
}
else
{
LetterRecent = false;
}
}
}
sr.Close();
You're doing ReadLine() twice for each line.
You could do something like:
count = 0;
while (line = sr.ReadLine()) {
char oldChar = 0;
for (char c in line) {
if (c != oldChar && Char.IsLetterOrDigit(c)) count++;
oldChar = c;
}
}
You are discarding half of the lines in the file by calling sr.ReadLine() twice. If you read the last line of the file in the while statement, the call to Line.Length will throw the null reference exception.
Try something this:
var wordCount = 0;
var line = sr.ReadLine();
while( line != null ) {
for( var i = 1; i < line.Length; i++ ) {
// Count words
}
line = sr.ReadLine();
}
You need to declare wordCount before using it.
Int wordCount = 0;
while (sr.ReadLine()!=null)
{
Update your loop condition to be like this:
while (sr.Peek() >= 0)
{
Line = sr.ReadLine();
}

Categories

Resources