폴더 브라우저 대화 상자 시작 위치 설정


113

폴더 브라우저 대화 상자의 초기 디렉토리를 비 특수 폴더로 설정하는 방법이 있습니까? 이것은 내가 현재 사용하고있는 것입니다

fdbLocation.RootFolder = Environment.SpecialFolder.Desktop;
하지만 다음과 같은 문자열에 저장 한 경로를 사용하고 싶습니다.
fdbLocation.RootFolder = myFolder;
이로 인해 " 'string'을 'System.Environment.SpecialFolder'로 변환 할 수 없습니다."라는 오류가 발생합니다.

답변:


188

ShowDialog를 호출하기 전에 SelectedPath 속성을 설정하기 만하면됩니다.

fdbLocation.SelectedPath = myFolder;

20
이 세트에 필요하다고 참고 RootFolderEnvironment.SpecialFolder.Desktop또는이 작동하지 않을 수 있습니다.
Mike Lowery 2014

3
아래 Chad Grants 답변을 참조하십시오. 그는 RootFolder가 설정되어야하며 SelectedPath가 작동하려면 해당 RootFolder 아래에 있어야한다고 올바르게 설명합니다 .
Dr Snooze

3
이것은 나를 위해 작동하지만 폴더에 초점을 맞추지 않습니다. 수동으로 아래로 스크롤하여 기본 폴더를 찾아야합니다. 표시 될 때 자동으로 초점을 설정하는 방법이 있습니까?
JoBaxter

2
그러나 이것은 설정과 동일 하지 않습니다RootFolder . RootFolder가 설정된 경우 지정된 폴더와 그 아래에있는 모든 하위 폴더 만 대화 상자에 나타납니다. SelectedPath단지 주어진 경로를 미리 선택합니다.
Jan Gassen

30

ShowDialog를 호출하기 전에 SelectedPath 속성을 설정합니다.

folderBrowserDialog1.SelectedPath = @"c:\temp\";
folderBrowserDialog1.ShowDialog();

C : \ Temp에서 시작합니다.


RootFolder ( SelectedPath is set to an absolute path that is a subfolder of RootFolder) 를 설정해야 합니까? 현재 동작 : C : \ Users \ Myusername \ Desktop을Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) 반환합니다 . 사용 로 가장 코드하는 것은 (로그온 유형 LOGON32_LOGON_INTERACTIVE 포함) 반환 빈 문자열을
Kiquenet

24
fldrDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)

"대화 상자를 표시하기 전에 SelectedPath 속성을 설정 한 경우 SelectedPath가 RootFolder의 하위 폴더 인 절대 경로로 설정되어 있으면이 경로가있는 폴더가 선택된 폴더가됩니다. RootFolder로 표시되는 쉘 네임 스페이스). "

MSDN-SelectedPath

"GetFolderPath 메서드는이 열거와 관련된 위치를 반환합니다. 이러한 폴더의 위치는 운영 체제마다 다른 값을 가질 수 있으며 사용자는 일부 위치를 변경할 수 있으며 위치는 지역화됩니다."

Re : Desktop 대 DesktopDirectory

데스크탑

"물리적 파일 시스템 위치가 아닌 논리적 데스크탑."

DesktopDirectory :

"데스크톱에 파일 개체를 물리적으로 저장하는 데 사용되는 디렉터리입니다.이 디렉터리를 가상 폴더 인 데스크톱 폴더 자체와 혼동하지 마십시오."

MSDN-특수 폴더 열거 형

MSDN-GetFolderPath


특수 경로의 경우 {{fldrDialog.RootFolder = Environment.SpecialFolder.DesktopDirectory}}를 수행 할 수 있습니다.
tymtam

완전한. 감사합니다. 핵심은 대화 상자가 열릴 때 SelectedPath를 가리 키도록하려면 SelectedPath가 RootFolder 아래에 있어야한다는 것입니다.
Dr Snooze

현재 동작 : C : \ Users \ Myusername \ Desktop을Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) 반환합니다 . 가장 코드 (LogonType LOGON32_LOGON_INTERACTIVE 사용)를 사용하면 빈 문자열이
Kiquenet

9

디렉토리 선택 경로를 설정하고 새 디렉토리를 검색하려면 :

dlgBrowseForLogDirectory.SelectedPath = m_LogDirectory;
if (dlgBrowseForLogDirectory.ShowDialog() == DialogResult.OK)
{
     txtLogDirectory.Text = dlgBrowseForLogDirectory.SelectedPath;
}

2

dotnet-snippets.de 에서 발견

리플렉션을 사용하면 실제 RootFolder가 작동하고 설정됩니다 !

using System;
using System.Reflection;
using System.Windows.Forms;

namespace YourNamespace
{
    public class RootFolderBrowserDialog
    {

        #region Public Properties

        /// <summary>
        ///   The description of the dialog.
        /// </summary>
        public string Description { get; set; } = "Chose folder...";

        /// <summary>
        ///   The ROOT path!
        /// </summary>
        public string RootPath { get; set; } = "";

        /// <summary>
        ///   The SelectedPath. Here is no initialization possible.
        /// </summary>
        public string SelectedPath { get; private set; } = "";

        #endregion Public Properties

        #region Public Methods

        /// <summary>
        ///   Shows the dialog...
        /// </summary>
        /// <returns>OK, if the user selected a folder or Cancel, if no folder is selected.</returns>
        public DialogResult ShowDialog()
        {
            var shellType = Type.GetTypeFromProgID("Shell.Application");
            var shell = Activator.CreateInstance(shellType);
            var folder = shellType.InvokeMember(
                             "BrowseForFolder", BindingFlags.InvokeMethod, null,
                             shell, new object[] { 0, Description, 0, RootPath, });
            if (folder is null)
            {
                return DialogResult.Cancel;
            }
            else
            {
                var folderSelf = folder.GetType().InvokeMember(
                                     "Self", BindingFlags.GetProperty, null,
                                     folder, null);
                SelectedPath = folderSelf.GetType().InvokeMember(
                                   "Path", BindingFlags.GetProperty, null,
                                   folderSelf, null) as string;
                // maybe ensure that SelectedPath is set
                return DialogResult.OK;
            }
        }

        #endregion Public Methods

    }
}

미리 설정된 폴더 항목을 확장 및 축소하는 방법을 알고 계십니까?
Goodies

나는 찬성 하고이 대답을 좋아하지만! msdn : docs.microsoft.com/en-us/windows/win32/shell/… 에 따라 사용자는이 루트 폴더에 설정된 것보다 더 높은 위치에서 탐색 할 수 없습니다 . 내가 사용한 해결 방법은 간단합니다. 기본 .net FolderBrowser를 사용하고 특수 폴더를 MyComputer로 설정 한 다음 선택한 경로를 설정합니다. 이렇게하면 선택한 경로 디렉토리까지 폴더가 확장되지만 스크롤되지는 않습니다.
Heriberto Lugo

0

제 경우에는 우연한 이중 탈출이었습니다.

이것은 작동합니다 :

SelectedPath = @"C:\Program Files\My Company\My product";

이것은하지 않습니다 :

SelectedPath = @"C:\\Program Files\\My Company\\My product";
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.