Get the latest news, exclusives, sport, celebrities, showbiz, politics, business and lifestyle from The VeryTime,Stay informed and read the latest news today from The VeryTime, the definitive source.

How to Search for a File in C#

10
    • 1). Create a new Windows Console application in Visual C#. Name it whatever you like, such as "FileSearchApp." You should be presented with a C# file named "Program.cs." If not, locate it in the Solution Explorer to the right and double-click it.

    • 2). Inside the Main method in the Program.cs file, add the following lines:

      string fileNameToFind = "*.txt";

      string directoryToSearch = @"C:\Path\To\Folder\To\Search\In";

      string[] files = Directory.GetFileSystemEntries(directoryToSearch, fileNameToFind, SearchOption.TopDirectoryOnly);

      foreach (string f in files)

      {

      Console.WriteLine("File: " + f);

      }

      Console.WriteLine("Total of " + files.Length + " files found.");

      Console.ReadKey();

      This searches for all files with a filename ending in "*txt" in the specified folder; you will need to change the folder to suit your system. Note that the returned string array contains the full paths to each of the individual files.

    • 3). To search for the given files in all subdirectories as well as the specified directory, change the line

      string[] files = Directory.GetFileSystemEntries(directoryToSearch, fileNameToFind, SearchOption.TopDirectoryOnly);

      to

      string[] files = Directory.GetFileSystemEntries(directoryToSearch, fileNameToFind, SearchOption.AllDirectories);

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.