Results 1 to 7 of 7

Thread: [RESOLVED] Fastest way to Search for a file

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2010
    Posts
    272

    Resolved [RESOLVED] Fastest way to Search for a file

    Of course this is just a snippet, but I was using this to search for a filename that I was inputting into a textbox on a windows form. I don't like it because it takes a great deal of time to search for the file, is there a faster way to use C# to search for a filename?
    Code:
    try
    {
    string searchFile = "";
    searchFile = txtbox1.Text;
    if (searchFile != string.Empty)
    {
    using (System.Diagnostics.Process pRun = new System.Diagnostics.Process())
    {
    pRun.StartInfo.FileName = "C:\\" + searchFile + ".doc";
    pRun.StartInfo.UseShellExecute = true;
    pRun.Start();
    }
    }
    catch
    {
    }
    Last edited by Jo15765; Aug 16th, 2013 at 03:45 PM. Reason: Copy/Pasted wrong Code

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: Fastest way to Search for a file

    How is that a file search? The term "file search" suggests that you have the name of a file but not the path and you want to find that path. Is that what you're trying to do?

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2010
    Posts
    272

    Re: Fastest way to Search for a file

    Quote Originally Posted by jmcilhinney View Post
    How is that a file search? The term "file search" suggests that you have the name of a file but not the path and you want to find that path. Is that what you're trying to do?
    Yes, there are .doc files that are stored somewhere in a sub-directory within my C: drive on my PC. I have a text box on a windows form where the user will input the name of the .doc file maybe it's Tuesday.doc so the user will input Tuesday, and the search begins...
    *Note, the end result I am going for (which I have code in place that I found this a.m.) is once the .doc file is found it will then be opened.

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: Fastest way to Search for a file

    There are a couple of methods in the .NET Framework that will find files matching a pattern but their major drawback is that they will fail if they encounter an inaccessible folder. They will continue to search the entire folder structure even if they have found a match, which is probably not what you want, so they will always find an inaccessible folder if you specify C: as the root. As such, you will have to write your own recursive file search. Here's one a whipped up that will terminate at the first match and allows you to specify breadth-first or depth-first and also the maximum depth to search:
    vb.net Code:
    1. Public Enum SearchMode
    2.     BreadthFirst
    3.     DepthFirst
    4. End Enum
    vb.net Code:
    1. ''' <summary>
    2. ''' Finds a file whose name matches a pattern.
    3. ''' </summary>
    4. ''' <param name="path">
    5. ''' The root folder in which to search.
    6. ''' </param>
    7. ''' <param name="searchPattern">
    8. ''' The pattern to match to the file name.
    9. ''' </param>
    10. ''' <returns>
    11. ''' The fully path of the file if one is found; otherwise, a null reference.
    12. ''' </returns>
    13. ''' <remarks>
    14. ''' Performs a breadth-first search.
    15. ''' </remarks>
    16. Public Function FindFile(path As String, searchPattern As String) As String
    17.     Return FindFile(path, searchPattern, SearchMode.BreadthFirst, Nothing)
    18. End Function
    19.  
    20. ''' <summary>
    21. ''' Finds a file whose name matches a pattern.
    22. ''' </summary>
    23. ''' <param name="path">
    24. ''' The root folder in which to search.
    25. ''' </param>
    26. ''' <param name="searchPattern">
    27. ''' The pattern to match to the file name.
    28. ''' </param>
    29. ''' <param name="mode">
    30. ''' A value indicating the type of search to perform: breadth-first or depth first.
    31. ''' </param>
    32. ''' <returns>
    33. ''' The fully path of the file if one is found; otherwise, a null reference.
    34. ''' </returns>
    35. Public Function FindFile(path As String, searchPattern As String, mode As SearchMode) As String
    36.     Return FindFile(path, searchPattern, mode, Nothing)
    37. End Function
    38.  
    39. ''' <summary>
    40. ''' Finds a file whose name matches a pattern.
    41. ''' </summary>
    42. ''' <param name="path">
    43. ''' The root folder in which to search.
    44. ''' </param>
    45. ''' <param name="searchPattern">
    46. ''' The pattern to match to the file name.
    47. ''' </param>
    48. ''' <param name="maxDepth">
    49. ''' The maximum depth of the subfolders to search or a null reference to search all subfolders.
    50. ''' </param>
    51. ''' <returns>
    52. ''' The fully path of the file if one is found; otherwise, a null reference.
    53. ''' </returns>
    54. ''' <remarks>
    55. ''' Performs a breadth-first search.
    56. ''' </remarks>
    57. Public Function FindFile(path As String, searchPattern As String, maxDepth As UInteger?) As String
    58.     Return FindFile(path, searchPattern, SearchMode.BreadthFirst, maxDepth)
    59. End Function
    60.  
    61. ''' <summary>
    62. ''' Finds a file whose name matches a pattern.
    63. ''' </summary>
    64. ''' <param name="path">
    65. ''' The root folder in which to search.
    66. ''' </param>
    67. ''' <param name="searchPattern">
    68. ''' The pattern to match to the file name.
    69. ''' </param>
    70. ''' <param name="mode">
    71. ''' A value indicating the type of search to perform: breadth-first or depth first.
    72. ''' </param>
    73. ''' <param name="maxDepth">
    74. ''' The maximum depth of the subfolders to search or a null reference to search all subfolders.
    75. ''' </param>
    76. ''' <returns>
    77. ''' The fully path of the file if one is found; otherwise, a null reference.
    78. ''' </returns>
    79. Public Function FindFile(path As String, searchPattern As String, mode As SearchMode, maxDepth As UInteger?) As String
    80.     Dim filePath As String = Nothing
    81.  
    82.     Select Case mode
    83.         Case SearchMode.BreadthFirst
    84.             filePath = Directory.GetFiles(path, searchPattern).FirstOrDefault()
    85.  
    86.             If filePath Is Nothing Then
    87.                 filePath = FindFileBreadthFirst(path, searchPattern, maxDepth)
    88.             End If
    89.         Case SearchMode.DepthFirst
    90.             filePath = FindFileDepthFirst(path, searchPattern, maxDepth)
    91.     End Select
    92.  
    93.     Return filePath
    94. End Function
    95.  
    96. ''' <summary>
    97. ''' Finds a file whose name matches a pattern by performing a breadth-first search.
    98. ''' </summary>
    99. ''' <param name="path">
    100. ''' The root folder in which to search.
    101. ''' </param>
    102. ''' <param name="searchPattern">
    103. ''' The pattern to match to the file name.
    104. ''' </param>
    105. ''' <param name="maxDepth">
    106. ''' The maximum depth of the subfolders to search or a null reference to search all subfolders.
    107. ''' </param>
    108. ''' <returns>
    109. ''' The fully path of the file if one is found; otherwise, a null reference.
    110. ''' </returns>
    111. Private Function FindFileBreadthFirst(path As String, searchPattern As String, maxDepth As UInteger?) As String
    112.     Dim filePath As String = Nothing
    113.  
    114.     'Only search subfolders if we have not exceeded the maximum depth.
    115.     If Not maxDepth.HasValue OrElse maxDepth.Value > 0 Then
    116.         Try
    117.             Dim subfolderPaths = Directory.GetDirectories(path)
    118.  
    119.             'Search the top level of each subfolder first.
    120.             For Each subfolderPath In subfolderPaths
    121.                 filePath = Directory.GetFiles(subfolderPath, searchPattern).FirstOrDefault()
    122.  
    123.                 'Stop if a match is found.
    124.                 If filePath IsNot Nothing Then
    125.                     Exit For
    126.                 End If
    127.             Next
    128.  
    129.             'Continue deeper if a match has not been found.
    130.             If filePath Is Nothing Then
    131.                 If maxDepth.HasValue Then
    132.                     'We're going one level deeper.
    133.                     maxDepth -= 1UI
    134.                 End If
    135.  
    136.                 'Search subfolders of each subfolder.
    137.                 For Each subfolderPath In subfolderPaths
    138.                     filePath = FindFileBreadthFirst(subfolderPath,
    139.                                                     searchPattern,
    140.                                                     maxDepth)
    141.  
    142.                     'Stop if a match is found.
    143.                     If filePath IsNot Nothing Then
    144.                         Exit For
    145.                     End If
    146.                 Next
    147.             End If
    148.         Catch ex As UnauthorizedAccessException
    149.             'Ignore an inaccessible folder and continue.
    150.         End Try
    151.     End If
    152.  
    153.     Return filePath
    154. End Function
    155.  
    156. ''' <summary>
    157. ''' Finds a file whose name matches a pattern by performing a depth-first search.
    158. ''' </summary>
    159. ''' <param name="path">
    160. ''' The root folder in which to search.
    161. ''' </param>
    162. ''' <param name="searchPattern">
    163. ''' The pattern to match to the file name.
    164. ''' </param>
    165. ''' <param name="maxDepth">
    166. ''' The maximum depth of the subfolders to search or a null reference to search all subfolders.
    167. ''' </param>
    168. ''' <returns>
    169. ''' The fully path of the file if one is found; otherwise, a null reference.
    170. ''' </returns>
    171. Private Function FindFileDepthFirst(path As String, searchPattern As String, maxDepth As UInteger?) As String
    172.     Dim filePath As String = Nothing
    173.  
    174.     Try
    175.         'Search the current folder first.
    176.         filePath = Directory.GetFiles(path, searchPattern).FirstOrDefault()
    177.  
    178.         'Only search subfolders if we have not exceeded the maximum depth.
    179.         If filePath Is Nothing AndAlso (Not maxDepth.HasValue OrElse maxDepth.Value > 0) Then
    180.             If maxDepth.HasValue Then
    181.                 'We're going one level deeper.
    182.                 maxDepth -= 1UI
    183.             End If
    184.  
    185.             'Search each subfolder.
    186.             For Each subfolderPath In Directory.GetDirectories(path)
    187.                 filePath = FindFileDepthFirst(subfolderPath,
    188.                                               searchPattern,
    189.                                               maxDepth)
    190.  
    191.                 'Stop if a match is found.
    192.                 If filePath IsNot Nothing Then
    193.                     Exit For
    194.                 End If
    195.             Next
    196.         End If
    197.     Catch ex As UnauthorizedAccessException
    198.         'Ignore an inaccessible folder and continue.
    199.     End Try
    200.  
    201.     Return filePath
    202. End Function
    Sample usage:
    vb.net Code:
    1. Dim fileName = TextBox1.Text & ".doc"
    2. Dim filePath = FindFile("C:", fileName)
    3.  
    4. If filePath Is Nothing Then
    5.     Console.WriteLine(fileName & " not found.")
    6. Else
    7.     Process.Start(filePath)
    8. End If

  5. #5
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Fastest way to Search for a file

    You posted VB code
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: Fastest way to Search for a file

    Quote Originally Posted by Niya View Post
    You posted VB code
    Ah b*gger! If I had a $ for every time I've forgotten that I'm in the C# forum I could buy myself a nice purple felt hat.
    csharp Code:
    1. public enum SearchMode
    2. {
    3.     BreadthFirst,
    4.     DepthFirst
    5. }
    csharp Code:
    1. /// <summary>
    2. /// Finds a file whose name matches a pattern.
    3. /// </summary>
    4. /// <param name="path">
    5. /// The root folder in which to search.
    6. /// </param>
    7. /// <param name="searchPattern">
    8. /// The pattern to match to the file name.
    9. /// </param>
    10. /// <returns>
    11. /// The fully path of the file if one is found; otherwise, a null reference.
    12. /// </returns>
    13. /// <remarks>
    14. /// Performs a breadth-first search.
    15. /// </remarks>
    16. public string FindFile(string path, string searchPattern)
    17. {
    18.     return FindFile(path, searchPattern, SearchMode.BreadthFirst, null);
    19. }
    20.  
    21. /// <summary>
    22. /// Finds a file whose name matches a pattern.
    23. /// </summary>
    24. /// <param name="path">
    25. /// The root folder in which to search.
    26. /// </param>
    27. /// <param name="searchPattern">
    28. /// The pattern to match to the file name.
    29. /// </param>
    30. /// <param name="mode">
    31. /// A value indicating the type of search to perform: breadth-first or depth first.
    32. /// </param>
    33. /// <returns>
    34. /// The fully path of the file if one is found; otherwise, a null reference.
    35. /// </returns>
    36. public string FindFile(string path, string searchPattern, SearchMode mode)
    37. {
    38.     return FindFile(path, searchPattern, mode, null);
    39. }
    40.  
    41. /// <summary>
    42. /// Finds a file whose name matches a pattern.
    43. /// </summary>
    44. /// <param name="path">
    45. /// The root folder in which to search.
    46. /// </param>
    47. /// <param name="searchPattern">
    48. /// The pattern to match to the file name.
    49. /// </param>
    50. /// <param name="maxDepth">
    51. /// The maximum depth of the subfolders to search or a null reference to search all subfolders.
    52. /// </param>
    53. /// <returns>
    54. /// The fully path of the file if one is found; otherwise, a null reference.
    55. /// </returns>
    56. /// <remarks>
    57. /// Performs a breadth-first search.
    58. /// </remarks>
    59. public string FindFile(string path, string searchPattern, uint? maxDepth)
    60. {
    61.     return FindFile(path, searchPattern, SearchMode.BreadthFirst, maxDepth);
    62. }
    63.  
    64. /// <summary>
    65. /// Finds a file whose name matches a pattern.
    66. /// </summary>
    67. /// <param name="path">
    68. /// The root folder in which to search.
    69. /// </param>
    70. /// <param name="searchPattern">
    71. /// The pattern to match to the file name.
    72. /// </param>
    73. /// <param name="mode">
    74. /// A value indicating the type of search to perform: breadth-first or depth first.
    75. /// </param>
    76. /// <param name="maxDepth">
    77. /// The maximum depth of the subfolders to search or a null reference to search all subfolders.
    78. /// </param>
    79. /// <returns>
    80. /// The fully path of the file if one is found; otherwise, a null reference.
    81. /// </returns>
    82. public string FindFile(string path, string searchPattern, SearchMode mode, uint? maxDepth)
    83. {
    84.     string filePath = null;
    85.  
    86.     switch (mode)
    87.     {
    88.         case SearchMode.BreadthFirst:
    89.             filePath = Directory.GetFiles(path, searchPattern).FirstOrDefault();
    90.  
    91.             if (filePath == null)
    92.             {
    93.                 filePath = FindFileBreadthFirst(path, searchPattern, maxDepth);
    94.             }
    95.  
    96.             break;
    97.         case SearchMode.DepthFirst:
    98.             filePath = FindFileDepthFirst(path, searchPattern, maxDepth);
    99.  
    100.             break;
    101.         default:
    102.             throw new ArgumentOutOfRangeException("mode");
    103.     }
    104.  
    105.     return filePath;
    106. }
    107.  
    108. /// <summary>
    109. /// Finds a file whose name matches a pattern by performing a breadth-first search.
    110. /// </summary>
    111. /// <param name="path">
    112. /// The root folder in which to search.
    113. /// </param>
    114. /// <param name="searchPattern">
    115. /// The pattern to match to the file name.
    116. /// </param>
    117. /// <param name="maxDepth">
    118. /// The maximum depth of the subfolders to search or a null reference to search all subfolders.
    119. /// </param>
    120. /// <returns>
    121. /// The fully path of the file if one is found; otherwise, a null reference.
    122. /// </returns>
    123. private string FindFileBreadthFirst(string path, string searchPattern, uint? maxDepth)
    124. {
    125.     string filePath = null;
    126.  
    127.     //Only search subfolders if we have not exceeded the maximum depth.
    128.     if (!maxDepth.HasValue || maxDepth.Value > 0)
    129.     {
    130.         try
    131.         {
    132.             var subfolderPaths = Directory.GetDirectories(path);
    133.  
    134.             //Search the top level of each subfolder first.
    135.             foreach (var subfolderPath in subfolderPaths)
    136.             {
    137.                 filePath = Directory.GetFiles(subfolderPath, searchPattern).FirstOrDefault();
    138.  
    139.                 //Stop if a match is found.
    140.                 if (filePath != null)
    141.                 {
    142.                     break;
    143.                 }
    144.             }
    145.  
    146.             //Continue deeper if a match has not been found.
    147.             if (filePath == null)
    148.             {
    149.                 if (maxDepth.HasValue)
    150.                 {
    151.                     //We're going one level deeper.
    152.                     maxDepth -= 1U;
    153.                 }
    154.  
    155.                 //Search subfolders of each subfolder.
    156.                 foreach (var subfolderPath in subfolderPaths)
    157.                 {
    158.                     filePath = FindFileBreadthFirst(subfolderPath, searchPattern, maxDepth);
    159.  
    160.                     //Stop if a match is found.
    161.                     if (filePath != null)
    162.                     {
    163.                         break;
    164.                     }
    165.                 }
    166.             }
    167.         }
    168.         catch (UnauthorizedAccessException)
    169.         {
    170.             //Ignore an inaccessible folder and continue.
    171.         }
    172.     }
    173.  
    174.     return filePath;
    175. }
    176.  
    177. /// <summary>
    178. /// Finds a file whose name matches a pattern by performing a depth-first search.
    179. /// </summary>
    180. /// <param name="path">
    181. /// The root folder in which to search.
    182. /// </param>
    183. /// <param name="searchPattern">
    184. /// The pattern to match to the file name.
    185. /// </param>
    186. /// <param name="maxDepth">
    187. /// The maximum depth of the subfolders to search or a null reference to search all subfolders.
    188. /// </param>
    189. /// <returns>
    190. /// The fully path of the file if one is found; otherwise, a null reference.
    191. /// </returns>
    192. private string FindFileDepthFirst(string path, string searchPattern, uint? maxDepth)
    193. {
    194.     string filePath = null;
    195.  
    196.     try
    197.     {
    198.         //Search the current folder first.
    199.         filePath = Directory.GetFiles(path, searchPattern).FirstOrDefault();
    200.  
    201.         //Only search subfolders if we have not exceeded the maximum depth.
    202.         if (filePath == null && (!maxDepth.HasValue || maxDepth.Value > 0))
    203.         {
    204.             if (maxDepth.HasValue)
    205.             {
    206.                 //We're going one level deeper.
    207.                 maxDepth -= 1U;
    208.             }
    209.  
    210.             //Search each subfolder.
    211.             foreach (var subfolderPath in Directory.GetDirectories(path))
    212.             {
    213.                 filePath = FindFileDepthFirst(subfolderPath, searchPattern, maxDepth);
    214.  
    215.                 //Stop if a match is found.
    216.                 if (filePath != null)
    217.                 {
    218.                     break;
    219.                 }
    220.             }
    221.         }
    222.     }
    223.     catch (UnauthorizedAccessException)
    224.     {
    225.         //Ignore an inaccessible folder and continue.
    226.     }
    227.  
    228.     return filePath;
    229. }
    Sample usage:
    csharp Code:
    1. var fileName = TextBox1.Text + ".doc";
    2. var filePath = FindFile("C:", fileName);
    3.  
    4. if (filePath == null)
    5. {
    6.     Console.WriteLine(fileName + " not found.");
    7. }
    8. else
    9. {
    10.     Process.Start(filePath);
    11. }
    Code conversions courtesy of Instant C# from Tangible Software Solutions.

  7. #7
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: [RESOLVED] Fastest way to Search for a file

    Beautiful example jmcilhinney

    There was a function I was testing once through P/Invoke: FindFirstFileEx. (I'm not suggesting this as a solution though.) There were discussions about enumerating the $MFT that I've seen around as well for file searching purposes.
    <<<------------
    Improving Managed Code Performance | .NET Application Performance
    < Please if this helped you out. Any kind of thanks is gladly appreciated >


    .NET Programming (2012 - 2018)
    ®Crestron - DMC-T Certified Programmer | Software Developer
    <<<------------

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width