Tuesday, August 30, 2005

Opening folders with C# is easy, sometimes you just want the path to the folder so you can read, write or access files but sometimes you want to open the folder for the user to see visually.

To open the Program Files folder for the user you would use the following code:

//Use the Environment.SpecialFolder.ProgramFiles

//to get the path to Program Files in case it

//isn't stored on the C: drive.

string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

//Get the Windows directory

string windir = Environment.GetEnvironmentVariable("WINDIR");

System.Diagnostics.Process prc = new System.Diagnostics.Process();

//Use the Windows Explorer to view the Program Files directory

prc.StartInfo.FileName = windir + @".exe";

prc.StartInfo.Arguments = path;

prc.Start();

 

A couple notes about the preceeding code:

Explorer.exe is located in the Windows directory which on my computer is located in C:\WINDOWS

The first line gets the path to the Program Files directory:

string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

The second line gets the Windows directory using the System Environment variable. You can look at where this is set

1. Go to the Desktop and right click on My Computer, go to properties.

2. Click the Advanced tab.

3. On the Advanced tab click on the Environment Variables button

4. It is located in the System Variables section:

 

Then using the System.Diagnostics.Process namespace the code creates a process to start Windows Explorer from the Windows directory and passes the path to Program Files as an argument:

System.Diagnostics.Process prc = new System.Diagnostics.Process();

//Use the Windows Explorer to view the Program Files directory

prc.StartInfo.FileName = windir + @".exe";

prc.StartInfo.Arguments = path;

prc.Start();

 

You can essentially replace the Program Files directory with any directory your computer to open up that directory.

Tuesday, August 30, 2005 8:24:07 PM (GMT Standard Time, UTC+00:00)  #    Comments [1]  | 

Theme design by Jelle Druyts

Pick a theme: