Reputation: 13
e.g txt file has following entries say :
england is cold country
India is poor country
england is cold country
england is cold country
India is poor country
english county cricket season.
now i want to search this txt file for a string "england" and return the entire line containing this string. How can i do it using C sharp language ?
Upvotes: 1
Views: 6486
Reputation: 62484
I would consider two approaches, for large file (megabytes) and for relatively small.
If file is large and contains megabytes of data: use stream reader, read file untile EndOfLine, analize just readed string
string pattern = "england";
IList<string> result = new List<string>();
using (var reader = new StreamReader("TestFile.txt"))
{
string currentLine;
while ((currentLine= reader.ReadLine()) != null)
{
if (currentLine.Contains(pattern)
{
// if you do not need multiple lines and just the first one
// just break from the loop (break;)
result.Add(currentLine);
}
}
}
If a file is small you can use helper which returns all file content as array of strings - (File.ReadAllLines()) string per line and then use LINQ to search for substring. if you are using .NET 4
or newer you can leverage new helper (File.ReadLines()) which does not read entire file and does read as deffered operation.
.NET 2.0 - 3.5:
string pattern = "england";
IEnumerable<string> result = File.ReadAllLines()
.Where(l => l.Contains(pattern));
.NET4 - 4.5:
string pattern = "england";
IEnumerable<string> result = File.ReadLines()
.Where(l => l.Contains(pattern));
if you need just the first line use .FirstOrDefault(l => l.Contains(pattern))
instead of Where(l => l.Contains(pattern))
MSDN:
The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.
Upvotes: 2
Reputation: 3046
1) Read All Lines. http://msdn.microsoft.com/en-us/library/system.io.file.readalllines.aspx
2) Create a List of strings to populate matches
3) Loop or linq the lines and look for match using IndexOf(matchstring) > -1
4) Return result
Upvotes: 0
Reputation: 9394
You can do it like. If you want to return all lines with "england" you need to create a list of strings and return this.
foreach(string line in File.ReadAllLines("FILEPATH"))
{
if(line.contains("england"))
return line;
}
return string.empty;
Upvotes: 0