Search Text File Using C# and Display the Line Number and the Complete Line That Contains the Search Keyword

search text file using c# and display the line number and the complete line that contains the search keyword

This is a slight modification from: http://msdn.microsoft.com/en-us/library/aa287535%28VS.71%29.aspx

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
if ( line.Contains("word") )
{
Console.WriteLine (counter.ToString() + ": " + line);
}

counter++;
}

file.Close();

C# Search file for a string and get the string's line number

I think a for loop makes more sense here

var lines = File.ReadAllLines(filepath);
for (int i = 0; i < lines.Length; i++)
{
if(lines[i].Contains("motd="))
{
lines[i] = "motd=" + textBox1.Text;
}
}

File.WriteAllLines(filepath, lines);

A couple of issues with your code was that you were writing out the file in side the loop and you incremented the index by 1 which would then point to the wrong line in the array and result in the exception you are getting if the last line contains the text you are searching for.

It should be noted that this could be a memory hog if you are working with a really large file. In that case I'd read the lines in one at a time and write them out to a temp file, then delete the original file and rename the temp at the end.

var tempFile = Path.GetTempFileName();
using (var file = File.OpenWrite(tempFile))
using (var writer = new StreamWriter(file))
{
foreach (var line in File.ReadLines(filepath))
{
if (line.Contains("motd="))
{
writer.WriteLine("motd=" + textBox1.Text);
}
else
{
writer.WriteLine(line);
}
}
}

File.Delete(filepath);
File.Move(tempFile, filepath);

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

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

Searching in text files for a keyword until a string is encountered

Try this:

var searchResults = files.Where(file => File.ReadLines(file.FullName)
.TakeWhile(line => line != "STOP")
.Any(line => line.Contains(keyWord)))
.Select(file => file.FullName);

Fastest way to locate a line which contains a specific word in a large text file

In general, disk IO of this nature is just going to be slow. There is likely little you can do to improve over your current version in terms of performance, at least not without dramatically changing the format in which you store your data, or your hardware.

However, you could shorten the code and simplify it in terms of maintenance and readability:

var lines = File.ReadLines(filename).Where(l => l.Contains("search string"));
foreach(var line in lines)
{
// Do something here with line
}

Reading the entire file into memory causes the application to hang and is very slow, do you think there are any other alternative

If the main goal here is to prevent application hangs, you can do this in the background instead of in a UI thread. If you make your method async, this can become:

while ((line = await reader.ReadLineAsync()) != null)
{
if (line.Contains("search string"))
{
//Do something with line
}
}

This will likely make the total operation take longer, but not block your UI thread while the file access is occurring.

C# text file search for specific word and delete whole line of text that contains that word

The easiest is to rewrite the whole file without the line(s) that contain the word. You can use LINQ for that:

var oldLines = System.IO.File.ReadAllLines(path);
var newLines = oldLines.Where(line => !line.Contains(wordToDelete));
System.IO.File.WriteAllLines(path, newLines);

If you only want to delete all lines that contain the word(not only the sequence of characters), you need to split the line by ' ':

var newLines = oldLines.Select(line => new { 
Line = line,
Words = line.Split(' ')
})
.Where(lineInfo => !lineInfo.Words.Contains(wordToDelete))
.Select(lineInfo => lineInfo.Line);


Related Topics



Leave a reply



Submit