简体   繁体   中英

c# call Win32 API for long file paths?

我将如何为长文件路径调用Win32 API,我唯一要做的就是获取该目录中所有文件的列表(递归)

If you want to use Win32 calls you will first have to use DllImport to import the kernel, the syntax is like something like this and you must do this for every method you want to use(this is all un-tested pseudo-code that only describes the concept), the code example converts your paths to UNC paths so you can have long file paths:

    using Microsoft.Win32.SafeHandles;
    ...
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
            static extern SafeHandleMinusOneIsInvalid FindFirstFileW(string lpFileName, IntPtr lpFindFileData);

    ...

            public String FindFirstFile(string filepath)
            {
                // If file path is disk file path then prepend it with \\?\
                // if file path is UNC prepend it with \\?\UNC\ and remove \\ prefix in unc path.
                if (filepath.StartsWith(@"\\"))
                    filepath = @"\\?\UNC\" + filepath.Substring(2, filepath.Length - 2);
                else
                    filepath = @"\\?\" + filepath;
...
                SafeHandleMinusOneIsInvalid ret = FindFirstFileW(filepath, lpFindFileData);
...
            }

After you call FindFirstFile you must call FindNextFile for the next file in the directory, and then finally FindClose; for a complete example about how to list files in a directory using the Win32 kernel look here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM