.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Sandeep Singh
Melody Anderson
Eminent IT

Home >> Articles >> LINQ >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Simple File Search Using LINQ

Posted By:Sajid P K       Posted Date: October 11, 2010    Points: 50    Category: LINQ    URL: http://www.dotnetspark.com  

We all know that LINQ is standard way to querying different Data source such as Memory Collection, Relational Database, XM L etc. Here I going to show you, how to use LINQ to find out /Search files in a Directory depending on a filtering condition.


1) Visual Studio 2008
2) .Net Framework 3.5

Simple Search Application:

Please have look at to below screen. it is the look and feel of the application.

You can click on . button and select a folder where you want to search files. After that give any filter in filter textbox.
Then click search button.If filter is blank it will list all files in grid


System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(txtFolderPath.Text);

var Result = from file in dir.GetFiles()
where file.Name.Contains(txtFilter.Text )
orderby file.Extension
select new { file.Name, file.Extension, file.Length, file.FullName };

dataGridView1.DataSource = Result.ToList();

You can see that here data source is the dir.GetFiles() . It will get all files in given diretory.

You can also achieve same thing using Lamda Expresion. Code for that is given below

var Result = dir.GetFiles()
.Where(x => x.Name.ToLower().Contains(txtFilter.Text))
.OrderBy(x => x.Extension)
.Select(x => new { x.Name, x.Extension, x.Length, x.FullName });

dataGridView1.DataSource = Result.ToList();

Home work

Task 1: Now this will search only in current Directory. Extend this to search all inner directories as well.

Task 2: While clicking on any search result. That file should open up in underlined application.
I.e. if I clicked on "txt" file it should open in the notepad, "doc" -- > Ms Word & ".CS" --> VS etc.

Task 3: Give a try to port same applcation to Vb.net

If done with this task, Attaches the solution in Responses section of this article.
So it can be useful for others

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend