在c#中获取unicode目录名?

时间:2014-05-22 13:55:46

标签: c# .net character-encoding io

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

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

此代码适用于具有ascii名称的目录。但是一个目录的名称是 “”(unicode值U + 00A0)。 GetDirectories()无法获取该目录。有没有办法让目录获得unicode名称?

1 个答案:

答案 0 :(得分:1)

好吧,你正在战斗的是.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枚举文档强调添加

目前的问题是CharSet上的DllImport参数。这意味着你只剩下一种方法;自己利用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);

使用这些可以构建自己的迭代器。但是,为了您的利益,这是Microsoft为" 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);
  }
}

以及他们为此做的事情"迭代"对于你正在寻找的东西:

  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' S。获取dotPeek的副本以填补空白。

注意: fileName接受的FindFirstFile参数将转到父目录。在您的情况下,H:\