Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C# FindFile FindFirstFile FindNextFile IEnumerable
/// <summary>
/// var ff = new FindFile(); ff.Path = @"c:\"; (var _fd in ff) {var filepath = _fd.cFileName;}
/// </summary>
public class FindFile : IEnumerable<WIN32_FIND_DATA>
{
public string Path { get; set; }
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(Path);
}
IEnumerator<WIN32_FIND_DATA> IEnumerable<WIN32_FIND_DATA>.GetEnumerator()
{
return new Enumerator(Path);
}
[Serializable]
public struct Enumerator : IEnumerator<WIN32_FIND_DATA>
{
private WIN32_FIND_DATA _finddata;
private readonly string _path;
private Win32Api.SafeFindHandle _handle;
public WIN32_FIND_DATA Current { get; private set; }
object IEnumerator.Current
{
get { return Current; }
}
internal Enumerator(string path)
{
_path = path;
_finddata = default(WIN32_FIND_DATA);
Current = default(WIN32_FIND_DATA);
_handle = null;
}
public void Dispose()
{
}
public bool MoveNext()
{
if (_handle == null)
{
_handle = Win32Api.FindFirstFile(_path + @"\*", out _finddata);
if (_handle.IsInvalid)
return false;
Current = _finddata;
return true;
}
if (!Win32Api.FindNextFile(_handle, out _finddata))
return false;
Current = _finddata;
return true;
}
void IEnumerator.Reset()
{
Current = default(WIN32_FIND_DATA);
_handle = null;
_finddata = default(WIN32_FIND_DATA);
}
}
}
[Serializable]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
[BestFitMapping(false)]
public struct WIN32_FIND_DATA
{
public FileAttributes dwFileAttributes;
public FILETIME ftCreationTime;
public FILETIME ftLastAccessTime;
public 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 cAlternate;
}
[SecurityCritical]
public class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid
{
[SecurityCritical]
internal SafeFindHandle()
: base(true)
{
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FindClose(IntPtr hFindFile);
[SecurityCritical]
protected override bool ReleaseHandle()
{
return FindClose(handle);
}
}
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
public static extern SafeFindHandle FindFirstFile(
string lpFileName,
out WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool FindNextFile(
SafeFindHandle hFindFile,
out WIN32_FIND_DATA lpFindFileData);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment