简体   繁体   English

C#调用Win32 API的长文件路径?

[英]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: 如果要使用Win32调用,则首先必须使用DllImport导入内核,其语法类似于这样,并且必须对要使用的每个方法都执行此操作(这都是未经测试的伪代码,仅描述此概念),代码示例将您的路径转换为UNC路径,因此您可以拥有较长的文件路径:

    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; 调用FindFirstFile之后,必须为目录中的下一个文件调用FindNextFile,然后最终调用FindClose。 for a complete example about how to list files in a directory using the Win32 kernel look here 有关如何使用Win32内核列出目录中文件的完整示例,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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