탐색기에서 폴더 열기 및 파일 선택


150

탐색기에서 파일을 선택한 상태로 폴더를 열려고합니다.

다음 코드는 파일을 찾을 수 없음 예외를 생성합니다.

System.Diagnostics.Process.Start(
    "explorer.exe /select," 
    + listView1.SelectedItems[0].SubItems[1].Text + "\\" 
    + listView1.SelectedItems[0].Text);

C #에서이 명령을 실행하려면 어떻게해야합니까?

답변:


51

이 방법을 사용하십시오 :

Process.Start(String, String)

첫 번째 인수는 응용 프로그램 (explorer.exe)이고 두 번째 인수는 실행하는 응용 프로그램의 인수입니다.

예를 들면 다음과 같습니다.

CMD에서 :

explorer.exe -p

C #에서 :

Process.Start("explorer.exe", "-p")

32
이 사무엘 Yangs 대답과 같은 파일을 선택하지 않습니다
— HENON

-p는 파일을 선택하기에 충분하지 않습니다
— Jek

327
// suppose that we have a test.txt at E:\
string filePath = @"E:\test.txt";
if (!File.Exists(filePath))
{
    return;
}

// combine the arguments together
// it doesn't matter if there is a space after ','
string argument = "/select, \"" + filePath +"\"";

System.Diagnostics.Process.Start("explorer.exe", argument);

1
그것은 나에게 중요했습니다 :) 그것은 디렉토리를 열뿐만 아니라 특정 파일을 선택했습니다 :) 감사합니다
— InfantPro'Aravind '

2
그것은 매력처럼 작동하지만 어떤 아이디어가 여러 파일에 대해 어떻게 할 수 있습니까?
— Pankaj

7
내 파일 경로에 슬래시를 사용하면 파일 경로가있는 / select 인수가 작동하지 않는 것 같습니다. 따라서 filePath = filePath.Replace ( '/', '\\');
— Victor Chelaru

6
다른 곳에서 언급했듯이 경로는 따옴표로 묶어야합니다. 이렇게하면 쉼표가 포함 된 디렉토리 또는 파일 이름에 문제가 발생하지 않습니다.
— 카가 나르

4
파일에 쉼표가 포함되어 있기 때문에 때로는 위의 접근 방식이 작동하지 않는 문제에 대해 싸우고있었습니다. 내가 Kaganar의 의견을 읽었다면 그것은 한 시간의 작업을 절약했을 것입니다. Samuel Yang은 위 코드를 다음과 같이 수정하도록 촉구합니다 : string argument = @ "/ select"+ "\" "+ filePath +"\ ""
— Wayne Lo

34

경로에 쉼표가 포함되어 있으면 Process.Start (ProcessStartInfo)를 사용할 때 경로를 따옴표로 묶어야합니다.

그러나 Process.Start (string, string)를 사용할 때는 작동하지 않습니다. Process.Start (string, string)은 실제로 인수 내부의 따옴표를 제거하는 것처럼 보입니다.

다음은 저에게 적합한 간단한 예입니다.

string p = @"C:\tmp\this path contains spaces, and,commas\target.txt";
string args = string.Format("/e, /select, \"{0}\"", p);

ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "explorer";
info.Arguments = args;
Process.Start(info);

이것이 정답입니다. 다양한 실패 (권리 문제, 잘못된 경로 등)에 대한 적절한 예외 처리 기능이 부족합니다.
— AFract

이것은 정답이며, 받아 들여진 답변이 효과가 없으며, Yang의 답변도 효과가 없습니다.
— VK

31

파일 이름에 공백이 포함되어 있으면 내 2 센트 만 사용할 수 있습니다 (예 : "c : \ My File Contains Spaces.txt"). 파일 이름을 따옴표로 묶어야합니다. 그렇지 않으면 탐색기에서 othe 단어가 다른 인수라고 가정합니다.

string argument = "/select, \"" + filePath +"\"";

4
사실은 아닙니다. @Samuel 양의 예는 공간 (테스트 Win7에)와 경로와 함께 작동
— 코티 크리스텐슨

8
Phil Hustwick의 답변을 읽으십시오. 그럼에도 불구하고 왜 인용을
— 해야하는지

18

사무엘 양의 대답이 저를 넘어 뜨 렸습니다. 여기에 3 센트의 가치가 있습니다.

Adrian Hum이 옳습니다. 파일 이름을 따옴표로 묶어야합니다. zourtney가 지적한 것처럼 공백을 처리 할 수 ​​없기 때문에 파일 이름의 쉼표 (및 다른 문자)를 별도의 인수로 인식하기 때문입니다. Adrian Hum이 제안한 것처럼 보일 것입니다.

string argument = "/select, \"" + filePath +"\"";

1
그리고 그것이 filePath포함 "되어 있지 않은지 확인하십시오 . 이 문자는 Windows 시스템에서는 불법이지만 POSIXish 시스템과 같은 다른 모든 시스템에서는 허용되므로 이식성을 원한다면 더 많은 코드가 필요합니다.
— binki

14

인수 와 함께 Process.Starton explorer.exe을 사용하면 /select길이가 120 자 미만인 경로에 대해서만 작동합니다.

모든 경우에 작동하려면 기본 Windows 방법을 사용해야했습니다.

[DllImport("shell32.dll", SetLastError = true)]
public static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, uint dwFlags);

[DllImport("shell32.dll", SetLastError = true)]
public static extern void SHParseDisplayName([MarshalAs(UnmanagedType.LPWStr)] string name, IntPtr bindingContext, [Out] out IntPtr pidl, uint sfgaoIn, [Out] out uint psfgaoOut);

public static void OpenFolderAndSelectItem(string folderPath, string file)
{
    IntPtr nativeFolder;
    uint psfgaoOut;
    SHParseDisplayName(folderPath, IntPtr.Zero, out nativeFolder, 0, out psfgaoOut);

    if (nativeFolder == IntPtr.Zero)
    {
        // Log error, can't find folder
        return;
    }

    IntPtr nativeFile;
    SHParseDisplayName(Path.Combine(folderPath, file), IntPtr.Zero, out nativeFile, 0, out psfgaoOut);

    IntPtr[] fileArray;
    if (nativeFile == IntPtr.Zero)
    {
        // Open the folder without the file selected if we can't find the file
        fileArray = new IntPtr[0];
    }
    else
    {
        fileArray = new IntPtr[] { nativeFile };
    }

    SHOpenFolderAndSelectItems(nativeFolder, (uint)fileArray.Length, fileArray, 0);

    Marshal.FreeCoTaskMem(nativeFolder);
    if (nativeFile != IntPtr.Zero)
    {
        Marshal.FreeCoTaskMem(nativeFile);
    }
}

이것은 하나의 폴더를 재사용하는 데 도움이되었습니다. Process.Start ( "explorer.exe", "/ select xxx")는 매번 새 폴더를 엽니 다!
— Mitkins

이것은 sfgao에 대한 플래그를 생성하고 uint 대신 enum을 전달합니다
— L.Trabacchin

작은 문제에도 불구하고 작동합니다. 폴더를 처음 열면 강조 표시되지 않습니다. 버튼 클릭 방법 내에서 이것을 호출하고 버튼을 다시 클릭하면 폴더가 열리면 선택한 파일 / 폴더가 강조 표시됩니다. 무엇이 문제 일 수 있습니까?
— Sach

13

"/select,c:\file.txt"를 사용하십시오.

공백 대신 / select 뒤에 쉼표가 있어야합니다.


6

Start 메소드의 두 번째 매개 변수에 전달할 인수 ( "/ select etc")를 넣어야합니다.


5
string windir = Environment.GetEnvironmentVariable("windir");
if (string.IsNullOrEmpty(windir.Trim())) {
    windir = "C:\\Windows\\";
}
if (!windir.EndsWith("\\")) {
    windir += "\\";
}    

FileInfo fileToLocate = null;
fileToLocate = new FileInfo("C:\\Temp\\myfile.txt");

ProcessStartInfo pi = new ProcessStartInfo(windir + "explorer.exe");
pi.Arguments = "/select, \"" + fileToLocate.FullName + "\"";
pi.WindowStyle = ProcessWindowStyle.Normal;
pi.WorkingDirectory = windir;

//Start Process
Process.Start(pi)

5

파일을 찾을 수없는 가장 큰 이유는 공백이있는 경로입니다. 예를 들어 "explorer / select, c : \ space space \ space.txt"를 찾을 수 없습니다.

경로 앞뒤에 큰 따옴표를 추가하십시오.

explorer /select,"c:\space space\space.txt"

또는 C #에서 동일한 작업을 수행하십시오.

System.Diagnostics.Process.Start("explorer.exe","/select,\"c:\space space\space.txt\"");

1

약간 과잉 일 수 있지만 편의 기능을 좋아하므로 다음 중 하나를 수행하십시오.

    public static void ShowFileInExplorer(FileInfo file) {
        StartProcess("explorer.exe", null, "/select, "+file.FullName.Quote());
    }
    public static Process StartProcess(FileInfo file, params string[] args) => StartProcess(file.FullName, file.DirectoryName, args);
    public static Process StartProcess(string file, string workDir = null, params string[] args) {
        ProcessStartInfo proc = new ProcessStartInfo();
        proc.FileName = file;
        proc.Arguments = string.Join(" ", args);
        Logger.Debug(proc.FileName, proc.Arguments); // Replace with your logging function
        if (workDir != null) {
            proc.WorkingDirectory = workDir;
            Logger.Debug("WorkingDirectory:", proc.WorkingDirectory); // Replace with your logging function
        }
        return Process.Start(proc);
    }

이것은 <string> .Quote ()로 사용하는 확장 함수입니다.

static class Extensions
{
    public static string Quote(this string text)
    {
        return SurroundWith(text, "\"");
    }
    public static string SurroundWith(this string text, string surrounds)
    {
        return surrounds + text + surrounds;
    }
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.