Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

FindFirstFile (kernel32)
 
.
Summary
Summary

C# Signature:

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern IntPtr FindFirstFileEx(
        string lpFileName,
        FINDEX_INFO_LEVELS fInfoLevelId,
        out WIN32_FIND_DATA lpFindFileData,
        FINDEX_SEARCH_OPS fSearchOp,
        IntPtr lpSearchFilter,
        int dwAdditionalFlags);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);

VB.NET Signature:

    <DllImport("kernel32.dll", CharSet:=CharSet.Auto)> _
    Private Function FindFirstFileEx(ByVal lpFileName As String, ByVal fInfoLevelId As FINDEX_INFO_LEVELS, ByRef lpFindFileData As WIN32_FIND_DATA, ByVal fSearchOp As FINDEX_SEARCH_OPS, lpSearchFilter As Int32, dwAdditionalFlags As Integer) As Int32
    End Function
<DllImport("kernel32.dll", CharSet := CharSet.Auto)> _
Private Shared Function FindFirstFile(ByVal lpFileName As String, ByRef lpFindFileData As WIN32_FIND_DATA) As IntPtr
End Function

OBS
The correct VB signature is:

   <DllImport("kernel32.dll", CharSet:=CharSet.Unicode)> _
    Public Shared Function FindFirstFileExW(ByVal lpFileName As String, ByVal fInfoLevelId As FINDEX_INFO_LEVELS, ByRef lpFindFileData As WIN32_FIND_DATAW, ByVal fSearchOp As FINDEX_SEARCH_OPS, lpSearchFilter As IntPtr, dwAdditionalFlags As Integer) As IntPtr
    End Function

Those 'int32's are IntPtr - and using an Int32 instead will fail on a 64-bit platform.

Jens

User-Defined Types:

FINDEX_INFO_LEVELS

FINDEX_SEARCH_OPS

WIN32_FIND_DATA

// dwAdditionalFlags:
public const int FIND_FIRST_EX_CASE_SENSITIVE= 1;
public const int FIND_FIRST_EX_LARGE_FETCH = 2;

Notes:

None.

The managed API only gives access to files/directories limited to 260 chars in length. This is a major flaw in the managed APIs, which every other administrator of a file server out there should agree on. This is the common scenario:

1. Create a folder like E:\CompanyData\Management on the server.

2. Share this as Management

3. The user mount this from his client PC to a drive letter like F:

4. The user creates directories and files below this F:. The user then has acess to a new 260 char length.

5. If the user creates a file with a name of e.g. 250 chars or with a combined length of subdirectorie names and file names of up to 260, these files will not be visible in Windows Explorer on the fileserver AND NOT be visible to the FileInfo DirectoryInfo, as well. in fact those API's blows up with an exception when encountering this situation.

Tips & Tricks:

Please add some!

Use CharSet=CharSet.Unicode, and prepend your filename to search for with "\\?\". This gives go access to filenames up to 32767 bytes in length.

Use "\\?\UNC\" prefix for fileshares.

Sample Code:

    WIN32_FIND_DATA findData;
    FINDEX_INFO_LEVELS findInfoLevel = FINDEX_INFO_LEVELS.FindExInfoStandard;
    int additionalFlags = 0;
    if (Environment.OSVersion.Version.Major >= 6)
    {
    findInfoLevel = FINDEX_INFO_LEVELS.FindExInfoBasic;
    additionalFlags = FIND_FIRST_EX_LARGE_FETCH;
    }

    IntPtr hFile = FindFirstFileEx(
    pattern,
    findInfoLevel,
    out findData,
    FINDEX_SEARCH_OPS.FindExSearchNameMatch,
    IntPtr.Zero,
    additionalFlags);
    int error = Marshal.GetLastWin32Error();
    public const int MAX_PATH = 260;
     public const int MAX_ALTERNATE = 14;

    if (hFile.ToInt32() != -1)
    {
    do
    {
        if ((findData.dwFileAttributes & FileAttributes.Directory) != FileAttributes.Directory)
        {
        Console.WriteLine("Found file {0}", findData.cFileName);
        }
    }
    while (FindNextFile(hFile, out findData));
    [StructLayout(LayoutKind.Sequential)]
        public struct FILETIME {
        public uint dwLowDateTime;
        public uint dwHighDateTime;
     };

    FindClose(hFile);
    }
    [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
    public struct WIN32_FIND_DATA {
        public FileAttributes dwFileAttributes;
        public FILETIME ftCreationTime;
        public FILETIME ftLastAccessTime;
        public FILETIME ftLastWriteTime;
        public uint nFileSizeHigh; //changed all to uint, otherwise you run into unexpected overflow
        public uint nFileSizeLow;  //|
        public uint dwReserved0;   //|
        public uint dwReserved1;   //v
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAX_PATH)]
        public string cFileName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAX_ALTERNATE)]
        public string cAlternate;
    }

Alternative Managed API:

The FileInfo() class provides managed access to this information. As with all .NET file handling (as of framework 4) it is constrained in terms of the length of filename allowed.

    [DllImport("kernel32", CharSet=CharSet.Unicode)]
    public static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);

Documentation

    [DllImport("kernel32", CharSet=CharSet.Unicode)]
    public static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATA lpFindFileData);

    private long RecurseDirectory(string directory, int level, out int files, out int folders) {
        IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
        long size = 0;
        files = 0;
        folders = 0;
        Kernel32.WIN32_FIND_DATA findData;

        IntPtr findHandle;

        // please note that the following line won't work if you try this on a network folder, like \\Machine\C$
        // simply remove the \\?\ part in this case or use \\?\UNC\ prefix
        findHandle = Kernel32.FindFirstFile(@"\\?\" + directory + @"\*", out findData);
        if (findHandle != INVALID_HANDLE_VALUE) {

            do {
                if ((findData.dwFileAttributes & FileAttributes.Directory) != 0) {

                    if (findData.cFileName != "." && findData.cFileName != "..") {
                        folders++;

                        int subfiles, subfolders;
                        string subdirectory = directory + (directory.EndsWith(@"\") ? "" : @"\") +
                            findData.cFileName;
                        if (level != 0)  // allows -1 to do complete search.
                            {
                        size += RecurseDirectory(subdirectory, level - 1, out subfiles, out subfolders);

                        folders += subfolders;
                        files += subfiles;
                        }
                    }
                }
                else {
                    // File
                    files++;

                    size += (long)findData.nFileSizeLow + (long)findData.nFileSizeHigh * 4294967296;
                }
            }
            while (Kernel32.FindNextFile(findHandle, out findData));
            Kernel32.FindClose(findHandle);

        }

        return size;
    }

    // [Sample by Kåre Smith] // [Minor edits by Mike Liddell] //[More minor edits Rob Toftness]

Sample Code:

This sample uses a custom SafeHandle to manage the Find Handle.

     [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
     static extern SafeFindHandle FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);

     [DllImport("kernel32.dll", SetLastError = true)]
     static extern bool FindClose(SafeHandle hFindFile);

     [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
     static extern bool FindNextFile(SafeHandle hFindFile, out WIN32_FIND_DATA lpFindFileData);

     internal sealed class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid
     {
        // Methods
        [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
        internal SafeFindHandle()
        : base(true)
        {
        }

        public SafeFindHandle(IntPtr preExistingHandle, bool ownsHandle) : base(ownsHandle)
        {
        base.SetHandle(preExistingHandle);
        }

        protected override bool ReleaseHandle()
        {
        if (!(IsInvalid || IsClosed))
        {
            return FindClose(this);
        }
        return (IsInvalid || IsClosed);
        }

        protected override void Dispose(bool disposing)
        {
        if (!(IsInvalid || IsClosed))
        {
            FindClose(this);
        }
        base.Dispose(disposing);
        }
     }

    private long RecurseDirectory(string directory, int level, out int files, out int folders) {
        IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
        long size = 0;
        files = 0;
        folders = 0;
        Kernel32.WIN32_FIND_DATA findData;

        // please note that the following line won't work if you try this on a network folder, like \\Machine\C$
        // simply remove the \\?\ part in this case or use \\?\UNC\ prefix
        using(SafeFindHandle findHandle = Kernel32.FindFirstFile(@"\\?\" + directory + @"\*", out findData))
           {
            if (!findHandle.IsInvalid) {

            do {
                if ((findData.dwFileAttributes & FileAttributes.Directory) != 0) {

                    if (findData.cFileName != "." && findData.cFileName != "..") {
                        folders++;

                        int subfiles, subfolders;
                        string subdirectory = directory + (directory.EndsWith(@"\") ? "" : @"\") +
                            findData.cFileName;
                        if (level != 0)  // allows -1 to do complete search.
                            {
                        size += RecurseDirectory(subdirectory, level - 1, out subfiles, out subfolders);

                        folders += subfolders;
                        files += subfiles;
                        }
                    }
                }
                else {
                    // File
                    files++;

                    size += (long)findData.nFileSizeLow + (long)findData.nFileSizeHigh * 4294967296;
                }
            }
            while (Kernel32.FindNextFile(findHandle, out findData));
            }

        }

        return size;
    }

Sample Code:

This sample shows the proper class definition and required using statements for Kernel32 as used in the other samples.

  using System.Runtime.InteropServices;
  using System.Security.Permissions;
  using Microsoft.Win32.SafeHandles;

  public class Kernel32
  {
    public const int MAX_PATH = 260;
    public const int MAX_ALTERNATE = 14;

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct WIN32_FIND_DATA
    {
      public FileAttributes dwFileAttributes;
      public FILETIME ftCreationTime;
      public FILETIME ftLastAccessTime;
      public FILETIME ftLastWriteTime;
      public uint nFileSizeHigh; //changed all to uint from int, otherwise you run into unexpected overflow
      public uint nFileSizeLow;  //| http://www.pinvoke.net/default.aspx/Structures/WIN32_FIND_DATA.html
      public uint dwReserved0;   //|
      public uint dwReserved1;   //v
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
      public string cFileName;
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_ALTERNATE)]
      public string cAlternate;
    }

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern SafeFindHandle FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool FindClose(SafeHandle hFindFile);

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern bool FindNextFile(SafeHandle hFindFile, out WIN32_FIND_DATA lpFindFileData);

    public sealed class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
      // Methods
      [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
      private SafeFindHandle() : base(true)
      {
      }

      private SafeFindHandle(IntPtr preExistingHandle, bool ownsHandle) : base(ownsHandle)
      {
        base.SetHandle(preExistingHandle);
      }

      protected override bool ReleaseHandle()
      {
        if (!(IsInvalid || IsClosed))
        {
          return FindClose(this);
        }
        return (IsInvalid || IsClosed);
      }

      protected override void Dispose(bool disposing)
      {
        if (!(IsInvalid || IsClosed))
        {
          FindClose(this);
        }
        base.Dispose(disposing);
      }
    }
  }

Sample Code:

This builds on Kåre Smith's example to recursively delete a directory.

    public const int MAX_PATH = 260;
    public const int MAX_ALTERNATE = 14;

    [StructLayout(LayoutKind.Sequential)]
    public struct FILETIME
    {
        public uint dwLowDateTime;
        public uint dwHighDateTime;
    };
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct WIN32_FIND_DATA
    {
        public FileAttributes dwFileAttributes;
        public FILETIME ftCreationTime;
        public FILETIME ftLastAccessTime;
        public FILETIME ftLastWriteTime;
        public uint nFileSizeHigh; //changed all to uint, otherwise you run into unexpected overflow
        public uint nFileSizeLow;  //|
        public uint dwReserved0;   //|
        public uint dwReserved1;   //v
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
        public string cFileName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_ALTERNATE)]
        public string cAlternate;
    }
    [DllImport("kernel32", CharSet = CharSet.Unicode)]
    public static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);

    [DllImport("kernel32", CharSet = CharSet.Unicode)]
    public static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATA lpFindFileData);

    [DllImport("kernel32.dll")]
    public static extern bool FindClose(IntPtr hFindFile);

    [DllImport("kernel32.dll", EntryPoint = "DeleteFileW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true,
     CallingConvention = CallingConvention.StdCall)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool DeleteFile(string lpFileName);

    [DllImport("kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool RemoveDirectory(string lpPathName);

    private static bool RecursivelyDeleteDirectory(string directoryPath)
    {
        bool isDeleted = false;
        bool isFailed = false;
        IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);

        WIN32_FIND_DATA findData;
        char[] backslash = new char[]{'\\'};
        IntPtr findHandle;
        string path = string.Empty;

        findHandle = FindFirstFile(directoryPath.TrimEnd(backslash) + @"\*", out findData);
        if (findHandle != INVALID_HANDLE_VALUE)
        {

             do
             {
                  path = string.Format("{0}\\{1}", directoryPath.TrimEnd(backslash), findData.cFileName);

                  if ((findData.dwFileAttributes & FileAttributes.Directory) != 0)
                  {
                      // this is a directory
                      if (findData.cFileName != "." && findData.cFileName != "..")
                      {

                          if (!RecursivelyDeleteDirectory(path))
                          {
                          // we failed to delete a directory
                          isFailed = true;
                          break;
                          }
                      }
                  }
                  else
                  {
                      // delete this file
                      if (!DeleteFile(path))
                      {
                       isFailed = true;
                       break;
                      }
                  }
             }
             while (FindNextFile(findHandle, out findData));

             FindClose(findHandle);

             if (!isFailed)
             {
                 // the directory should be empty now, delete directory
                 isDeleted = RemoveDirectory(directoryPath);

             }

        }

        return isDeleted;
    }
    // [Sample by Chris Drake]

Alternative Managed API:

System.IO.Directory:

GetDirectories
GetFiles
GetFileSystemEntries

Documentation

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Edit This Page
Find References
Show Printable Version
Revisions