Search string by means of StreamReader - c#

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

Related

C# Can StreamReader check current line number?

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

File manipulation - procedure problems

I've been given a few different sets of procedures for various different things in C# under file manipulation.
I have forgotten basically how to call or use the procedures and so they are pretty much useless to me until I figure out how. Apologies for sounding stupid but I've done as much searching as I can and I can't relate other sources to my problem.
Here's a procedure I've been given:
void readFromTextFile(string path)
{
StreamReader sr = new StreamReader(path);
//Read the first line of text
string line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//write the line to console window
Console.WriteLine(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
}
Now I understand completely what this and all the other procedures do, yet I forget how to use them in main.
Here's what I currently have in main:
string path = "C:\\Users\\Joe\\Documents\\General\\College\\Computer Science\\Coding\\TextFileWork\\textFile.txt";
string readFile;
readFile = readFromTextFile(path);
Now the problem I'm having is understanding how to use the procedure back into main to return the read file. The string readFile is what I am trying to append the read text into, however I don't know how I should call the function in order to append it. Some basic help should suffice, thanks!
EDIT:
Here's the entire code I currently have (C# Console Application)
namespace TextFileWork_03._03._18
{
class Program
{
static void Main(string[] args)
{
string path = "C:\\Users\\Joe\\Documents\\General\\College\\Computer
Science\\Coding\\TextFileWork\\textFile.txt";
string readFile;
readFromTextFile(readFile);
if (File.Exists(path) == true)
{
//Create a file to write to.
Console.WriteLine(path + " Exists");
}
else
{
Console.WriteLine(path + " File not found");
}
FileInfo fi = new FileInfo(path);
FileStream fs = fi.Create();
fs.Close();
if (File.Exists(path) == true)
{
//Create a file to write to.
Console.WriteLine(path + " Now exists");
}
else
{
Console.WriteLine(path + " File still not found");
}
}
static void readFromTextFile(string path)
{
StreamReader sr = new StreamReader(path);
//Read the first line of text
string line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//write the line to console window
Console.WriteLine(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
}
}
}
To make your code work you'll need a return value from your method, otherwise you cannot say:
mysomthing = readFromTextFile
So, lets return a string value:
There is one problem: do you want to return a single line or just the whole file?
Here's the whole file version:
static string readFromTextFile(string path)
{
StreamReader sr = new StreamReader(path);
StringBuilder sb = new StringBuilder();
//Read the first line of text
string line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//write the line to console window
Console.WriteLine(line);
//Read the next line
line = sr.ReadLine();
sb.AppendLine(line);
}
//close the file
sr.Close();
return sb.ToString();
}
update this answer is not valid, I'll just keep it for a few minutes for reference.
You should have given more of your code to actually make this a valid question. Nevertheless, I'll try to help you out.
Your procedure (we call it methods in C#, (strongly related to functions)), lives in a class, lets call it Foo, but you can look it up in your code. Just scroll up: its the first blue class you'll see.
public class Foo //this is your class
{
void readFromTextFile(string path)
{
StreamReader sr = new StreamReader(path);
//Read the first line of text
string line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//write the line to console window
Console.WriteLine(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
}
}
To call it, from your Main method, you'll need an object
void Main()
{
string path = "C:\\Users\\Joe\\Documents\\General\\College\\ComputerScience\\Coding\\TextFileWork\\textFile.txt";
string readFile;
Foo fooObject = new Foo(); //create a new Foo
readFile = fooObject.readFromTextFile(path);
}

Searching for a Specific Word in a Text File and Displaying the line its on

I am having trouble attempting to find words in a text file in C#.
I want to find the word that is input into the console then display the entire line that the word was found on in the console.
In my text file I have:
Stephen Haren,December,9,4055551235
Laura Clausing,January,23,4054447788
William Connor,December,13,123456789
Kara Marie,October,23,1593574862
Audrey Carrit,January,16,1684527548
Sebastian Baker,October,23,9184569876
So if I input "December" I want it to display "Stephen Haren,December,9,4055551235" and "William Connor,December,13,123456789" .
I thought about using substrings but I figured there had to be a simpler way.
My Code After Given Answer:
using System;
using System.IO;
class ReadFriendRecords
{
public static void Main()
{
//the path of the file
FileStream inFile = new FileStream(#"H:\C#\Chapter.14\FriendInfo.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inFile);
string record;
string input;
Console.Write("Enter Friend's Birth Month >> ");
input = Console.ReadLine();
try
{
//the program reads the record and displays it on the screen
record = reader.ReadLine();
while (record != null)
{
if (record.Contains(input))
{
Console.WriteLine(record);
}
record = reader.ReadLine();
}
}
finally
{
//after the record is done being read, the progam closes
reader.Close();
inFile.Close();
}
Console.ReadLine();
}
}
Iterate through all the lines (StreamReader, File.ReadAllLines, etc.) and check if
line.Contains("December") (replace "December" with the user input).
Edit:
I would go with the StreamReader in case you have large files. And use the IndexOf-Example from #Matias Cicero instead of contains for case insensitive.
Console.Write("Keyword: ");
var keyword = Console.ReadLine() ?? "";
using (var sr = new StreamReader("")) {
while (!sr.EndOfStream) {
var line = sr.ReadLine();
if (String.IsNullOrEmpty(line)) continue;
if (line.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase) >= 0) {
Console.WriteLine(line);
}
}
}
As mantioned by #Rinecamo, try this code:
string toSearch = Console.ReadLine().Trim();
In this codeline, you'll be able to read user input and store it in a line, then iterate for each line:
foreach (string line in System.IO.File.ReadAllLines(FILEPATH))
{
if(line.Contains(toSearch))
Console.WriteLine(line);
}
Replace FILEPATH with the absolute or relative path, e.g. ".\file2Read.txt".
How about something like this:
//We read all the lines from the file
IEnumerable<string> lines = File.ReadAllLines("your_file.txt");
//We read the input from the user
Console.Write("Enter the word to search: ");
string input = Console.ReadLine().Trim();
//We identify the matches. If the input is empty, then we return no matches at all
IEnumerable<string> matches = !String.IsNullOrEmpty(input)
? lines.Where(line => line.IndexOf(input, StringComparison.OrdinalIgnoreCase) >= 0)
: Enumerable.Empty<string>();
//If there are matches, we output them. If there are not, we show an informative message
Console.WriteLine(matches.Any()
? String.Format("Matches:\n> {0}", String.Join("\n> ", matches))
: "There were no matches");
This approach is simple and easy to read, it uses LINQ and String.IndexOf instead of String.Contains so we can do a case insensitive search.
For finding text in a file you can use this algorithim use this code in
static void Main(string[] args)
{
}
try this one
StreamReader oReader;
if (File.Exists(#"C:\TextFile.txt"))
{
Console.WriteLine("Enter a word to search");
string cSearforSomething = Console.ReadLine().Trim();
oReader = new StreamReader(#"C:\TextFile.txt");
string cColl = oReader.ReadToEnd();
string cCriteria = #"\b"+cSearforSomething+#"\b";
System.Text.RegularExpressions.Regex oRegex = new
System.Text.RegularExpressions.Regex(cCriteria,RegexOptions.IgnoreCase);
int count = oRegex.Matches(cColl).Count;
Console.WriteLine(count.ToString());
}
Console.ReadLine();

moving file pointer in c# to a line containing specific string

I want some way to read from a .txt file in a way that I want to move pointer to a specific position and then read my .txt file containing strings in blocks like below
BLOCK1
string1
string2
string3
.....
.....
ENDOFBLOCK
BLOCK2
string1
string2
string3
.....
.....
ENDOFBLOCK
BLOCK3
string1
string2
string3
......
......
ENDOFBLOCK
Instead of reading file from beginning I want to move pointer to line containing string BLOCK2 and read up to line containing string ENDOFBLOCK. I want some method of C# that it searches a string in a file.
If found then it moves pointer in file to line containing that string and read file line by line up to a specific string. I hope I was
able to tell clearly what I want to do. Actually I am making an application of urdu language that's why I was unable to share actual code as example.
This should work:
using System;
using System.IO;
public class Program
{
public static void Main()
{
using (var fileStream = File.Open(#"c:\test.txt", FileMode.Open))
{
using (var streamReader = new StreamReader(fileStream))
{
string line = "";
while (line != "BLOCK2" && line != null)
{
line = streamReader.ReadLine();
}
line = streamReader.ReadLine();
while (line != "ENDOFBLOCK" && line != null)
{
Console.WriteLine(line);
line = streamReader.ReadLine();
}
}
}
}
}
since you dont know where block2 begins, you need to read the file from the top till you reach the string block2.(untested example)
while((line = file.ReadLine()) != "BLOCK2"){}
//block2 found
while((line = file.ReadLine()) != "ENDOFBLOCK") {
//this is what you want
}
thanks venerik and every body for help.below code worked for me.actually i did not know that a specific BLOCK occurred in file or not.so i have to read a file to end first and break if BLOCK found
public partial class MainWindow : Window
{
String stringfound;
public MainWindow()
{
InitializeComponent();
}
void clickhandler(object sender, RoutedEventArgs e)
{
String line;
try
{
StreamReader file = new StreamReader("d:\\test.txt");
while((line = file.ReadLine()) != null )
{
if (line.Contains("BLOCK2"))
{
stringfound=line;
break;
}
}
if(stringfound=="BLOCK2") // checking if BLOCK2 exists or not
{
while (line != "ENDOFBLOCK" && line != null)
{
line = file.ReadLine();
}
}
else // BLOCK2 not found
{
// do something else
}
}
catch(Exception)
{
MessageBox.Show("unknown exception occurred");
}
}
}
}

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