C# Winforms open folder and select the specified file and open file

Lionsure 2020-08-12 Original by the website

Sometimes it is necessary to open a folder and select a specified file, and sometimes only need to open a specified file in the process of Winforms program development. For these requirements, C# provides corresponding implementation methods, that is, use the Process.Start() method. There are two ways to implement this method, one is to create an object first, and then set the arguments through properties; the other is to call this method directly (implemented in one sentence); for the convenience of everyone, the article will list the two methods specific implementation code.

 

1. C# Winforms open folder and select the specified file

Method 1: Call Process.Start() directly

First need to reference "using System.Diagnostics;", the specific implementation code:

/// <summary>
       /// C# Winform open folder(Open window)
       /// </summary>
       /// <param name="path">Path</param>

       public void OpenFolder(string path)
       {
              Process.Start("Explorer.exe", path);//There is DBCS in the path, you need to add double quotes
       }

Explorer.exe is not case-sensitive, and it is not necessary to write .exe, that is, just write explorer.

Call: OpenFolder( @"G:\xq\");

 

/// <summary>
       /// C# Winforms open folder and select the specified file
       /// </summary>
       /// <param name="path">Path</param>
       /// <param name="fileName">File name</param>

       public void OpenFolderSelectFile(string path, string fileName)
       {
              //There are DBCS in the path and file name, and double quotes are required
              Process.Start("Explorer.exe", "/select," + path + fileName);
       }

Call: OpenFolderSelectFile( @"G:\xq\", "test.txt");

 

Method 2: Create a new ProcessStartInfo object

/// <summary>
       /// C# Winforms open folder and select the specified file
       /// </summary>
       /// <param name="pathFile">Path(including file name)</param>

       public void OpenFolderSelectFiles(string pathFile)
       {
              ProcessStartInfo psi = new ProcessStartInfo("Explorer.exe");
              psi.Arguments = " /select," + pathFile;//Set arguments
              Process.Start(psi);
       }

Call:

OpenFolderSelectFiles(@"E:\Txts\notepad.exe");//Open the folder where "My Documents" is located and select it

OpenFolderSelectFiles(@"C:\Windows\notepad.exe");//Open the Windows folder and select notepad.exe

OpenFolderSelectFiles(@"G:\xq\text.txt");//Open the xq folder and select text.txt

 

 

2. C# Winform open file

Open a file the same as opening a folder in C#, the specific code is as follows:

using System.Diagnostics;

public void OpenFile(string filePath)
       {
              Process.Start("explorer.exe", filePath);
       }

Call: OpenFile(@"G:\xq\text.txt");