Exemplo n.º 1
0
        public static string GetDirectoryViaBrowseDialog(this IVsUIShell2 shell, IntPtr parentWindow, Guid persistenceSlot, string title, string initialDirectory, bool overridePersistedInitialDirectory)
        {
            if (shell == null)
            {
                throw new ArgumentNullException("shell");
            }
            if (title == null)
            {
                throw new ArgumentNullException("title");
            }

            const int MaxDirName    = 10000;
            IntPtr    dirNameBuffer = Marshal.AllocCoTaskMem((MaxDirName + 1) * sizeof(char));

            try
            {
                VSBROWSEINFOW[] browse = new VSBROWSEINFOW[]
                {
                    new VSBROWSEINFOW
                    {
                        pwzDlgTitle   = title,
                        dwFlags       = (uint)BrowseInfoFlags.ReturnOnlyFileSystemDirectories,
                        hwndOwner     = parentWindow,
                        pwzInitialDir = GetInitialDirectoryToUse(initialDirectory, overridePersistedInitialDirectory, persistenceSlot),
                        nMaxDirName   = MaxDirName,
                        lStructSize   = (uint)Marshal.SizeOf(typeof(VSBROWSEINFOW)),
                        pwzDirName    = dirNameBuffer,
                        dwHelpTopic   = 0
                    }
                };

                string             helpTopic       = string.Empty;
                string             openButtonLabel = null;
                string             ceilingDir      = null;
                VSNSEBROWSEINFOW[] nseBrowseInfo   = null;

                ErrorHandler.ThrowOnFailure(shell.GetDirectoryViaBrowseDlgEx(browse, helpTopic, openButtonLabel, ceilingDir, nseBrowseInfo));
                string folder = Marshal.PtrToStringUni(browse[0].pwzDirName);
                if (!string.IsNullOrEmpty(folder))
                {
                    PersistLastUseDirectory(persistenceSlot, folder);
                }

                return(folder);
            }
            catch (COMException ex) when(ex.ErrorCode == VSConstants.OLE_E_PROMPTSAVECANCELLED)
            {
            }
            finally
            {
                if (dirNameBuffer != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(dirNameBuffer);
                    dirNameBuffer = IntPtr.Zero;
                }
            }

            return(null);
        }