Getting the NAME (not path) of a special folder.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sin Jeong-hun

    Getting the NAME (not path) of a special folder.

    Hello.

    Speical folders, like Desktop, usually have different display names.
    For example, in Japanese Windows, it's displayed as "$B%G%9%/%H%C%W(B". I want
    to get the this displayed name of a special folder but I can't find a
    suitable method. Environment.Get FolderPath() is to get the path not
    the name. There's no way provided the .NET BCL?

    I also tried to get it through Win32 API. I looked up the MSDN site
    (http://support.microsoft.com/kb/319350), and wrote a code like the
    following, but it didn't work. It showed "top" instead of "Desktop" on
    my PC (64 bit, Vista, English).

    Path =
    Environment.Get FolderPath(Envi ronment.Special Folder.DesktopD irectory);
    SHFILEINFO shinfo=new SHFILEINFO();
    SHGetFileInfo(P ath, 0, ref shinfo, (uint)Marshal.S izeOf(shinfo),
    SHGFI_DISPLAYNA ME);
    MessageBox.Show (shinfo.szDispl ayName);
    ///////////////////////////// P/Invoke declarations
    [StructLayout(La youtKind.Sequen tial)]
    public struct SHFILEINFO
    {
    public IntPtr hIcon;
    public IntPtr iIcon;
    public uint dwAttributes;
    [MarshalAs(Unman agedType.ByValT Str, SizeConst = 260)]
    public string szDisplayName;
    [MarshalAs(Unman agedType.ByValT Str, SizeConst = 80)]
    public string szTypeName;
    };
    public const int SHGFI_DISPLAYNA ME = 0x000000200; // get display
    name
    [DllImport("shel l32.dll")]
    public static extern IntPtr SHGetFileInfo(s tring pszPath, uint
    dwFileAttribute s, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint
    uFlags);
  • Jeroen Mostert

    #2
    Re: Getting the NAME (not path) of a special folder.

    Sin Jeong-hun wrote:
    Speical folders, like Desktop, usually have different display names.
    For example, in Japanese Windows, it's displayed as "デスクトムƒãƒ—". I want
    to get the this displayed name of a special folder but I can't find a
    suitable method. Environment.Get FolderPath() is to get the path not
    the name. There's no way provided the .NET BCL?
    >
    Nope.
    I also tried to get it through Win32 API. I looked up the MSDN site
    (http://support.microsoft.com/kb/319350), and wrote a code like the
    following, but it didn't work. It showed "top" instead of "Desktop" on
    my PC (64 bit, Vista, English).
    >
    Path =
    Environment.Get FolderPath(Envi ronment.Special Folder.DesktopD irectory);
    SHFILEINFO shinfo=new SHFILEINFO();
    SHGetFileInfo(P ath, 0, ref shinfo, (uint)Marshal.S izeOf(shinfo),
    SHGFI_DISPLAYNA ME);
    MessageBox.Show (shinfo.szDispl ayName);
    ///////////////////////////// P/Invoke declarations
    [StructLayout(La youtKind.Sequen tial)]
    public struct SHFILEINFO
    {
    public IntPtr hIcon;
    public IntPtr iIcon;
    public uint dwAttributes;
    [MarshalAs(Unman agedType.ByValT Str, SizeConst = 260)]
    public string szDisplayName;
    [MarshalAs(Unman agedType.ByValT Str, SizeConst = 80)]
    public string szTypeName;
    };
    Try declaring "iIcon" as "int" rather than "IntPtr". This is the wrong size
    on 64-bit.

    --
    J.

    Comment

    • Sin Jeong-hun

      #3
      Re: Getting the NAME (not path) of a special folder.

      On Jul 12, 12:25 am, Jeroen Mostert <jmost...@xs4al l.nlwrote:
      Sin Jeong-hun wrote:
      Speical folders, like Desktop, usually have different display names.
      For example, in Japanese Windows, it's displayed as "$B%G%9%/%H%C%W(B". I want
      to get the this displayed name of a special folder but I can't find a
      suitable method. Environment.Get FolderPath() is to get the path not
      the name. There's no way provided the .NET BCL?
      >
      Nope.
      >
      >
      >
      >
      >
      I also tried to get it through Win32 API. I looked up the MSDN site
      (http://support.microsoft.com/kb/319350), and wrote a code like the
      following, but it didn't work. It showed "top" instead of "Desktop" on
      my PC (64 bit, Vista, English).
      >
      Path =
      Environment.Get FolderPath(Envi ronment.Special Folder.DesktopD irectory);
      SHFILEINFO shinfo=new SHFILEINFO();
      SHGetFileInfo(P ath, 0, ref shinfo, (uint)Marshal.S izeOf(shinfo),
      SHGFI_DISPLAYNA ME);
      MessageBox.Show (shinfo.szDispl ayName);
      ///////////////////////////// P/Invoke declarations
      [StructLayout(La youtKind.Sequen tial)]
      public struct SHFILEINFO
      {
      public IntPtr hIcon;
      public IntPtr iIcon;
      public uint dwAttributes;
      [MarshalAs(Unman agedType.ByValT Str, SizeConst = 260)]
      public string szDisplayName;
      [MarshalAs(Unman agedType.ByValT Str, SizeConst = 80)]
      public string szTypeName;
      };
      >
      Try declaring "iIcon" as "int" rather than "IntPtr". This is the wrong size
      on 64-bit.
      >
      --
      J.
      Thank you for the answer. Now that I know the BCL doesn't provide any
      method to do that, the only choice I have is to use Win32 API.

      However, chaning IntPtr to int or Int32 or even long didn't make it
      return correct string. I think I once dealt with a similar problem of
      declaring a Win32 structure for 64bit C# application, but I cannot
      remember how I did it.

      Comment

      • =?Utf-8?B?Q2lhcmFuIE8nJ0Rvbm5lbGw=?=

        #4
        Re: Getting the NAME (not path) of a special folder.

        I think I this might be the answer, I assembled it from some clever guys blog



        He seems to REALLY know what he's doing with shell interact so if this isnt
        it, you could probably ask him how its done.
        Anyway. paste this into consoleapp and give it a go. It seems to work for me
        but my Desktop is called Desktop. My Computer however has had its display
        name changed to my name and then the computer name and it gave me that back
        correctly.

        Ah Ok hold on. this web app only allows 30,000 characters and this is 35501.
        So i will chop off the bottom and reply to this post with the rest of the code

        --
        Ciaran O''Donnell


        // Everything from here down is code:
        using System;
        using System.Collecti ons.Generic;
        using System.Linq;
        using System.Text;
        using System.IO;
        using System.Data.Sql Client;
        using System.Data;
        using System.Diagnost ics;
        using System.Reflecti on;
        using System.Threadin g;
        using System.Windows. Forms;
        using Microsoft.Win32 ;
        using System.Collecti ons;
        using System.Runtime. InteropServices ;
        using System.Drawing;
        using System.Security .Permissions;

        namespace ConsoleApplicat ion1
        {
        class Program
        {

        static void Main(string[] args)
        {

        CGFolder f = new CGFolder(Enviro nment.SpecialFo lder.Desktop);

        Console.WriteLi ne(f.Pidl.Displ ayName );
        Console.ReadLin e();
        }


        }





        [ComVisible(fals e)]
        public sealed class CGFolder : IDisposable
        {

        private static class NativeMethods
        {

        public static Guid IID_IShellFolde r = new Guid(
        "{000214E6-0000-0000-C000-000000000046}"
        );

        [DllImport("shel l32.dll")]
        public static extern Int32 SHGetDesktopFol der(
        out IShellFolder ppshf
        );

        public enum SHCONTF
        {
        SHCONTF_FOLDERS = 0x0020,
        SHCONTF_NONFOLD ERS = 0x0040,
        SHCONTF_INCLUDE HIDDEN = 0x0080,
        SHCONTF_INIT_ON _FIRST_NEXT = 0x0100,
        SHCONTF_NETPRIN TERSRCH = 0x0200,
        SHCONTF_SHAREAB LE = 0x0400,
        SHCONTF_STORAGE = 0x0800
        }

        [Flags]
        public enum SHCIDS : uint
        {
        SHCIDS_ALLFIELD S = 0x80000000,
        SHCIDS_CANONICA LONLY = 0x10000000,
        SHCIDS_BITMASK = 0xFFFF0000,
        SHCIDS_COLUMNMA SK = 0x0000FFFF
        }

        [Flags]
        public enum FOLDERFLAGS
        {
        FWF_AUTOARRANGE = 0x1,
        FWF_ABBREVIATED NAMES = 0x2,
        FWF_SNAPTOGRID = 0x4,
        FWF_OWNERDATA = 0x8,
        FWF_BESTFITWIND OW = 0x10,
        FWF_DESKTOP = 0x20,
        FWF_SINGLESEL = 0x40,
        FWF_NOSUBFOLDER S = 0x80,
        FWF_TRANSPARENT = 0x100,
        FWF_NOCLIENTEDG E = 0x200,
        FWF_NOSCROLL = 0x400,
        FWF_ALIGNLEFT = 0x800,
        FWF_NOICONS = 0x1000,
        FWF_SHOWSELALWA YS = 0x2000,
        FWF_NOVISIBLE = 0x4000,
        FWF_SINGLECLICK ACTIVATE = 0x8000,
        FWF_NOWEBVIEW = 0x10000,
        FWF_HIDEFILENAM ES = 0x20000,
        FWF_CHECKSELECT = 0x40000
        }

        public enum FOLDERVIEWMODE
        {
        FVM_FIRST = 1,
        FVM_ICON = 1,
        FVM_SMALLICON = 2,
        FVM_LIST = 3,
        FVM_DETAILS = 4,
        FVM_THUMBNAIL = 5,
        FVM_TILE = 6,
        FVM_THUMBSTRIP = 7,
        FVM_LAST = 7
        }

        [StructLayout(La youtKind.Explic it)]
        public struct STRRET
        {
        [FieldOffset(0)]
        UInt32 uType;
        [FieldOffset(4)]
        IntPtr pOleStr;
        [FieldOffset(4)]
        IntPtr pStr;
        [FieldOffset(4)]
        UInt32 uOffset;
        [FieldOffset(4)]
        IntPtr cStr;
        }

        [Flags()]
        public enum SFGAO : uint
        {
        SFGAO_CANCOPY = 0x000000001,
        SFGAO_CANMOVE = 0x000000002,
        SFGAO_CANLINK = 0x000000004,
        SFGAO_STORAGE = 0x000000008,
        SFGAO_CANRENAME = 0x00000010,
        SFGAO_CANDELETE = 0x00000020,
        SFGAO_HASPROPSH EET = 0x00000040,
        SFGAO_DROPTARGE T = 0x00000100,
        SFGAO_CAPABILIT YMASK = 0x00000177,
        SFGAO_ENCRYPTED = 0x00002000,
        SFGAO_ISSLOW = 0x00004000,
        SFGAO_GHOSTED = 0x00008000,
        SFGAO_LINK = 0x00010000,
        SFGAO_SHARE = 0x00020000,
        SFGAO_READONLY = 0x00040000,
        SFGAO_HIDDEN = 0x00080000,
        SFGAO_DISPLAYAT TRMASK = 0x000FC000,
        SFGAO_FILESYSAN CESTOR = 0x10000000,
        SFGAO_FOLDER = 0x20000000,
        SFGAO_FILESYSTE M = 0x40000000,
        SFGAO_HASSUBFOL DER = 0x80000000,
        SFGAO_CONTENTSM ASK = 0x80000000,
        SFGAO_VALIDATE = 0x01000000,
        SFGAO_REMOVABLE = 0x02000000,
        SFGAO_COMPRESSE D = 0x04000000,
        SFGAO_BROWSABLE = 0x08000000,
        SFGAO_NONENUMER ATED = 0x00100000,
        SFGAO_NEWCONTEN T = 0x00200000,
        SFGAO_CANMONIKE R = 0x00400000,
        SFGAO_HASSTORAG E = 0x00400000,
        SFGAO_STREAM = 0x00400000,
        SFGAO_STORAGEAN CESTOR = 0x00800000,
        SFGAO_STORAGECA PMASK = 0x70C50008
        }

        [Flags()]
        public enum SHGDN
        {
        SHGDN_NORMAL = 0,
        SHGDN_INFOLDER = 1,
        SHGDN_FORADDRES SBAR = 16384,
        SHGDN_FORPARSIN G = 32768
        }

        [StructLayout(La youtKind.Sequen tial)]
        public struct RECT
        {
        public int left;
        public int top;
        public int right;
        public int bottom;

        public RECT(
        Rectangle r
        )
        {
        left = r.Left;
        top = r.Top;
        right = r.Right;
        bottom = r.Bottom;
        }

        }

        [StructLayout(La youtKind.Sequen tial)]
        public struct FOLDERSETTINGS
        {
        public FOLDERFLAGS ViewMode;
        public FOLDERVIEWMODE fFlags;
        }

        public enum SVUIA_STATUS
        {
        SVUIA_DEACTIVAT E = 0,
        SVUIA_ACTIVATE_ NOFOCUS = 1,
        SVUIA_ACTIVATE_ FOCUS = 2,
        SVUIA_INPLACEAC TIVATE = 3
        }

        [ComImportAttrib ute()]
        [GuidAttribute(
        "000214F2-0000-0000-C000-000000000046")]
        [InterfaceTypeAt tribute(
        ComInterfaceTyp e.InterfaceIsIU nknown)]
        public interface IEnumIDList
        {
        [PreserveSig]
        int Next(
        int celt,
        ref IntPtr
        rgelt, out
        int pceltFetched
        );
        [PreserveSig]
        int Skip(int celt);
        [PreserveSig]
        int Reset();
        [PreserveSig]
        int Clone(
        ref IEnumIDList ppenum
        );
        }

        [ComImport()]
        [Guid(
        "000214E2-0000-0000-C000-000000000046")]
        [InterfaceType(
        ComInterfaceTyp e.InterfaceIsIU nknown)]
        public interface IShellBrowser
        {
        [PreserveSig]
        int GetWindow(out IntPtr phwnd);
        [PreserveSig]
        int ContextSensitiv eHelp(bool fEnterMode);
        [PreserveSig]
        int InsertMenusSB(
        IntPtr hmenuShared,
        ref IntPtr lpMenuWidths
        );
        [PreserveSig]
        int SetMenuSB(
        IntPtr hmenuShared,
        IntPtr holemenuRes,
        IntPtr hwndActiveObjec t
        );
        [PreserveSig]
        int RemoveMenusSB(
        IntPtr hmenuShared
        );
        [PreserveSig]
        int SetStatusTextSB (
        string pszStatusText
        );
        [PreserveSig]
        int EnableModelessS B(
        bool fEnable
        );
        [PreserveSig]
        int TranslateAccele ratorSB(
        IntPtr pmsg,
        short wID
        );
        [PreserveSig]
        int BrowseObject(
        IntPtr pidl,
        uint wFlags
        );
        [PreserveSig]
        int GetViewStateStr eam(
        long grfMode,
        ref UCOMIStream ppStrm
        );
        [PreserveSig]
        int GetControlWindo w(
        uint id,
        ref IntPtr phwnd
        );
        [PreserveSig]
        int SendControlMsg(
        uint id,
        uint uMsg,
        short wParam,
        long lParam,
        ref long pret
        );
        [PreserveSig]
        int QueryActiveShel lView(
        ref IShellView ppshv
        );
        [PreserveSig]
        int OnViewWindowAct ive(
        IShellView pshv
        );
        [PreserveSig]
        int SetToolbarItems (
        IntPtr lpButtons,
        uint nButtons,
        uint uFlags
        );
        }

        [ComImport()]
        [Guid("000214E3-0000-0000-C000-000000000046")]
        [InterfaceType(C omInterfaceType .InterfaceIsIUn known)]
        public interface IShellView
        {
        [PreserveSig]
        int GetWindow(out IntPtr phwnd);
        [PreserveSig]
        int ContextSensitiv eHelp(bool fEnterMode);
        [PreserveSig]
        int TranslateAccele ratorA(IntPtr pmsg);
        [PreserveSig]
        int EnableModeless( bool fEnable);
        [PreserveSig]
        int UIActivate(SVUI A_STATUS uState);
        [PreserveSig]
        int Refresh();
        [PreserveSig]
        int CreateViewWindo w(
        IShellView psvPrevious,
        ref FOLDERSETTINGS pfs,
        IShellBrowser psb,
        ref RECT prcView,
        out IntPtr phWnd
        );
        [PreserveSig]
        int DestroyViewWind ow();
        [PreserveSig]
        int GetCurrentInfo( ref FOLDERSETTINGS pfs);
        [PreserveSig]
        int AddPropertyShee tPages(
        long dwReserved,
        ref IntPtr pfnPtr,
        int lparam
        );
        [PreserveSig]
        int SaveViewState() ;
        [PreserveSig]
        int SelectItem(IntP tr pidlItem, uint uFlags);
        [PreserveSig]
        int GetItemObject(
        uint uItem,
        ref Guid riid,
        ref IntPtr ppv
        );
        }

        [ComImport]
        [InterfaceType(C omInterfaceType .InterfaceIsIUn known)]
        [Guid("000214E6-0000-0000-C000-000000000046")]
        public interface IShellFolder
        {
        [PreserveSig]
        Int32 ParseDisplayNam e(
        IntPtr hwnd,
        IntPtr pbc,
        [MarshalAs(Unman agedType.LPWStr )]
        string pszDisplayName,
        ref UInt32 pchEaten,
        out IntPtr ppidl,
        ref UInt32 pdwAttributes
        );
        [PreserveSig]
        Int32 EnumObjects(
        IntPtr hwnd,
        SHCONTF grfFlags,
        out IEnumIDList ppenumIDList
        );
        [PreserveSig]
        Int32 BindToObject(
        IntPtr pidl,
        IntPtr pbc,
        ref Guid riid,
        out IntPtr ppv
        );
        [PreserveSig]
        Int32 BindToStorage(
        IntPtr pidl,
        IntPtr pbc,
        ref Guid riid,
        out IntPtr ppv
        );
        [PreserveSig]
        Int32 CompareIDs(
        SHCIDS lParam,
        IntPtr pidl1,
        IntPtr pidl2
        );
        [PreserveSig]
        Int32 CreateViewObjec t(
        IntPtr hwndOwner,
        ref Guid riid,
        out IShellView ppv
        );
        [PreserveSig]
        Int32 GetAttributesOf (
        UInt32 cidl,
        [MarshalAs(Unman agedType.LPArra y, SizeParamIndex = 0)]
        IntPtr[] apidl,
        ref SFGAO rgfInOut
        );
        [PreserveSig]
        Int32 GetUIObjectOf(
        IntPtr hwndOwner,
        UInt32 cidl,
        IntPtr[] apidl,
        Guid riid,
        ref UInt32 rgfReserved,
        out IntPtr ppv
        );
        [PreserveSig]
        Int32 GetDisplayNameO f(
        IntPtr pidl,
        SHGDN uFlags,
        out STRRET pName
        );
        [PreserveSig]
        Int32 SetNameOf(
        IntPtr hwnd,
        IntPtr pidl,
        [MarshalAs(Unman agedType.LPWStr )]
        string pszName,
        UInt32 uFlags,
        out IntPtr ppidlOut
        );
        }
        }

        private static readonly NativeMethods.I ShellFolder
        c_desktopFolder ;
        private NativeMethods.I ShellFolder m_folder;
        private CGPidl m_pidl;

        public CGPidl Pidl
        {
        get { return m_pidl; }
        }

        public object Interface
        {
        get { return m_folder; }
        }

        [SecurityPermiss ion(SecurityAct ion.LinkDemand,
        Flags = SecurityPermiss ionFlag.Unmanag edCode)]
        static CGFolder()
        {

        // Get a reference to the desktop folder.
        NativeMethods.S HGetDesktopFold er(
        out c_desktopFolder
        );

        }

        public CGFolder()
        {

        }

        [SecurityPermiss ion(SecurityAct ion.LinkDemand,
        Flags = SecurityPermiss ionFlag.Unmanag edCode)]
        public CGFolder(
        Environment.Spe cialFolder specialFolder
        )
        {
        Open(specialFol der);
        }

        [SecurityPermiss ion(SecurityAct ion.LinkDemand,
        Flags = SecurityPermiss ionFlag.Unmanag edCode)]
        public CGFolder(
        string fullPath
        )
        {
        Open(fullPath);
        }

        [SecurityPermiss ion(SecurityAct ion.LinkDemand,
        Flags = SecurityPermiss ionFlag.Unmanag edCode)]
        public CGFolder(
        CGPidl pidl
        )
        {
        Open(pidl);
        }

        public void Dispose()
        {
        Close();
        }

        [SecurityPermiss ion(SecurityAct ion.LinkDemand,
        Flags = SecurityPermiss ionFlag.Unmanag edCode)]
        public void Open(
        Environment.Spe cialFolder specialFolder
        )
        {

        // Free any open resources.
        Close();

        // Create the identifier.
        m_pidl = new CGPidl(specialF older);

        // Create the folder reference.
        InitializeFolde r();

        }

        [SecurityPermiss ion(SecurityAct ion.LinkDemand,
        Flags = SecurityPermiss ionFlag.Unmanag edCode)]
        public void Open(
        string fullPath
        )
        {

        // Create the identifier.
        m_pidl = new CGPidl(fullPath );

        // Create the folder reference.
        InitializeFolde r();

        }

        [SecurityPermiss ion(SecurityAct ion.LinkDemand,
        Flags = SecurityPermiss ionFlag.Unmanag edCode)]
        public void Open(
        CGPidl pidl
        )
        {

        // Clone the identifier.
        m_pidl = (CGPidl)pidl.Cl one();

        // Create the folder reference.
        InitializeFolde r();

        }

        public void Close()
        {

        // Should we cleanup the identifier?
        if (m_pidl != null)
        m_pidl.Dispose( );

        m_pidl = null;

        // Should we cleanup the folder?
        if (m_folder != null)
        Marshal.Release ComObject(m_fol der);

        m_folder = null;

        }

        [SecurityPermiss ion(SecurityAct ion.LinkDemand,
        Flags = SecurityPermiss ionFlag.Unmanag edCode)]
        public System.Collecti ons.ArrayList GetChildren(
        bool showHiddenObjec ts,
        bool showNonFolders,
        bool sortResults
        )
        {

        ArrayList children = new ArrayList();
        NativeMethods.I EnumIDList enumList = null;

        try
        {
        // Sanity check the folder before attempting to use it.
        if (m_pidl == null || !m_pidl.IsFolde r || m_folder == null)
        return children;

        // Get the enumerator for the object.
        int hr = m_folder.EnumOb jects(
        IntPtr.Zero,
        NativeMethods.S HCONTF.SHCONTF_ FOLDERS |
        (showNonFolders ?
        NativeMethods.S HCONTF.SHCONTF_ NONFOLDERS : 0) |
        (showHiddenObje cts ?
        NativeMethods.S HCONTF.SHCONTF_ INCLUDEHIDDEN : 0),
        out enumList
        );

        // Did we fail?
        if (hr != 0)
        Marshal.ThrowEx ceptionForHR(hr );

        IntPtr pidl = IntPtr.Zero;
        int fetched = 0;

        // Loop and walk through the child objects.
        while (enumList.Next( 1, ref pidl, out fetched) == 0 &&
        fetched == 1)
        {

        // Create a new identifier for the object.
        CGPidl child = new CGPidl(
        m_pidl.Pidl,
        pidl
        );

        // Add the object to the array.
        children.Add(ch ild);

        } // End while there are more child objects.

        // Should we sort the results?
        if (sortResults)
        children.Sort() ;

        } // End try

        finally
        {

        // Should we cleanup the enumerator reference?
        if (enumList != null)
        Marshal.Release ComObject(enumL ist);

        enumList = null;

        } // End finally

        // Return the list of children.
        return children;

        }

        [SecurityPermiss ion(SecurityAct ion.LinkDemand,
        Flags = SecurityPermiss ionFlag.Unmanag edCode)]
        private void InitializeFolde r()
        {

        // Should we simply obtain a reference to the desktop?
        if (m_pidl.IsDeskt op)
        NativeMethods.S HGetDesktopFold er(
        out m_folder
        );
        else
        {

        NativeMethods.I ShellFolder parentFolder = null;

        try
        {

        IntPtr ptr;

        // Get a reference to the folder.
        int hr = c_desktopFolder .BindToObject(
        m_pidl.Pidl,
        IntPtr.Zero,
        ref NativeMethods.I ID_IShellFolder ,
        out ptr
        );

        // Did we fail?
        if (hr != 0)
        Marshal.ThrowEx ceptionForHR(hr );

        // Unwrap the inteface.
        m_folder =
        (NativeMethods. IShellFolder)
        Marshal.GetType dObjectForIUnkn own(
        ptr,
        typeof(NativeMe thods.IShellFol der)
        );

        } // End try

        finally
        {

        // Should we cleanup the parent folder?
        if (parentFolder != null)
        Marshal.Release ComObject(paren tFolder);

        parentFolder = null;

        } // End finally

        } // End else we should handle the general case.
        }
        }


        Comment

        • =?Utf-8?B?Q2lhcmFuIE8nJ0Rvbm5lbGw=?=

          #5
          Re: Getting the NAME (not path) of a special folder.

          Here is the rest of the code
          --
          Ciaran O''Donnell



          [ComVisible(fals e)]
          public sealed class CGPidl : IDisposable, IComparable, ICloneable
          {

          private static class NativeMethods
          {

          [StructLayout(La youtKind.Sequen tial)]
          public struct RECT
          {
          public int left;
          public int top;
          public int right;
          public int bottom;

          public RECT(
          Rectangle r
          )
          {
          left = r.Left;
          top = r.Top;
          right = r.Right;
          bottom = r.Bottom;
          }

          }

          [Flags]
          public enum CSIDL
          {
          CSIDL_FLAG_CREA TE = 0x8000,
          CSIDL_ADMINTOOL S = 0x0030,
          CSIDL_ALTSTARTU P = 0x001d,
          CSIDL_APPDATA = 0x001a,
          CSIDL_BITBUCKET = 0x000a,
          CSIDL_CDBURN_AR EA = 0x003b,
          CSIDL_COMMON_AD MINTOOLS = 0x002f,
          CSIDL_COMMON_AL TSTARTUP = 0x001e,
          CSIDL_COMMON_AP PDATA = 0x0023,
          CSIDL_COMMON_DE SKTOPDIRECTORY = 0x0019,
          CSIDL_COMMON_DO CUMENTS = 0x002e,
          CSIDL_COMMON_FA VORITES = 0x001f,
          CSIDL_COMMON_MU SIC = 0x0035,
          CSIDL_COMMON_PI CTURES = 0x0036,
          CSIDL_COMMON_PR OGRAMS = 0x0017,
          CSIDL_COMMON_ST ARTMENU = 0x0016,
          CSIDL_COMMON_ST ARTUP = 0x0018,
          CSIDL_COMMON_TE MPLATES = 0x002d,
          CSIDL_COMMON_VI DEO = 0x0037,
          CSIDL_CONTROLS = 0x0003,
          CSIDL_COOKIES = 0x0021,
          CSIDL_DESKTOP = 0x0000,
          CSIDL_DESKTOPDI RECTORY = 0x0010,
          CSIDL_DRIVES = 0x0011,
          CSIDL_FAVORITES = 0x0006,
          CSIDL_FONTS = 0x0014,
          CSIDL_HISTORY = 0x0022,
          CSIDL_INTERNET = 0x0001,
          CSIDL_INTERNET_ CACHE = 0x0020,
          CSIDL_LOCAL_APP DATA = 0x001c,
          CSIDL_MYDOCUMEN TS = 0x000c,
          CSIDL_MYMUSIC = 0x000d,
          CSIDL_MYPICTURE S = 0x0027,
          CSIDL_MYVIDEO = 0x000e,
          CSIDL_NETHOOD = 0x0013,
          CSIDL_NETWORK = 0x0012,
          CSIDL_PERSONAL = 0x0005,
          CSIDL_PRINTERS = 0x0004,
          CSIDL_PRINTHOOD = 0x001b,
          CSIDL_PROFILE = 0x0028,
          CSIDL_PROFILES = 0x003e,
          CSIDL_PROGRAM_F ILES = 0x0026,
          CSIDL_PROGRAM_F ILES_COMMON = 0x002b,
          CSIDL_PROGRAMS = 0x0002,
          CSIDL_RECENT = 0x0008,
          CSIDL_SENDTO = 0x0009,
          CSIDL_STARTMENU = 0x000b,
          CSIDL_STARTUP = 0x0007,
          CSIDL_SYSTEM = 0x0025,
          CSIDL_TEMPLATES = 0x0015,
          CSIDL_WINDOWS = 0x0024
          }

          [StructLayout(La youtKind.Sequen tial)]
          public struct SHFILEINFO
          {
          public IntPtr hIcon;
          public Int32 iIcon;
          public UInt32 dwAttributes;
          [MarshalAs(Unman agedType.ByValT Str, SizeConst = 260)]
          public string szDisplayName;
          [MarshalAs(Unman agedType.ByValT Str, SizeConst = 80)]
          public string szTypeName;
          };

          public enum SHCONTF
          {
          SHCONTF_FOLDERS = 0x0020,
          SHCONTF_NONFOLD ERS = 0x0040,
          SHCONTF_INCLUDE HIDDEN = 0x0080,
          SHCONTF_INIT_ON _FIRST_NEXT = 0x0100,
          SHCONTF_NETPRIN TERSRCH = 0x0200,
          SHCONTF_SHAREAB LE = 0x0400,
          SHCONTF_STORAGE = 0x0800
          }

          [Flags]
          public enum SHGFI
          {
          SHGFI_ICON = 0x000000100,
          SHGFI_DISPLAYNA ME = 0x000000200,
          SHGFI_TYPENAME = 0x000000400,
          SHGFI_ATTRIBUTE S = 0x000000800,
          SHGFI_ICONLOCAT ION = 0x000001000,
          SHGFI_EXETYPE = 0x000002000,
          SHGFI_SYSICONIN DEX = 0x000004000,
          SHGFI_LINKOVERL AY = 0x000008000,
          SHGFI_SELECTED = 0x000010000,
          SHGFI_ATTR_SPEC IFIED = 0x000020000,
          SHGFI_LARGEICON = 0x000000000,
          SHGFI_SMALLICON = 0x000000001,
          SHGFI_OPENICON = 0x000000002,
          SHGFI_SHELLICON SIZE = 0x000000004,
          SHGFI_PIDL = 0x000000008,
          SHGFI_USEFILEAT TRIBUTES = 0x000000010,
          SHGFI_ADDOVERLA YS = 0x000000020,
          SHGFI_OVERLAYIN DEX = 0x000000040
          }

          [Flags]
          public enum SHCIDS : uint
          {
          SHCIDS_ALLFIELD S = 0x80000000,
          SHCIDS_CANONICA LONLY = 0x10000000,
          SHCIDS_BITMASK = 0xFFFF0000,
          SHCIDS_COLUMNMA SK = 0x0000FFFF
          }

          [Flags()]
          public enum SFGAO : uint
          {
          SFGAO_CANCOPY = 0x000000001,
          SFGAO_CANMOVE = 0x000000002,
          SFGAO_CANLINK = 0x000000004,
          SFGAO_STORAGE = 0x000000008,
          SFGAO_CANRENAME = 0x00000010,
          SFGAO_CANDELETE = 0x00000020,
          SFGAO_HASPROPSH EET = 0x00000040,
          SFGAO_DROPTARGE T = 0x00000100,
          SFGAO_CAPABILIT YMASK = 0x00000177,
          SFGAO_ENCRYPTED = 0x00002000,
          SFGAO_ISSLOW = 0x00004000,
          SFGAO_GHOSTED = 0x00008000,
          SFGAO_LINK = 0x00010000,
          SFGAO_SHARE = 0x00020000,
          SFGAO_READONLY = 0x00040000,
          SFGAO_HIDDEN = 0x00080000,
          SFGAO_DISPLAYAT TRMASK = 0x000FC000,
          SFGAO_FILESYSAN CESTOR = 0x10000000,
          SFGAO_FOLDER = 0x20000000,
          SFGAO_FILESYSTE M = 0x40000000,
          SFGAO_HASSUBFOL DER = 0x80000000,
          SFGAO_CONTENTSM ASK = 0x80000000,
          SFGAO_VALIDATE = 0x01000000,
          SFGAO_REMOVABLE = 0x02000000,
          SFGAO_COMPRESSE D = 0x04000000,
          SFGAO_BROWSABLE = 0x08000000,
          SFGAO_NONENUMER ATED = 0x00100000,
          SFGAO_NEWCONTEN T = 0x00200000,
          SFGAO_CANMONIKE R = 0x00400000,
          SFGAO_HASSTORAG E = 0x00400000,
          SFGAO_STREAM = 0x00400000,
          SFGAO_STORAGEAN CESTOR = 0x00800000,
          SFGAO_STORAGECA PMASK = 0x70C50008
          }

          [Flags()]
          public enum SHGDN
          {
          SHGDN_NORMAL = 0,
          SHGDN_INFOLDER = 1,
          SHGDN_FORADDRES SBAR = 16384,
          SHGDN_FORPARSIN G = 32768
          }

          [StructLayout(La youtKind.Explic it)]
          public struct STRRET
          {
          [FieldOffset(0)]
          UInt32 uType;
          [FieldOffset(4)]
          IntPtr pOleStr;
          [FieldOffset(4)]
          IntPtr pStr;
          [FieldOffset(4)]
          UInt32 uOffset;
          [FieldOffset(4)]
          IntPtr cStr;
          }

          public enum SVUIA_STATUS
          {
          SVUIA_DEACTIVAT E = 0,
          SVUIA_ACTIVATE_ NOFOCUS = 1,
          SVUIA_ACTIVATE_ FOCUS = 2,
          SVUIA_INPLACEAC TIVATE = 3
          }

          [StructLayout(La youtKind.Sequen tial)]
          public struct FOLDERSETTINGS
          {
          public FOLDERFLAGS ViewMode;
          public FOLDERVIEWMODE fFlags;
          }

          [Flags]
          public enum FOLDERFLAGS
          {
          FWF_AUTOARRANGE = 0x1,
          FWF_ABBREVIATED NAMES = 0x2,
          FWF_SNAPTOGRID = 0x4,
          FWF_OWNERDATA = 0x8,
          FWF_BESTFITWIND OW = 0x10,
          FWF_DESKTOP = 0x20,
          FWF_SINGLESEL = 0x40,
          FWF_NOSUBFOLDER S = 0x80,
          FWF_TRANSPARENT = 0x100,
          FWF_NOCLIENTEDG E = 0x200,
          FWF_NOSCROLL = 0x400,
          FWF_ALIGNLEFT = 0x800,
          FWF_NOICONS = 0x1000,
          FWF_SHOWSELALWA YS = 0x2000,
          FWF_NOVISIBLE = 0x4000,
          FWF_SINGLECLICK ACTIVATE = 0x8000,
          FWF_NOWEBVIEW = 0x10000,
          FWF_HIDEFILENAM ES = 0x20000,
          FWF_CHECKSELECT = 0x40000
          }

          public enum FOLDERVIEWMODE
          {
          FVM_FIRST = 1,
          FVM_ICON = 1,
          FVM_SMALLICON = 2,
          FVM_LIST = 3,
          FVM_DETAILS = 4,
          FVM_THUMBNAIL = 5,
          FVM_TILE = 6,
          FVM_THUMBSTRIP = 7,
          FVM_LAST = 7
          }

          [ComImport]
          [InterfaceType(C omInterfaceType .InterfaceIsIUn known)]
          [Guid("000214E6-0000-0000-C000-000000000046")]
          public interface IShellFolder
          {
          [PreserveSig]
          Int32 ParseDisplayNam e(
          IntPtr hwnd,
          IntPtr pbc,
          [MarshalAs(Unman agedType.LPWStr )]
          string pszDisplayName,
          ref UInt32 pchEaten,
          out IntPtr ppidl,
          ref UInt32 pdwAttributes
          );
          [PreserveSig]
          Int32 EnumObjects(
          IntPtr hwnd,
          SHCONTF grfFlags,
          out IEnumIDList ppenumIDList
          );
          [PreserveSig]
          Int32 BindToObject(
          IntPtr pidl,
          IntPtr pbc,
          ref Guid riid,
          out IntPtr ppv
          );
          [PreserveSig]
          Int32 BindToStorage(
          IntPtr pidl,
          IntPtr pbc,
          ref Guid riid,
          out IntPtr ppv
          );
          [PreserveSig]
          Int32 CompareIDs(
          SHCIDS lParam,
          IntPtr pidl1,
          IntPtr pidl2
          );
          [PreserveSig]
          Int32 CreateViewObjec t(
          IntPtr hwndOwner,
          ref Guid riid,
          out IShellView ppv
          );
          [PreserveSig]
          Int32 GetAttributesOf (
          UInt32 cidl,
          [MarshalAs(Unman agedType.LPArra y, SizeParamIndex = 0)]
          IntPtr[] apidl,
          ref SFGAO rgfInOut
          );
          [PreserveSig]
          Int32 GetUIObjectOf(
          IntPtr hwndOwner,
          UInt32 cidl,
          IntPtr[] apidl,
          Guid riid,
          ref UInt32 rgfReserved,
          out IntPtr ppv
          );
          [PreserveSig]
          Int32 GetDisplayNameO f(
          IntPtr pidl,
          SHGDN uFlags,
          out STRRET pName
          );
          [PreserveSig]
          Int32 SetNameOf(
          IntPtr hwnd,
          IntPtr pidl,
          [MarshalAs(Unman agedType.LPWStr )]
          string pszName,
          UInt32 uFlags,
          out IntPtr ppidlOut
          );
          }

          [ComImportAttrib ute()]
          [GuidAttribute(" 000214F2-0000-0000-C000-000000000046")]
          [InterfaceTypeAt tribute(ComInte rfaceType.Inter faceIsIUnknown)]
          public interface IEnumIDList
          {
          [PreserveSig]
          int Next(
          int celt,
          ref IntPtr rgelt,
          out int pceltFetched
          );
          [PreserveSig]
          int Skip(int celt);
          [PreserveSig]
          int Reset();
          [PreserveSig]
          int Clone(ref IEnumIDList ppenum);
          }

          [ComImport()]
          [Guid("000214E3-0000-0000-C000-000000000046")]
          [InterfaceType(C omInterfaceType .InterfaceIsIUn known)]
          public interface IShellView
          {
          [PreserveSig]
          int GetWindow(out IntPtr phwnd);
          [PreserveSig]
          int ContextSensitiv eHelp(bool fEnterMode);
          [PreserveSig]
          int TranslateAccele ratorA(IntPtr pmsg);
          [PreserveSig]
          int EnableModeless( bool fEnable);
          [PreserveSig]
          int UIActivate(SVUI A_STATUS uState);
          [PreserveSig]
          int Refresh();
          [PreserveSig]
          int CreateViewWindo w(
          IShellView psvPrevious,
          ref FOLDERSETTINGS pfs,
          IShellBrowser psb,
          ref RECT prcView,
          out IntPtr phWnd
          );
          [PreserveSig]
          int DestroyViewWind ow();
          [PreserveSig]
          int GetCurrentInfo(
          ref FOLDERSETTINGS pfs
          );
          [PreserveSig]
          int AddPropertyShee tPages(
          long dwReserved,
          ref IntPtr pfnPtr,
          int lparam
          );
          [PreserveSig]
          int SaveViewState() ;
          [PreserveSig]
          int SelectItem(
          IntPtr pidlItem,
          uint uFlags
          );
          [PreserveSig]
          int GetItemObject(
          uint uItem,
          ref Guid riid,
          ref IntPtr ppv
          );
          }

          [ComImport()]
          [Guid("000214E2-0000-0000-C000-000000000046")]
          [InterfaceType(C omInterfaceType .InterfaceIsIUn known)]
          public interface IShellBrowser
          {
          [PreserveSig]
          int GetWindow(out IntPtr phwnd);
          [PreserveSig]
          int ContextSensitiv eHelp(bool fEnterMode);
          [PreserveSig]
          int InsertMenusSB(
          IntPtr hmenuShared,
          ref IntPtr lpMenuWidths
          );
          [PreserveSig]
          int SetMenuSB(
          IntPtr hmenuShared,
          IntPtr holemenuRes,
          IntPtr hwndActiveObjec t
          );
          [PreserveSig]
          int RemoveMenusSB(I ntPtr hmenuShared);
          [PreserveSig]
          int SetStatusTextSB (string pszStatusText);
          [PreserveSig]
          int EnableModelessS B(bool fEnable);
          [PreserveSig]
          int TranslateAccele ratorSB(
          IntPtr pmsg,
          short wID
          );
          [PreserveSig]
          int BrowseObject(
          IntPtr pidl,
          uint wFlags
          );
          [PreserveSig]
          int GetViewStateStr eam(
          long grfMode,
          ref UCOMIStream ppStrm
          );
          [PreserveSig]
          int GetControlWindo w(uint id, ref IntPtr phwnd);
          [PreserveSig]
          int SendControlMsg(
          uint id,
          uint uMsg,
          short wParam,
          long lParam,
          ref long pret
          );
          [PreserveSig]
          int QueryActiveShel lView(
          ref IShellView ppshv
          );
          [PreserveSig]
          int OnViewWindowAct ive(
          IShellView pshv
          );
          [PreserveSig]
          int SetToolbarItems (
          IntPtr lpButtons,
          uint nButtons,
          uint uFlags
          );
          }

          [DllImport("shel l32.dll", EntryPoint = "#18")]
          public static extern IntPtr ILClone(
          IntPtr pidl
          );

          [DllImport("shel l32.dll", EntryPoint = "#25")]
          public static extern IntPtr ILCombine(
          IntPtr pidlA,
          IntPtr pidlB
          );

          [DllImport("shel l32.dll", EntryPoint = "#17")]
          public static extern bool ILRemoveLastID(
          IntPtr pidl
          );

          [DllImport("shel l32.dll")]
          public static extern Int32 SHGetDesktopFol der(
          out IShellFolder ppshf
          );

          [DllImport("shel l32.dll")]
          public static extern Int32 SHGetFolderLoca tion(
          IntPtr hwndOwner,
          CSIDL nFolder,
          IntPtr hToken,
          UInt32 dwReserved,
          out IntPtr ppidl
          );

          [DllImport("shel l32.dll")]
          public static extern IntPtr SHGetFileInfo(
          string fileName,
          uint dwFileAttribute s,
          ref SHFILEINFO psfi,
          int cbSizeFileInfo,
          SHGFI flags
          );

          [DllImport("shel l32.dll")]
          public static extern IntPtr SHGetFileInfo(
          IntPtr pidl,
          uint dwFileAttribute s,
          ref SHFILEINFO psfi,
          int cbSizeFileInfo,
          SHGFI flags
          );

          [DllImport("shel l32.dll")]
          public static extern bool SHGetPathFromID List(
          IntPtr pidl,
          StringBuilder pszPath
          );



          }

          private static readonly
          NativeMethods.I ShellFolder c_desktopFolder ;
          private static readonly IntPtr c_desktopPidl;
          private IntPtr m_pidl;
          private string m_displayName;
          private string m_typeName;
          private string m_physicalPath;
          private NativeMethods.S FGAO m_attributes;

          public IntPtr Pidl
          {
          get {return m_pidl;}
          }

          public string DisplayName
          {
          get {return m_displayName;}
          }

          public string TypeName
          {
          get {return m_typeName;}
          }

          public string PhysicalPath
          {
          get {return m_physicalPath; }
          }

          public bool CanRename
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_CANR ENAME) != 0;
          }
          }

          public bool CanMove
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_CANM OVE) != 0;
          }
          }

          public bool CanDelete
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_CAND ELETE) != 0;
          }
          }

          public bool CanCopy
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_CANC OPY) != 0;
          }
          }

          public bool IsReadOnly
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_READ ONLY) != 0;
          }
          }

          public bool IsEncrypted
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_ENCR YPTED) != 0;
          }
          }

          public bool IsLink
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_LINK ) != 0;
          }
          }

          public bool IsHidden
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_HIDD EN) != 0;
          }
          }

          public bool IsSlow
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_ISSL OW) != 0;
          }
          }

          public bool IsGhosted
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_GHOS TED) != 0;
          }
          }

          public bool IsCompressed
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_COMP RESSED) != 0;
          }
          }

          public bool IsRemovable
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_REMO VABLE) != 0;
          }
          }

          public bool IsShared
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_SHAR E) != 0;
          }
          }

          public bool IsFolder
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_FOLD ER) != 0;
          }
          }

          public bool IsFileSystem
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_FILE SYSTEM) != 0;
          }
          }

          public bool HasSubfolders
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_HASS UBFOLDER) != 0;
          }
          }

          public bool IsBrowsable
          {
          get {
          return (m_attributes &
          NativeMethods.S FGAO.SFGAO_BROW SABLE) != 0;
          }
          }

          public bool IsDesktop
          {
          get
          {

          // Ask the desktop to determine if they are equal.
          return c_desktopFolder .CompareIDs(
          NativeMethods.S HCIDS.SHCIDS_CA NONICALONLY,
          m_pidl,
          c_desktopPidl
          ) == 0;

          } // End get

          }

          [SecurityPermiss ion(
          SecurityAction. LinkDemand,
          Flags=SecurityP ermissionFlag.U nmanagedCode)]
          static CGPidl()
          {

          // Get a reference to the desktop folder.
          NativeMethods.S HGetDesktopFold er(
          out c_desktopFolder
          );

          IntPtr hToken = new IntPtr(-1);

          // Get the pidl for the desktop folder.
          int hr = NativeMethods.S HGetFolderLocat ion(
          IntPtr.Zero,
          NativeMethods.C SIDL.CSIDL_DESK TOP,
          hToken,
          0,
          out c_desktopPidl
          );

          }

          public CGPidl()
          {

          }

          [SecurityPermiss ion(
          SecurityAction. LinkDemand,
          Flags=SecurityP ermissionFlag.U nmanagedCode)]
          public CGPidl(
          IntPtr pidl
          )
          {
          Open(pidl);
          }

          [SecurityPermiss ion(
          SecurityAction. LinkDemand,
          Flags=SecurityP ermissionFlag.U nmanagedCode)]
          public CGPidl(
          IntPtr parentPidl,
          IntPtr pidl
          )
          {
          Open(parentPidl , pidl);
          }

          [SecurityPermiss ion(
          SecurityAction. LinkDemand,
          Flags=SecurityP ermissionFlag.U nmanagedCode)]
          public CGPidl(
          Environment.Spe cialFolder specialFolder
          )
          {
          Open(specialFol der);
          }

          [SecurityPermiss ion(
          SecurityAction. LinkDemand,
          Flags=SecurityP ermissionFlag.U nmanagedCode)]
          public CGPidl(
          string fullPath
          )
          {
          Open(fullPath);
          }

          public void Dispose()
          {
          Close();
          }

          public override bool Equals(object obj)
          {

          // Recover a reference to the CGPidl object.
          CGPidl pidl = obj as CGPidl;

          // Sanity check the type first.
          if (pidl == null)
          return false;

          // Ask the desktop to determine if they are equal.
          return c_desktopFolder .CompareIDs(
          NativeMethods.S HCIDS.SHCIDS_CA NONICALONLY,
          m_pidl,
          pidl.m_pidl
          ) == 0;

          }

          public override int GetHashCode()
          {
          return base.GetHashCod e() ^ m_pidl.GetHashC ode();
          }

          public void Open(
          IntPtr pidl
          )
          {

          // Clone to pidl.
          m_pidl = NativeMethods.I LClone(pidl);

          // Initialize the object.
          InitializeObjec t();

          }

          [SecurityPermiss ion(
          SecurityAction. LinkDemand,
          Flags=SecurityP ermissionFlag.U nmanagedCode)]
          public void Open(
          IntPtr parentPidl,
          IntPtr pidl
          )
          {

          // Create a fully qualified pidl for the object.
          m_pidl = NativeMethods.I LCombine(
          parentPidl,
          pidl
          );

          // Initialize the object.
          InitializeObjec t();

          }

          [SecurityPermiss ion(
          SecurityAction. LinkDemand,
          Flags=SecurityP ermissionFlag.U nmanagedCode)]
          public void Open(
          Environment.Spe cialFolder specialFolder
          )
          {

          IntPtr hToken = new IntPtr(-1);

          // Get the pidl for the special folder.
          int hr = NativeMethods.S HGetFolderLocat ion(
          IntPtr.Zero,
          SpecialFolderTo CSIDL(specialFo lder),
          hToken,
          0,
          out m_pidl
          );

          // Did we fail?
          if (hr != 0)
          Marshal.ThrowEx ceptionForHR(hr );

          // Initialize the object.
          InitializeObjec t();

          }

          [SecurityPermiss ion(
          SecurityAction. LinkDemand,
          Flags=SecurityP ermissionFlag.U nmanagedCode)]
          public void Open(
          string fullPath
          )
          {

          uint attr = 0;
          uint pchEaten = 0;

          // Attempt to get a pidl to the object.
          int hr = c_desktopFolder .ParseDisplayNa me(
          IntPtr.Zero,
          IntPtr.Zero,
          fullPath,
          ref pchEaten,
          out m_pidl,
          ref attr
          );

          // Did we fail?
          if (hr != 0)
          Marshal.ThrowEx ceptionForHR(hr );

          // Initialize the object.
          InitializeObjec t();

          }

          public void Close()
          {

          // Should we cleanup the pidl?
          if (m_pidl != IntPtr.Zero)
          Marshal.FreeCoT askMem(m_pidl);

          m_pidl = IntPtr.Zero;

          }

          [SecurityPermiss ion(
          SecurityAction. LinkDemand,
          Flags=SecurityP ermissionFlag.U nmanagedCode)]
          public CGPidl GetParentFolder ()
          {

          // Sanity check the pidl before attempting to use it.
          if (m_pidl == IntPtr.Zero)
          return null;

          // The desktop folder doesn't have a parent.
          if (c_desktopFolde r.CompareIDs(
          NativeMethods.S HCIDS.SHCIDS_AL LFIELDS,
          m_pidl,
          c_desktopPidl
          ) == 0)
          return null;

          // Start by copying our pidl since we are about to
          // modify it to create a pidl for the parent.
          IntPtr parentPidl = NativeMethods.I LClone(m_pidl);

          // If we failed to remove the last item in the PIDL then
          // there really isn't any way to recover.
          if (!NativeMethods .ILRemoveLastID (parentPidl))
          {

          // Free the cloned pidl.
          Marshal.FreeCoT askMem(parentPi dl);
          parentPidl = IntPtr.Zero;

          return null;

          } // End if we failed to locate the parent.

          // Otherwise, create a CGPidl and return it.
          return new CGPidl(parentPi dl);

          }

          [SecurityPermiss ion(
          SecurityAction. LinkDemand,
          Flags=SecurityP ermissionFlag.U nmanagedCode)]
          public System.Collecti ons.ArrayList GetAncestors()
          {

          ArrayList list = new ArrayList();

          // Sanity check the pidl before attempting to use it.
          if (m_pidl == IntPtr.Zero)
          return list;

          CGPidl pidl = (CGPidl)Clone() ;

          // Loop and find the ancestors.
          while (pidl != null)
          {

          list.Add(pidl);
          pidl = pidl.GetParentF older();

          } // End while there are more ancestors.

          // Return the family tree.
          return list;

          }

          [SecurityPermiss ion(
          SecurityAction. LinkDemand,
          Flags=SecurityP ermissionFlag.U nmanagedCode)]
          private void InitializeObjec t()
          {

          NativeMethods.S HFILEINFO shfi =
          new NativeMethods.S HFILEINFO();

          // Attempt to get the information for the shell object.
          NativeMethods.S HGetFileInfo(
          m_pidl,
          0,
          ref shfi,
          Marshal.SizeOf( shfi),
          NativeMethods.S HGFI.SHGFI_PIDL |
          NativeMethods.S HGFI.SHGFI_DISP LAYNAME |
          NativeMethods.S HGFI.SHGFI_ATTR IBUTES |
          NativeMethods.S HGFI.SHGFI_TYPE NAME
          );

          // Save the information.
          m_displayName = shfi.szDisplayN ame;
          m_typeName = shfi.szTypeName ;
          m_attributes = (NativeMethods. SFGAO)shfi.dwAt tributes;

          StringBuilder sb = new StringBuilder(2 60);

          // Get the physical path to the shell object.
          NativeMethods.S HGetPathFromIDL ist(
          m_pidl,
          sb
          );

          // Save the path.
          m_physicalPath = sb.ToString();

          }

          private static NativeMethods.C SIDL SpecialFolderTo CSIDL(
          Environment.Spe cialFolder sf
          )
          {

          switch (sf)
          {

          case Environment.Spe cialFolder.Appl icationData :

          return NativeMethods.C SIDL.CSIDL_APPD ATA;

          case Environment.Spe cialFolder.Comm onApplicationDa ta :

          return NativeMethods.C SIDL.CSIDL_COMM ON_APPDATA;

          case Environment.Spe cialFolder.Comm onProgramFiles :

          return NativeMethods.C SIDL.CSIDL_COMM ON_PROGRAMS;

          case Environment.Spe cialFolder.Cook ies :

          return NativeMethods.C SIDL.CSIDL_COOK IES;

          case Environment.Spe cialFolder.Desk top :

          return NativeMethods.C SIDL.CSIDL_DESK TOP;

          case Environment.Spe cialFolder.Desk topDirectory :

          return NativeMethods.C SIDL.CSIDL_DESK TOPDIRECTORY;

          case Environment.Spe cialFolder.Favo rites :

          return NativeMethods.C SIDL.CSIDL_FAVO RITES;

          case Environment.Spe cialFolder.Hist ory :

          return NativeMethods.C SIDL.CSIDL_HIST ORY;

          case Environment.Spe cialFolder.Inte rnetCache :

          return NativeMethods.C SIDL.CSIDL_INTE RNET_CACHE;

          case Environment.Spe cialFolder.Loca lApplicationDat a :

          return NativeMethods.C SIDL.CSIDL_LOCA L_APPDATA;

          case Environment.Spe cialFolder.MyCo mputer :

          return NativeMethods.C SIDL.CSIDL_DRIV ES;

          case Environment.Spe cialFolder.MyMu sic :

          return NativeMethods.C SIDL.CSIDL_MYMU SIC;

          case Environment.Spe cialFolder.MyPi ctures :

          return NativeMethods.C SIDL.CSIDL_MYPI CTURES;

          case Environment.Spe cialFolder.Pers onal :

          return NativeMethods.C SIDL.CSIDL_PERS ONAL;

          case Environment.Spe cialFolder.Prog ramFiles :

          return NativeMethods.C SIDL.CSIDL_PROG RAM_FILES;

          case Environment.Spe cialFolder.Prog rams :

          return NativeMethods.C SIDL.CSIDL_PROG RAMS;

          case Environment.Spe cialFolder.Rece nt :

          return NativeMethods.C SIDL.CSIDL_RECE NT;

          case Environment.Spe cialFolder.Send To :

          return NativeMethods.C SIDL.CSIDL_SEND TO;

          case Environment.Spe cialFolder.Star tMenu :

          return NativeMethods.C SIDL.CSIDL_STAR TMENU;

          case Environment.Spe cialFolder.Star tup :

          return NativeMethods.C SIDL.CSIDL_STAR TUP;

          case Environment.Spe cialFolder.Syst em :

          return NativeMethods.C SIDL.CSIDL_SYST EM;

          case Environment.Spe cialFolder.Temp lates :

          return NativeMethods.C SIDL.CSIDL_TEMP LATES;

          } // End switch

          return NativeMethods.C SIDL.CSIDL_DESK TOP;

          }

          public int CompareTo(objec t obj)
          {

          // Recover a reference to the CGPidl object.
          CGPidl pidl = obj as CGPidl;

          // Sanity check the type first.
          if (pidl == null)
          return 0;

          // Ask the shell to do the compare.
          return c_desktopFolder .CompareIDs(
          NativeMethods.S HCIDS.SHCIDS_CA NONICALONLY,
          pidl.Pidl,
          m_pidl
          );

          }

          public object Clone()
          {

          // Clone the object.
          CGPidl pidl = new CGPidl();
          pidl.m_pidl = NativeMethods.I LClone(m_pidl);
          pidl.m_displayN ame = m_displayName;
          pidl.m_typeName = m_typeName;
          pidl.m_attribut es = m_attributes;
          pidl.m_physical Path = m_physicalPath;

          // Return the clone.
          return pidl;

          }

          }

          }

          Comment

          • =?Utf-8?B?Q2lhcmFuIE8nJ0Rvbm5lbGw=?=

            #6
            Re: Getting the NAME (not path) of a special folder.

            I have posted a new and improved version of this using the shell interface
            for windows.
            its on my blog:
            http://wannabedevelope r.spaces.live.c om/blog/cns!9051A75A660 C95FA!185.entry

            --
            Ciaran O''Donnell



            "Ciaran O''Donnell" wrote:
            Here is the rest of the code
            --
            Ciaran O''Donnell

            >
            >
            [ComVisible(fals e)]
            public sealed class CGPidl : IDisposable, IComparable, ICloneable
            {
            >
            private static class NativeMethods
            {
            >
            [StructLayout(La youtKind.Sequen tial)]
            public struct RECT
            {
            public int left;
            public int top;
            public int right;
            public int bottom;
            >
            public RECT(
            Rectangle r
            )
            {
            left = r.Left;
            top = r.Top;
            right = r.Right;
            bottom = r.Bottom;
            }
            >
            }
            >
            [Flags]
            public enum CSIDL
            {
            CSIDL_FLAG_CREA TE = 0x8000,
            CSIDL_ADMINTOOL S = 0x0030,
            CSIDL_ALTSTARTU P = 0x001d,
            CSIDL_APPDATA = 0x001a,
            CSIDL_BITBUCKET = 0x000a,
            CSIDL_CDBURN_AR EA = 0x003b,
            CSIDL_COMMON_AD MINTOOLS = 0x002f,
            CSIDL_COMMON_AL TSTARTUP = 0x001e,
            CSIDL_COMMON_AP PDATA = 0x0023,
            CSIDL_COMMON_DE SKTOPDIRECTORY = 0x0019,
            CSIDL_COMMON_DO CUMENTS = 0x002e,
            CSIDL_COMMON_FA VORITES = 0x001f,
            CSIDL_COMMON_MU SIC = 0x0035,
            CSIDL_COMMON_PI CTURES = 0x0036,
            CSIDL_COMMON_PR OGRAMS = 0x0017,
            CSIDL_COMMON_ST ARTMENU = 0x0016,
            CSIDL_COMMON_ST ARTUP = 0x0018,
            CSIDL_COMMON_TE MPLATES = 0x002d,
            CSIDL_COMMON_VI DEO = 0x0037,
            CSIDL_CONTROLS = 0x0003,
            CSIDL_COOKIES = 0x0021,
            CSIDL_DESKTOP = 0x0000,
            CSIDL_DESKTOPDI RECTORY = 0x0010,
            CSIDL_DRIVES = 0x0011,
            CSIDL_FAVORITES = 0x0006,
            CSIDL_FONTS = 0x0014,
            CSIDL_HISTORY = 0x0022,
            CSIDL_INTERNET = 0x0001,
            CSIDL_INTERNET_ CACHE = 0x0020,
            CSIDL_LOCAL_APP DATA = 0x001c,
            CSIDL_MYDOCUMEN TS = 0x000c,
            CSIDL_MYMUSIC = 0x000d,
            CSIDL_MYPICTURE S = 0x0027,
            CSIDL_MYVIDEO = 0x000e,
            CSIDL_NETHOOD = 0x0013,
            CSIDL_NETWORK = 0x0012,
            CSIDL_PERSONAL = 0x0005,
            CSIDL_PRINTERS = 0x0004,
            CSIDL_PRINTHOOD = 0x001b,
            CSIDL_PROFILE = 0x0028,
            CSIDL_PROFILES = 0x003e,
            CSIDL_PROGRAM_F ILES = 0x0026,
            CSIDL_PROGRAM_F ILES_COMMON = 0x002b,
            CSIDL_PROGRAMS = 0x0002,
            CSIDL_RECENT = 0x0008,
            CSIDL_SENDTO = 0x0009,
            CSIDL_STARTMENU = 0x000b,
            CSIDL_STARTUP = 0x0007,
            CSIDL_SYSTEM = 0x0025,
            CSIDL_TEMPLATES = 0x0015,
            CSIDL_WINDOWS = 0x0024
            }
            >
            [StructLayout(La youtKind.Sequen tial)]
            public struct SHFILEINFO
            {
            public IntPtr hIcon;
            public Int32 iIcon;
            public UInt32 dwAttributes;
            [MarshalAs(Unman agedType.ByValT Str, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(Unman agedType.ByValT Str, SizeConst = 80)]
            public string szTypeName;
            };
            >
            public enum SHCONTF
            {
            SHCONTF_FOLDERS = 0x0020,
            SHCONTF_NONFOLD ERS = 0x0040,
            SHCONTF_INCLUDE HIDDEN = 0x0080,
            SHCONTF_INIT_ON _FIRST_NEXT = 0x0100,
            SHCONTF_NETPRIN TERSRCH = 0x0200,
            SHCONTF_SHAREAB LE = 0x0400,
            SHCONTF_STORAGE = 0x0800
            }
            >
            [Flags]
            public enum SHGFI
            {
            SHGFI_ICON = 0x000000100,
            SHGFI_DISPLAYNA ME = 0x000000200,
            SHGFI_TYPENAME = 0x000000400,
            SHGFI_ATTRIBUTE S = 0x000000800,
            SHGFI_ICONLOCAT ION = 0x000001000,
            SHGFI_EXETYPE = 0x000002000,
            SHGFI_SYSICONIN DEX = 0x000004000,
            SHGFI_LINKOVERL AY = 0x000008000,
            SHGFI_SELECTED = 0x000010000,
            SHGFI_ATTR_SPEC IFIED = 0x000020000,
            SHGFI_LARGEICON = 0x000000000,
            SHGFI_SMALLICON = 0x000000001,
            SHGFI_OPENICON = 0x000000002,
            SHGFI_SHELLICON SIZE = 0x000000004,
            SHGFI_PIDL = 0x000000008,
            SHGFI_USEFILEAT TRIBUTES = 0x000000010,
            SHGFI_ADDOVERLA YS = 0x000000020,
            SHGFI_OVERLAYIN DEX = 0x000000040
            }
            >
            [Flags]
            public enum SHCIDS : uint
            {
            SHCIDS_ALLFIELD S = 0x80000000,
            SHCIDS_CANONICA LONLY = 0x10000000,
            SHCIDS_BITMASK = 0xFFFF0000,
            SHCIDS_COLUMNMA SK = 0x0000FFFF
            }
            >
            [Flags()]
            public enum SFGAO : uint
            {
            SFGAO_CANCOPY = 0x000000001,
            SFGAO_CANMOVE = 0x000000002,
            SFGAO_CANLINK = 0x000000004,
            SFGAO_STORAGE = 0x000000008,
            SFGAO_CANRENAME = 0x00000010,
            SFGAO_CANDELETE = 0x00000020,
            SFGAO_HASPROPSH EET = 0x00000040,
            SFGAO_DROPTARGE T = 0x00000100,
            SFGAO_CAPABILIT YMASK = 0x00000177,
            SFGAO_ENCRYPTED = 0x00002000,
            SFGAO_ISSLOW = 0x00004000,
            SFGAO_GHOSTED = 0x00008000,
            SFGAO_LINK = 0x00010000,
            SFGAO_SHARE = 0x00020000,
            SFGAO_READONLY = 0x00040000,
            SFGAO_HIDDEN = 0x00080000,
            SFGAO_DISPLAYAT TRMASK = 0x000FC000,
            SFGAO_FILESYSAN CESTOR = 0x10000000,
            SFGAO_FOLDER = 0x20000000,
            SFGAO_FILESYSTE M = 0x40000000,
            SFGAO_HASSUBFOL DER = 0x80000000,
            SFGAO_CONTENTSM ASK = 0x80000000,
            SFGAO_VALIDATE = 0x01000000,
            SFGAO_REMOVABLE = 0x02000000,
            SFGAO_COMPRESSE D = 0x04000000,
            SFGAO_BROWSABLE = 0x08000000,
            SFGAO_NONENUMER ATED = 0x00100000,
            SFGAO_NEWCONTEN T = 0x00200000,
            SFGAO_CANMONIKE R = 0x00400000,
            SFGAO_HASSTORAG E = 0x00400000,
            SFGAO_STREAM = 0x00400000,
            SFGAO_STORAGEAN CESTOR = 0x00800000,
            SFGAO_STORAGECA PMASK = 0x70C50008
            }
            >
            [Flags()]
            public enum SHGDN
            {
            SHGDN_NORMAL = 0,
            SHGDN_INFOLDER = 1,
            SHGDN_FORADDRES SBAR = 16384,
            SHGDN_FORPARSIN G = 32768
            }
            >
            [StructLayout(La youtKind.Explic it)]
            public struct STRRET
            {
            [FieldOffset(0)]
            UInt32 uType;
            [FieldOffset(4)]
            IntPtr pOleStr;
            [FieldOffset(4)]
            IntPtr pStr;
            [FieldOffset(4)]
            UInt32 uOffset;
            [FieldOffset(4)]
            IntPtr cStr;
            }
            >
            public enum SVUIA_STATUS
            {
            SVUIA_DEACTIVAT E = 0,
            SVUIA_ACTIVATE_ NOFOCUS = 1,
            SVUIA_ACTIVATE_ FOCUS = 2,
            SVUIA_INPLACEAC TIVATE = 3
            }
            >
            [StructLayout(La youtKind.Sequen tial)]
            public struct FOLDERSETTINGS
            {
            public FOLDERFLAGS ViewMode;
            public FOLDERVIEWMODE fFlags;
            }
            >
            [Flags]
            public enum FOLDERFLAGS
            {
            FWF_AUTOARRANGE = 0x1,
            FWF_ABBREVIATED NAMES = 0x2,
            FWF_SNAPTOGRID = 0x4,
            FWF_OWNERDATA = 0x8,
            FWF_BESTFITWIND OW = 0x10,
            FWF_DESKTOP = 0x20,
            FWF_SINGLESEL = 0x40,
            FWF_NOSUBFOLDER S = 0x80,
            FWF_TRANSPARENT = 0x100,
            FWF_NOCLIENTEDG E = 0x200,
            FWF_NOSCROLL = 0x400,
            FWF_ALIGNLEFT = 0x800,
            FWF_NOICONS = 0x1000,
            FWF_SHOWSELALWA YS = 0x2000,
            FWF_NOVISIBLE = 0x4000,
            FWF_SINGLECLICK ACTIVATE = 0x8000,
            FWF_NOWEBVIEW = 0x10000,
            FWF_HIDEFILENAM ES = 0x20000,
            FWF_CHECKSELECT = 0x40000
            }
            >
            public enum FOLDERVIEWMODE
            {
            FVM_FIRST = 1,
            FVM_ICON = 1,
            FVM_SMALLICON = 2,
            FVM_LIST = 3,
            FVM_DETAILS = 4,
            FVM_THUMBNAIL = 5,
            FVM_TILE = 6,
            FVM_THUMBSTRIP = 7,
            FVM_LAST = 7
            }
            >
            [ComImport]
            [InterfaceType(C omInterfaceType .InterfaceIsIUn known)]
            [Guid("000214E6-0000-0000-C000-000000000046")]
            public interface IShellFolder
            {
            [PreserveSig]
            Int32 ParseDisplayNam e(
            IntPtr hwnd,
            IntPtr pbc,
            [MarshalAs(Unman agedType.LPWStr )]
            string pszDisplayName,
            ref UInt32 pchEaten,
            out IntPtr ppidl,
            ref UInt32 pdwAttributes
            );
            [PreserveSig]
            Int32 EnumObjects(
            IntPtr hwnd,
            SHCONTF grfFlags,
            out IEnumIDList ppenumIDList
            );
            [PreserveSig]
            Int32 BindToObject(
            IntPtr pidl,
            IntPtr pbc,
            ref Guid riid,
            out IntPtr ppv
            );
            [PreserveSig]
            Int32 BindToStorage(
            IntPtr pidl,
            IntPtr pbc,
            ref Guid riid,
            out IntPtr ppv
            );
            [PreserveSig]
            Int32 CompareIDs(
            SHCIDS lParam,
            IntPtr pidl1,
            IntPtr pidl2
            );
            [PreserveSig]

            Comment

            Working...