Learn C# Part 5: Mini project - File Search.

Ahteshamax
Posted by in C# category on for Beginner level | Points: 250 | Views : 593 red flag

In this article we will do a directory and file search project based on user request.
Recommendation
Read Learn C# Part 4b: Delegates, Multicast Delegates and Events. before this article.

Below are the links for other articles of Learn C# Step by Step :-

Learn C# Step By Step :- Part 1.

Learn C# Step By Step: - Part 2

Learn C# Step By Step (Concept of Class and Object): - Part 3

Learn C# Part 4: Synchronous and Asynchronous methodology.

Learn C# Part 4b: Delegates, Multicast Delegates and Events.

Learn C# Part 6: Delegates - Lambda Expression, Expression Tree, Func<>, Action<> and Predicate<>

On the basis of past lab 4 and 4b which we have learned till now in this lab we will be doing a small project which will do a directory and file search based on user request. We will create a console application which will do the directory or the file search based on the user input request given and if user searches for directory and search records is directory under directory i.e. subdirectory then that also application will search out and display its name.

Below is the requirement which should be fulfilled to execute the application: -

  1. Provision to enter directory name by user in the application so that it can be searched.
  2. Application will show all files within the directory and will also display subdirectories if any present within.
  3. For better usability operation performed by the application should be asynchronous i.e. threading implementation.

So before proceeding with the project very essential thing is how to learn read directory and files using the C# program. Having knowledge will help you to build the application easily.

While creating an application in Visual Studio the basic and very important use is of System.IO namespace it has to be mandatorily imported into the program with which creating, reading of files and directories or folder can be done.

Do not worry we will demonstrate in this article reading of directories and sub-directories if any present within the user’s directory name search.

For that start a new console application project using the C# language as we did in our previously to this article. Click on New Project which will open New Project window screen. In this screen click on Visual C# Windows and on the center click in Console Application. Give a suitable name to the project and provide location to save the project. Here we have used default name and default location to create and save the project respectively.

Next is create a new project and empty project screen with name “Program.cs” will open in front with default namespaces loaded required to create a project.

So now under “Program.cs” first import namespace with the following code line

using System.IO

Followed by a code of line in which application will take input from the user to search directory name within the system. So as soon as application is started. A writeline will prompt user with this text “Enter Directory Name”

Console.WriteLIne(“Enter Directory Name”);

With the help of following line application will wait for user to enter input.

stringstrdir = Console.ReadLine();

Now in order to make the coding usable always follow best practice of creating (class library).dll where the business logic is written and it separated from the client. So in case tomorrow if we want to change our client from console application to windows application then that can be done and achieved easily.

In order to add class library do right click on the Solution and click on add new project follow the same steps which we did to create Console Application project. Here only thing is to select Class Library give a suitable name to the project and select the location to save the class library project. Here we have used “FileSearch” name and default location to save project.

Once class library project is created with name “FileSearch” just click on “Class1.cs” and empty screen will open with basic coding on it. Do follow below steps to write the logic code to search directory (folder) and file.

  1. Importnamespace of input-output(IO) from system
    using System.IO;
  2. Give a name to the class as File which lies under the namespace FileSearch.
  3. Declare a method name as “Search”which is “void” and pass directory name as “dirName” with variable as string use below syntax to code. It will accept directory name from the user.
    public void  Search(string dirName)
  4. Under the same “Search” method write foreach loop code which will get the directory name within the directory i.e. subdirectories. It will get the subdirectories name found under directory search done by user within string “dir”. Below is the code line for it.
    foreach (string dir in Directory.GetDirectories(dirName))
  5. Next line of the code is which will get the file name within the user’s search directory. Again it will be a foreach loop
    foreach (string str in Directory.GetFiles(dir))
  6. Next is declare a public delegate named “DisplayFileName” which is “void” and access modifier is set to be public This delegate will pass the parameter string file within.
    public delegate void DisplayFileName(string file);
  7. Make the delegate as event by writing syntax event with pointer name “sendFileName” which will be exposed out of FileSearch project so that subscriber client(console application) can only display.
    public event DisplayFileNamesendFileName;
  8. Now under foreach loop scope of GetFileswrite code which will get all file namesand get it stored under “str” and then pass it as parameter in pointer “sendFileName”
    sendfileName(str);
  9. Import namespace of Threading from system to use threading into class library
    usingSystem.Threading;
  10. Once the output is displayed it should not just go away without being noticed by user. Make it available output for atleast 1000 ms(1 sec) on console prompt.
    Thread.Sleep(1000);
  11. Program should not exit in order to avoid that make a recursive call of the “Search”method again and again till user’s requested directory is found.
    Search(dir);

Now go to Solution and under ConsoleApplication do a right click on “Reference” and click “Add Reference” which will open Reference Manager screen on the left side do a click on Solution and under it do check box on “FileSearch” and click on OK.

Now go on “Program.cs” of Console Application and on that do the following: -

  1. Import namespace “FileSearch” which is a class library so that its class and methods can be used.
    usingFileSearch;
  2. Create an object called “fileobj”of the class “File” under namespace “FileSearch” with the following code
    FileSearch.Filefileobj = new FileSearch.File();

    Here we have to mentioned namespace also along with class name because it is getting conflict with already existing System.File

  3. Create a static function with void called “sendFileName” and in that pass parameter which is same as signature of delegate “string file” and in that
  4. write a display line which will display all the file which will be given by publisher.
    private static void sendFileName(string file)
    {
    Console.WriteLine(file);
    }
    
  5. Import namespace of Threading which is part of System in order to make our program asynchrounous
    usingSystem.Threading;
  6. Write a multicast delegate code line which get subscribed to “FileSearch” as subscriber in order to broadcast message and display file name on the console application
    fileobj.sendFileName += sendFileName;
  7. Create object of the thread using lambda expression which is denoted by ‘=>’ to make program running asynchronous along with the input search given by the user.
    Thread thread = new Thread(() =>fileobj.Search(strdir));
  8. Invoke thread by writing the following code
    Thread.Start();
  9. In order to show the input on the console screen given by the user write below code of read
    Console.Read();

Now build the entire solution in order to see if any error is present. Once found Build is successful then press “ctrl+F5” on the keyboard to run the application.

Once the console screen is open give input on keyboard – “d:\k”

It will start displaying the output from ‘d’ drive and all files present under ‘k’ directory or folder. If you see following image screen it shows all files along with files present within subdirectory or subfolder also.

With above result displaying from user input of directory or folder our project of folder search is successful.

As we did this project using console application as client it can also be done by changing client i.e. in windows application and using the same class library. On windows application user enter directory name which needs to be searched in textbox and display the result in grid or list box.

File Search application using Windows Application

In order to get better user experience in the form of visual like text box, buttons we will recreate same project windows application.

Under Visual Studio of existing project go to Solution Explorer and do right click and add new project by clicking Add New Project. New window will open, on this window select Visual C# > Windows > Windows Form Application. After type of project is selected give suitable name to it, here name to project given is “FileSearchWindows” and then click on OK.

After adding windows project along with its other associated project file it will be seen under Solution Explorer as shown in the screen down below.

Now do the following on the “FileSearchWindows”.

  1. Double click on “Form1.cs” which will open its designer mode and on that you will see winform. On that drag and drop components from Toolbox.
  2. If you do not see Toolbox on the screen then click on View option available on the Menu and then click on Toolbox.
  3. Drag “Button” from the Toolbox and drop it on Form1.cs. Using this button user will submit his directory request into the application.
  4. Drag “Listbox” from the Toolbox and drop it on Form1.cs. It will display all the result from requested user including files and subdirectory.
  5. Drag “Textbox” from the Toolbox and drop it on Form1.cs. User will enter name of the directory in textbox which user will search using “FileSearchWindows”.

Please Note: As per requirement size of the winform it can be adjusted with the help of mouse.

Next is go to each properties of component and change its name for ease of understanding while coding. Starting first with button component do a right click on the button and open properties go to the “Text” field and change button default text name to “Search Now” so that application becomes user friendly and getseasily understood by user.

Secondly change the default name of button from “button1” which will appear while coding to “btnSearch” for simplifying the understanding of the code.

Similarly change the name of other components including the form on which components are placed for easily identifying them.

Starting from Textbox change its name from “textbox1” to “txtDir” as this textbox will be used to enter directory name which is wished by the user to search by application.

Followed by Listbox change its name from “listbox1” to “listFiles” this listbox will be used to display in list form all of the found files and subdirectories.

And at last change the name of the main winform on which textbox, buttons and listbox is placed. Current name is “Form1” to “File Search”

We have changed default properties details and text name by customized it according to our file search application in order to make our application more user friendly.

It is the time to consume the logic of class library “FileSearch” in new client i.e. made already created .dll file reusabledue to which our pain of doing rework reduced and then write code in button code event of windows application “FileSearchWindows”.

In order to consume class library in client just do a right click on “FileSearchWindows”and click on Add > Reference and then Reference Manager window will open select “Solution” on the left and at the center select “FileSearch” followed by clicking OK. And then you will find that reference of class library is nowgot added to windows application client.

After reference is successfully added now go and double click on the button which will open Form1.cs where we can do coding on button event in order develop our file search project.

Once the code behind screen is open do the following step shown coding on it: -

  1. Create object “fileobj” of the class “File” which belongs to namespace “FileSearch” of class library “FileSearch”
    FileSearch.Filefileobj = new FileSearch.File();
  2. Subscribe to an event present in class library which gives output & display it on “sendFileName” function in our windows client. As this client is subscribed to event then there will be only one way communication which means output given from class library(.dll) can only be displayed on windows application.
    fileobj.sendFileName += sendFileName;
  3. Import namespace of Threading so that we can use threading to make our windows application asynchronous.
    usingSystem.Threading;
  4. Create an object with name “thread” of thread with lamba expression(=>) which take input from user in textbox and we have named that textbox as “txtDir.Text”.
    Thread thread = new Thread(() =>fileobj.Search(txtDir.Text));
  5. Once the user has given input in textbox then thread should invoke with following line.
    thread.Start();
  6. Create a method with name “sendFileName” which is with datatype “string” for output received in variable “file” and passesas “string file” in parameter and will display the output of windows application on listbox. Below is the code for the same: -
    private void sendFileName(string file)
            {
    listFiles.Items.Add(file);
            }
    

Once you finish coding in code behind of “Form1.cs” next step is to make this Windows application as startup project so that when you click on ctrl+F5 windows application will start. For that do a right click on “FileSearchWindows” and click on “Set as StartUp Project” as shown in the image down below: -

After the project is set as startup project you will find all the characters now have turned in bold letters.

Very curious to see output on our new client windows application – winform. For that press “ctrl+F5” on the keyboard. You will see our very first windows screen in front which will run our windows application.

On textbox enter the directory name which you want to search.Writing convention should be with drive name “d: location” followed by the path directory name “k” so the text will look “d:\k”and then click on the button “Search Now” and below to that on listbox you will see output of “k” directory with subdirectories and all files related to “k” directory and folder.

Finally we had now got a breakthrough from traditional black console screen and happy to display output on our very first windows application.

Below is the nice video explaining start-up topic for learning C# programming to complete fresher in IT field: -

Page copy protected against web site content infringement by Copyscape

About the Author

Ahteshamax
Full Name: Ahtesham Shaikh
Member Level:
Member Status: Member
Member Since: 10/3/2016 2:36:04 AM
Country: India
Ahtesham Shaikh
http://www.learnmsbitutorials.net/
Hey Friends, Myself Ahtesham a coder, writer & technical supporter for IT world and for my company Questpond. Having 10+ years of experience in microsoft technologies like WCF, WPF, MVC, Sharepoint, AngularJS, MSBI, Excel 2000 - 2013, Powerpoint, C#, SQL Server and so on. I just find myself happy and satisfy by doing this job. Apart from profession love reading novels and other digital network books. I'm a faculty at Questpond and do take trainings on c#, object oriented programming, msbi, sharepoint, mvc, mvc, angularJS and so on. Feel free get in touch me for one-to-one trainings, offline trainings @Andheri Mumbai, Online training via microsoft live meeting.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)