Hi all,

I'm trying to get the list of files in a directory using WINAPI functions FindFirstFile and FindNextFile.
The problem is that WIN32_FIND_DATA.cFileName returns only the first character of the file name.
This is a console application created in Microsoft Visual C# 2008 Express Edition.
Here is the code. Do you have any ideas what is wrong?


using System;
using System.IO;
using System.Runtime.InteropServices;

namespace DirectoryWINAPI
    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;

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

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

        [DllImport("kernel32", CharSet = CharSet.Auto)]
        public static extern bool FindClose(IntPtr hFindFile);

        static void Main(string[] args)
            StreamWriter sw = new StreamWriter("dir.txt", false);
            string dir = Path.GetFullPath(System.IO.Directory.GetCurrentDirectory());
            WIN32_FIND_DATA wfd = new WIN32_FIND_DATA();
            IntPtr h = FindFirstFile((dir + @"\*.*"), out wfd);
            while (FindNextFile(h, out wfd))

Hi Momerath,

The reason for this is that if I add FileInfo.Length and a recursive parsing of subdirectories on top of it, it executes much slower than a similar app I have done in Delphi using WINAPI, especialy if there are a lot of files and subdirectories.
Any suggestions, please?


The problem is solved by adding:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]


struct WIN32_FIND_DATA


This question has already been answered. Start a new discussion instead.