How to use DirectoryInfo.GetFiles and stop it after finding the first match?

You need to find the directory / subdirectories to search for the file, it will prefer to stop it as soon as it finds it.

Is this a function built into the DirectoryInfo.GetFiles directory that I am missing, or do I need to use something else (self-implemented recursive search)?

+4
source share
3 answers

Use DirectoryInfo.EnumerateFiles() , which lazily returns files (unlike GetFiles , which first returns a complete list of files to memory) - you can add FirstOrDefault() to achieve the desired result:

 var firstTextFile = new DirectoryInfo(someDirectory).EnumerateFiles("*.txt") .FirstOrDefault(); 

From MSDN:

The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start listing a collection of FileInfo objects before returning the entire collection; when you use GetFiles, you must wait for the entire array of FileInfo objects to be there before you can access the array. Therefore, when you work with many files and directories, EnumerateFiles can be more efficient.

( DirectoryInfo.EnumerateFiles requires .NET 4.0)

+12
source

Best way to use for pre-.NET 4.0, use FindFirstFile ()

  [DllImport("kernel32", CharSet = CharSet.Unicode)] public static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool FindClose(IntPtr hFindFile); public void findFile() { WIN32_FIND_DATA findData; var findHandle = FindFirstFile(@"\\?\" + directory + @"\*", out findData); FindClose(findHandle); } 

This structure is required

  //Struct layout required for FindFirstFile [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] struct WIN32_FIND_DATA { public uint dwFileAttributes; public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime; public uint nFileSizeHigh; public uint nFileSizeLow; public uint dwReserved0; public uint dwReserved1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName; } 
+4
source

Have you tried DirectoryInfo.GetFiles ([your template], SearchOption.AllDirectories) .First ();

0
source

Source: https://habr.com/ru/post/1394498/


All Articles