【问题标题】:c# call Win32 API for long file paths?c#为长文件路径调用Win32 API?
【发布时间】:2009-08-08 12:56:24
【问题描述】:

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

【问题讨论】:

    标签: c#


    【解决方案1】:

    如果你想使用 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);
    ...
                }
    

    在调用 FindFirstFile 之后,必须为目录中的下一个文件调用 FindNextFile,最后是 FindClose;有关如何使用 Win32 内核列出目录中文件的完整示例,请查看 here

    【讨论】:

      猜你喜欢
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 2020-03-13
      相关资源
      最近更新 更多