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

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

解决方法

您可以使用SHGetFileInfo API获取本地化的显示名称
public  static string GetDisplayName(Environment.SpecialFolder specialFolder)
    {
        IntPtr pidl = IntPtr.Zero;
        try
        {
            HResult hr = SHGetFolderLocation(IntPtr.Zero,(int) specialFolder,IntPtr.Zero,out pidl);
            if (hr.IsFailure)
                return null;

            SHFILEINFO shfi;
            if (0 != SHGetFileInfo(
                        pidl,FILE_ATTRIBUTE_NORMAL,out shfi,(uint)Marshal.SizeOf(typeof(SHFILEINFO)),SHGFI_PIDL | SHGFI_DISPLAYNAME))
            {
                return shfi.szDisplayName;
            }
            return null;
        }
        finally
        {
            if (pidl != IntPtr.Zero)
                ILFree(pidl);
        }
    }

    public static string GetDisplayName(string path)
    {
        SHFILEINFO shfi;
        if (0 != SHGetFileInfo(
                    path,SHGFI_DISPLAYNAME))
        {
            return shfi.szDisplayName;
        }
        return null;
    }

    private const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;
    private const uint SHGFI_DISPLAYNAME = 0x000000200;     // get display name
    private const uint SHGFI_PIDL = 0x000000008;     // pszPath is a pidl

    [DllImport("shell32")]
    private static extern int SHGetFileInfo(IntPtr pidl,uint dwFileAttributes,out SHFILEINFO psfi,uint cbFileInfo,uint flags);
    [DllImport("shell32")]
    private static extern HResult SHGetFolderLocation(IntPtr hwnd,int nFolder,IntPtr token,int dwReserved,out IntPtr pidl);
    [DllImport("shell32")]
    private static extern void ILFree(IntPtr pidl);

    [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
    private struct SHFILEINFO
    {
        public IntPtr hIcon;
        public int iIcon;
        public uint dwAttributes;
        [MarshalAs(UnmanagedType.ByValTStr,SizeConst = 260)]
        public string szDisplayName;
        [MarshalAs(UnmanagedType.ByValTStr,SizeConst = 80)]
        public string szTypeName;
    }

[StructLayout(LayoutKind.Sequential)]
public struct HResult
{
    private int _value;

    public int Value
    {
        get { return _value; }
    }

    public Exception Exception
    {
        get { return Marshal.GetExceptionForHR(_value); }
    }

    public bool IsSuccess
    {
        get { return _value >= 0; }
    }

    public bool IsFailure
    {
        get { return _value < 0; }
    }
}
原文链接:https://www.f2er.com/csharp/100757.html

猜你在找的C#相关文章