c# – 如何获取实际(本地化)文件夹名称?

前端之家收集整理的这篇文章主要介绍了c# – 如何获取实际(本地化)文件夹名称?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Function for getting localized path?2个
我在c#中编写一个功能,我需要列出给定目录中的所有文件/文件名称.该功能在EN OS上运行良好,但是当我在本地化操作系统(例如德语)上运行应用程序时,我仍然获得特殊文件夹的英文名称(程序文件而不是程序,收藏夹而非收藏夹等).我不认为带有Environment.SpecialFolder的Environment.GetFolderPath可以提供任何帮助,因为它与我想要的完全相反,即它给出了枚举的特殊文件夹的完整路径,而我想要给定的本地化名称路径.我尝试过使用File,SHFileInfo,但没有用.任何想法,我怎样才能获得操作系统中显示文件名称

解决方法

您可以使用SHGetFileInfo API获取本地化的显示名称
  1. public static string GetDisplayName(Environment.SpecialFolder specialFolder)
  2. {
  3. IntPtr pidl = IntPtr.Zero;
  4. try
  5. {
  6. HResult hr = SHGetFolderLocation(IntPtr.Zero,(int) specialFolder,IntPtr.Zero,out pidl);
  7. if (hr.IsFailure)
  8. return null;
  9.  
  10. SHFILEINFO shfi;
  11. if (0 != SHGetFileInfo(
  12. pidl,FILE_ATTRIBUTE_NORMAL,out shfi,(uint)Marshal.SizeOf(typeof(SHFILEINFO)),SHGFI_PIDL | SHGFI_DISPLAYNAME))
  13. {
  14. return shfi.szDisplayName;
  15. }
  16. return null;
  17. }
  18. finally
  19. {
  20. if (pidl != IntPtr.Zero)
  21. ILFree(pidl);
  22. }
  23. }
  24.  
  25. public static string GetDisplayName(string path)
  26. {
  27. SHFILEINFO shfi;
  28. if (0 != SHGetFileInfo(
  29. path,SHGFI_DISPLAYNAME))
  30. {
  31. return shfi.szDisplayName;
  32. }
  33. return null;
  34. }
  35.  
  36. private const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;
  37. private const uint SHGFI_DISPLAYNAME = 0x000000200; // get display name
  38. private const uint SHGFI_PIDL = 0x000000008; // pszPath is a pidl
  39.  
  40. [DllImport("shell32")]
  41. private static extern int SHGetFileInfo(IntPtr pidl,uint dwFileAttributes,out SHFILEINFO psfi,uint cbFileInfo,uint flags);
  42. [DllImport("shell32")]
  43. private static extern HResult SHGetFolderLocation(IntPtr hwnd,int nFolder,IntPtr token,int dwReserved,out IntPtr pidl);
  44. [DllImport("shell32")]
  45. private static extern void ILFree(IntPtr pidl);
  46.  
  47. [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
  48. private struct SHFILEINFO
  49. {
  50. public IntPtr hIcon;
  51. public int iIcon;
  52. public uint dwAttributes;
  53. [MarshalAs(UnmanagedType.ByValTStr,SizeConst = 260)]
  54. public string szDisplayName;
  55. [MarshalAs(UnmanagedType.ByValTStr,SizeConst = 80)]
  56. public string szTypeName;
  57. }
  58.  
  59. [StructLayout(LayoutKind.Sequential)]
  60. public struct HResult
  61. {
  62. private int _value;
  63.  
  64. public int Value
  65. {
  66. get { return _value; }
  67. }
  68.  
  69. public Exception Exception
  70. {
  71. get { return Marshal.GetExceptionForHR(_value); }
  72. }
  73.  
  74. public bool IsSuccess
  75. {
  76. get { return _value >= 0; }
  77. }
  78.  
  79. public bool IsFailure
  80. {
  81. get { return _value < 0; }
  82. }
  83. }

猜你在找的C#相关文章