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

C# Signature:

[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 Shared Function FindFirstFile(ByVal lpFileName As String, ByRef lpFindFileData As WIN32_FIND_DATA) As IntPtr
End Function

User-Defined Types:

WIN32_FIND_DATA

Notes:

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:

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:

    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);

    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);
      }
    }
  }

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
Find References
Show Printable Version
Revisions