Type a page name and press Enter. You'll jump to the page if it exists, or you can create it if it doesn't.
To create a page in a module other than kernel32, prefix the name with the module name and a period.
FindFirstFile (kernel32)
.
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
<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.
// 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 FileInfoDirectoryInfo, 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.
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);
[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);
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);
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)
{
}
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);
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);
An IntPtr is a pointer to a memory location (unmanaged) that adapts to the platform it is running on (64-bit, etc.) UNLIKE a standard int/Integer. You should always use this type for unmanaged calls that require it, even though an int will appear to work on your development machine.
1/13/2008 4:00:13 AM - Damon Carr-72.43.165.29
Defines values that are used with the FindFirstFileEx function to specify the information level of the returned data.
12/8/2019 11:57:18 AM - -71.90.183.45
Defines values that are used with the FindFirstFileEx function to specify the type of filtering to perform.
12/8/2019 11:55:21 AM - -71.90.183.45
Contains information about the file that is found by the FindFirstFile, FindFirstFileEx, or FindNextFile function.
11/10/2021 10:35:50 AM - -62.91.108.152
TODO - a short description
3/16/2007 8:11:30 AM - -61.11.98.124
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).