获取c#中的unicode目录名

本文关键字:unicode 中的 获取 | 更新日期: 2023-09-27 18:04:33

我正在尝试使用以下代码从我的usb驱动器获取所有目录

DirectoryInfo di = new DirectoryInfo("H:''");
DirectoryInfo[] allDir = di.GetDirectories();

这段代码适用于ASCII名称的目录。但是其中一个目录的名字是" "(unicode值U+00A0)。GetDirectories()无法获取该目录。是否有一种方法来获得目录与unicode名称?

获取c#中的unicode目录名

好了,你要对抗的是。net框架使用FindFirstFile:

这个签名
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
internal static SafeFindHandle FindFirstFile(string fileName, [In, Out] Win32Native.WIN32_FIND_DATA data);

更糟的是,你在和语言作斗争:

为目标操作系统自动封送字符串。Windows NT、Windows 2000、Windows XP和Windows Server 2003系列的默认值是Unicode;在Windows 98和Windows Me上默认为Ansi。虽然公共语言运行时默认值为Auto,但语言可以覆盖此默认值。例如,c#默认将所有方法和类型标记为Ansi。

(来自CharSet枚举文档强调添加)

当前的问题是DllImport上的CharSet参数。这意味着你只剩下一种方法;您可以自己使用P/Invoke。你需要很多东西。首先需要返回的数据结构:

[BestFitMapping(false)]
[Serializable]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal class WIN32_FIND_DATA
{
  internal int dwFileAttributes;
  internal uint ftCreationTime_dwLowDateTime;
  internal uint ftCreationTime_dwHighDateTime;
  internal uint ftLastAccessTime_dwLowDateTime;
  internal uint ftLastAccessTime_dwHighDateTime;
  internal uint ftLastWriteTime_dwLowDateTime;
  internal uint ftLastWriteTime_dwHighDateTime;
  internal int nFileSizeHigh;
  internal int nFileSizeLow;
  internal int dwReserved0;
  internal int dwReserved1;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
  internal string cFileName;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
  internal string cAlternateFileName;
  [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  public WIN32_FIND_DATA()
  {
  }
}

接下来需要正确导入FindFirstFile:

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)]
internal static SafeFindHandle FindFirstFile(string fileName, [In, Out] Win32Native.WIN32_FIND_DATA data);

接下来你需要GetLastWin32Error来检查错误;可以通过InteropServices命名空间中的Marshal.GetLastWin32Error访问。

接下来需要迭代,所以需要FindNextFile:

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)]
internal static bool FindNextFile(SafeFindHandle hndFindFile, [MarshalAs(UnmanagedType.LPStruct), In, Out] Win32Native.WIN32_FIND_DATA lpFindFileData);
有了这些,你就可以构建自己的迭代器了。但是,为了您的利益,这里是微软为"init"做的:
[SecurityCritical]
private void CommonInit()
{
  string fileName = Path.InternalCombine(this.searchData.fullPath, this.searchCriteria);
  Win32Native.WIN32_FIND_DATA wiN32FindData = new Win32Native.WIN32_FIND_DATA();
  this._hnd = Win32Native.FindFirstFile(fileName, wiN32FindData);
  if (this._hnd.IsInvalid)
  {
    int lastWin32Error = Marshal.GetLastWin32Error();
    switch (lastWin32Error)
    {
      case 2:
      case 18:
        this.empty = this.searchData.searchOption == SearchOption.TopDirectoryOnly;
        break;
      default:
        this.HandleError(lastWin32Error, this.searchData.fullPath);
        break;
    }
  }
  if (this.searchData.searchOption == SearchOption.TopDirectoryOnly)
  {
    if (this.empty)
    {
      this._hnd.Dispose();
    }
    else
    {
      SearchResult searchResult = this.CreateSearchResult(this.searchData, wiN32FindData);
      if (!this._resultHandler.IsResultIncluded(searchResult))
        return;
      this.current = this._resultHandler.CreateObject(searchResult);
    }
  }
  else
  {
    this._hnd.Dispose();
    this.searchStack.Add(this.searchData);
  }
}

,这里是他们对"iterate"所做的,对于你正在寻找的内容:

  if (this.searchData != null && this._hnd != null)
  {
    while (Win32Native.FindNextFile(this._hnd, wiN32FindData))
    {
      SearchResult searchResult = this.CreateSearchResult(this.searchData, wiN32FindData);
      if (this._resultHandler.IsResultIncluded(searchResult))
      {
        if (this.needsParentPathDiscoveryDemand)
        {
          this.DoDemand(this.searchData.fullPath);
          this.needsParentPathDiscoveryDemand = false;
        }
        this.current = this._resultHandler.CreateObject(searchResult);
        return true;
      }
    }
    int lastWin32Error = Marshal.GetLastWin32Error();
    if (this._hnd != null)
      this._hnd.Dispose();
    if (lastWin32Error != 0 && lastWin32Error != 18 && lastWin32Error != 2)
      this.HandleError(lastWin32Error, this.searchData.fullPath);
  }

注意:你不能直接使用这段代码,你必须让它适合你的解决方案,但这是API的一个巨大的开始。给你找一份dotPeek来填补空白。

注: FindFirstFile接受的fileName参数是进入父目录。在您的例子中,H:' .