C# Can StreamReader check current line number? - c#

I tried making a script that would read a TXT file line by line, and change labels depending on what is inside.
Is there a way to check which line is being read?

This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class and you can just check the line string and matches with your desire label and replace with that.
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\test.txt");
while((line = file.ReadLine()) != null)
{
System.Console.WriteLine(line);
counter++;
}
file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
System.Console.ReadLine();
OR
using System;
using System.IO;
public class Example
{
public static void Main()
{
string fileName = #"C:\some\path\file.txt";
using (StreamReader reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
Hope this will help you.

You can try querying file with a help of Linq:
using System.IO;
using System.Linq;
...
var modifiedLines = File
.ReadLines(#"c:\myInitialScript.txt") // read file line by line
.Select((line, number) => {
//TODO: relevant code here based on line and number
// Demo: return number and then line itself
return $"{number} : {line}";
})
// .ToArray() // uncomment if you want all (modified) lines as an array
;
If you want write modified lines to a file:
File.WriteAllLines(#"c:\MyModifiedScript.txt", modifiedLines);
If you insist on StreamReader, you can implement a for loop:
using (StreamReader reader = new StreamReader("c:\myInitialScript.txt")) {
for ((string line, int number) record = (reader.ReadLine(), 0);
record.line != null;
record = (reader.ReadLine(), ++record.number)) {
//TODO: relevant code here
// record.line - line itself
// record.number - its number (zero based)
}
}

Related

Search string by means of StreamReader

I have this code in C # perform a string search from a .txt file, but it shows only one line.
and I need that 3 from the first match.
Example: Search: 1
result
line 1
line 2
line 3
Help me please. regards
.......................................
Text File
Code: 1
Note name: Josh
body Note : tex
Code: 2
Note name: Josh
body note: txt
C# Code
using System;
using System.IO;
class Test
{
public static void Main()
{
enter code here
try
{
string searchString = "some string";
searchString = Console.ReadLine();
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
if(line.Contains(searchString))
{
// Do some logic (the search string is found)
// I need to show 3 lines here
// Code:1
// Note name: Josh
// Body Note : tex
// for the moment Console.WriteLine(line);just shows me 1
Console.WriteLine(line);
count++;
}
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
The reason you are only getting one line is becuase your keep comparing the searchString with each line in the file once a match was found. You could add a flag to bypass the contains like:
bool found = false;
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
// bypass the search once we've found a match
if(found || line.Contains(searchString))
{
// Do some logic (the search string is found)
// I need to show 3 lines here
// Code:1
// Note name: Josh
// Body Note : tex
// for the moment Console.WriteLine(line);just shows me 1
found = true;
Console.WriteLine(line);
count++;
if(count == 3) {
break;
}
}
}
}
Or you could read the stream all the way to its end and then check and post-process:
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string contents = sr.ReadToEnd();
if (contents.Contains(searchString))
{
// do you magic here
}
}

Deleting some content from the text file in c#

I have text file called Load.txt which contains approximately 200 lines. I have a checkbox, If that is checked then I want to create a new file which had only first 100 lines from the Load.txt. And I am using c# for this program. Actually my real requirement is that I have to delete from line 110 to 201.And my code is below and because of some reason its deleting from line 1 to 92. I dnt know whats happening.
String line = null;
String tempFile = Path.GetTempFileName();
String filePath = saveFileDialog1.FileName;
int line_number = 110;
int lines_to_delete = 201;
using (StreamReader reader = new StreamReader(sqlConnectionString))
{
using (StreamWriter writer = new StreamWriter(saveFileDialog1.FileName))
{
while ((line = reader.ReadLine()) != null)
{
line_number++;
if (line_number <= lines_to_delete)
continue;
writer.WriteLine(line);
}
}
}
So I figured out this issue. But my next issue is that: I am updating some of variables in the text file. Before my that code was alright . But now That code is conflicting with my delete lines code. If I am able to delete lines then I m not able to update those variables.
My Code is:
File.WriteAllLines(saveFileDialog1.FileName, System.IO.File.ReadLine(sqlConnectionString).Take(110));
File.WriteAllText(saveFileDialog1.FileName, fileContents);
File.WriteAllLines("new.txt", File.ReadLines("Load.txt").Take(100));
After update...
var desired = File.ReadLines("Load.txt")
.Take(110) // "And I want to keep 1-110" -- OP
.Select(line => UpdateLine(line)); // "And I also want to update variables between 1-110" -- OP
File.WriteAllLines("new.txt", desired);
...
static string UpdateLine(string given)
{
var updated = given;
// other ops
return updated;
}
MSDN File.WriteAllLines
MSDN File.ReadLines
THis should accomplish what you need. It reads the text then dumps 100 lines of it.
System.IO.File.WriteAllLines("newLoad.txt", System.IO.File.ReadLines("Load.txt").Take(100));
"I want to create a new file which had only first 100 lines"
Keeping with your original model, here's one way to keep just the first 100 lines:
int LinesToKeep = 100;
using (StreamReader reader = new StreamReader(sqlConnectionString))
{
using (StreamWriter writer = new StreamWriter(saveFileDialog1.FileName))
{
for (int i = 1; (i <= LinesToKeep) && ((line = reader.ReadLine()) != null); i++)
{
writer.WriteLine(line);
}
}
}
"my real requirement is that I have to delete from line 110 to 201"
So copy the file, but skip lines 110 to 201?
int currentLine = 0;
using (StreamReader reader = new StreamReader(sqlConnectionString))
{
using (StreamWriter writer = new StreamWriter(saveFileDialog1.FileName))
{
while ((line = reader.ReadLine()) != null)
{
currentLine++;
if (currentLine < 110 || currentLine > 201)
{
writer.WriteLine(line);
}
}
}
}

Writing a specific line from one text file to other text file using c#

I Am using sharp develop. I am making a Win App using C# . I want my program check a text file named test in drive c: and find the line which contains "=" and then write this line to other newly created text file in drive c: .
Try this one-liner:
File.WriteAllLines(destinationFileName,
File.ReadAllLines(sourceFileName)
.Where(x => x.Contains("=")));
Here's another simple way using File.ReadLines, Linq's Where and File.AppendAllLines
var path1 = #"C:\test.txt";
var path2 = #"C:\test_out.txt";
var equalLines = File.ReadLines(path1)
.Where(l => l.Contains("="));
File.AppendAllLines(path2, equalLines.Take(1));
using(StreamWriter sw = new StreamWriter(#"C:\destinationFile.txt"))
{
StreamReader sr = new StreamReader(#"C:\sourceFile.txt");
string line = String.Empty;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("=")) { sw.WriteLine(line)); }
}
sr.Close();
}
Have you tried something?
Here are two ways to read a file:
Use static methods available in File class. ReadAllLines to be specific. This is good enough if you are dealing with small files. Next, once you have the array, just find the item with "=" using LINQ or by any other iteration method. Once you got the line, again use File class to create and write data to the file.
If you are dealing with large files, use Stream. Rest remains fairly same.
if (File.Exists(txtBaseAddress.Text))
{
StreamReader sr = new StreamReader(txtBaseAddress.Text);
string line;
string fileText = "";
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("="))
{
fileText += line;
}
}
sr.Close();
if (fileText != "")
{
try
{
StreamWriter sw = new StreamWriter(txtDestAddress.Text);
sw.Write(fileText);
sw.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
a bit edited Furqan's answer
using (StreamReader sr = new StreamReader(#"C:\Users\Username\Documents\a.txt"))
using (StreamWriter sw = new StreamWriter(#"C:\Users\Username\Documents\b.txt"))
{
int counter = 0;
string line = String.Empty;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("="))
{
sw.WriteLine(line);
if (++counter == 4)
{
sw.WriteLine();
counter = 0;
}
}
}
}

Delete last 3 lines within while ((line = r.ReadLine()) != null) but not open a new text file to delete the lines?

This is the code I've seen so far to delete last 3 lines in a text file, but it's required to determine string[] lines = File.ReadAllLines(); which is nt necessary for me to do so.
string[] lines = File.ReadAllLines(#"C:\\Users.txt");
StringBuilder sb = new StringBuilder();
int count = lines.Length - 3; // except last 3 lines
for (int s = 0; s < count; s++)
{
sb.AppendLine(lines[s]);
}
The code works well, but I don't wanna re-read the file as I've mentioned the streamreader above :
using (StreamReader r = new StreamReader(#"C:\\Users.txt"))
Im new to C#, as far as I know, after using streamreader, and if I wanna modify the lines, I have to use this :
while ((line = r.ReadLine()) != null)
{
#sample codes inside the bracket
line = line.Replace("|", "");
line = line.Replace("MY30", "");
line = line.Replace("E", "");
}
So, is there any way to delete the last 3 lines in the file within the "while ((line = r.ReadLine()) != null)" ??
I have to delete lines, replace lines and a few more modications in one shot, so I can't keep opening/reading the same text file again and again to modify the lines. I hope the way I ask is understable for you guys >.<
Plz help me, I know the question sounds simple but I've searched so many ways to solve it but failed =(
So far, my code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication11
{
public class Read
{
static void Main(string[] args)
{
string tempFile = Path.GetTempFileName();
using (StreamReader r = new StreamReader(#"C:\\Users\SAP Report.txt"))
{
using (StreamWriter sw = new StreamWrite (#"C:\\Users\output2.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
line = line.Replace("|", "");
line = line.Replace("MY30", "");
line = line.Replace("E", "");
line = System.Text.RegularExpressions.Regex.Replace(line, #"\s{2,}", " ");
sw.WriteLine(line);
}
}
}
}
}
}
Now my next task is to delete the last 3 lines in the file after these codes, and I need help on this one.
Thank you.
With File.ReadAllLines you have already read the file, so you can process each one line in the string[] (replaces and regexes), and then write them in the output. You don't have to reread them and put them in the StringBuilder.
You could keep a "rolling window" of the previous three lines:
string[] previousLines = new string[3];
int index = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
if (previousLines[index] != null)
{
sw.WriteLine(previousLines[index]);
}
line = line.Replace("|", "")
.Replace("MY30", "")
.Replace("E", "");
line = Regex.Replace(line, #"\s{2,}", " ");
previousLines[index] = line;
index = (index + 1) % previousLines.Length;
}
Instead of appending the lines directly to the string builder, you could keep a list of the lines and join them later on. That way you can easily leave out the last three lines.
To reduce the amount lines you have to keep in the list, you could regularly append one line of the list and remove it from it. So you would keep a buffer of 3 lines in an array and would pop & append a line whenever the buffer contains 4 lines.

Using StreamReader to check if a file contains a string

I have a string that is args[0].
Here is my code so far:
static void Main(string[] args)
{
string latestversion = args[0];
// create reader & open file
using (StreamReader sr = new StreamReader("C:\\Work\\list.txt"))
{
while (sr.Peek() >= 0)
{
// code here
}
}
}
I would like to check if my list.txt file contains args[0]. If it does, then I will create another process StreamWriter to write a string 1 or 0 into the file. How do I do this?
Are you expecting the file to be particularly big? If not, the simplest way of doing it would be to just read the whole thing:
using (StreamReader sr = new StreamReader("C:\\Work\\list.txt"))
{
string contents = sr.ReadToEnd();
if (contents.Contains(args[0]))
{
// ...
}
}
Or:
string contents = File.ReadAllText("C:\\Work\\list.txt");
if (contents.Contains(args[0]))
{
// ...
}
Alternatively, you could read it line by line:
foreach (string line in File.ReadLines("C:\\Work\\list.txt"))
{
if (line.Contains(args[0]))
{
// ...
// Break if you don't need to do anything else
}
}
Or even more LINQ-like:
if (File.ReadLines("C:\\Work\\list.txt").Any(line => line.Contains(args[0])))
{
...
}
Note that ReadLines is only available from .NET 4, but you could reasonably easily call TextReader.ReadLine in a loop yourself instead.
You should not add the ';' at the end of the using statement.
Code to work:
string latestversion = args[0];
using (StreamReader sr = new StreamReader("C:\\Work\\list.txt"))
using (StreamWriter sw = new StreamWriter("C:\\Work\\otherFile.txt"))
{
// loop by lines - for big files
string line = sr.ReadLine();
bool flag = false;
while (line != null)
{
if (line.IndexOf(latestversion) > -1)
{
flag = true;
break;
}
line = sr.ReadLine();
}
if (flag)
sw.Write("1");
else
sw.Write("0");
// other solution - for small files
var fileContents = sr.ReadToEnd();
{
if (fileContents.IndexOf(latestversion) > -1)
sw.Write("1");
else
sw.Write("0");
}
}
if ( System.IO.File.ReadAllText("C:\\Work\\list.txt").Contains( args[0] ) )
{
...
}
The accepted answer reads all file in memory which can be consuming.
Here's an alternative inspired by VMAtm answer
using (var sr = new StreamReader("c:\\path\\to\\file", true))
for (string line; (line = sr.ReadLine()) != null;) //read line by line
if (line.Contains("mystring"))
return true;

Categories

Resources