Tuesday 12 June 2012

.Net Beginners , C# Tips : Locate specific lines within the Text file Using LINQ

You can also query the text file using LINQ .
Here are example for this.
In this example we can get specific lines which has matching word given by us.
After the LINQ query is executed you need to close file otherwise it gives error on next attempt to access of file.

C# Example :
string[] lineNumbers = (from line in
                        System.IO.File.ReadLines(MapPath(
                        where line.Contains("sample")
                        select line).ToArray();

System.IO.File.OpenText(MapPath("TextFile.txt")).Close();

VB.net Example :
Dim lineNumbers As String() = (From line In
                              System.IO.File.ReadLines(MapPath("TextFile.txt"))
                              Where line.Contains("sample")
                              Select line).ToArray()

System.IO.File.OpenText(MapPath("TextFile.txt")).Close()

2 comments:

  1. Why don't use Substring with IndexOf to find the text, it's simple. Or can you consider a explicit benefit of using Linq for this task??

    string txtTest = "some text here";
    string txtResult = txtTest.Substring(txtTest.IndexOf("text"));

    Thanks.

    ReplyDelete
    Replies
    1. Hi,
      Thank you for your valuable comment.
      Yes you are right this is also a possible way.
      But I am demonstrate with the use of LINQ.

      Delete