Click here to Skip to main content
15,881,139 members
Articles / Programming Languages / C#
Article

'which' utility for Windows

Rate me:
Please Sign up or sign in to vote.
3.30/5 (5 votes)
6 Jul 20051 min read 41.2K   574   21   11
Find all possible locations of an executable.

Sample Image - WinWhich.gif

Introduction

This simple program lets you find out the location of the executable that is being run. This was useful when running the 'java' executable and I was not sure which version of the JRE was actually being run.

Source code and Demo

The demo can be tested to find out the version of Notepad that is executed like this:

c:\temp\winwhich notepad
 1 C:\WINDOWS\system32\notepad.exe
 2 C:\WINDOWS\NOTEPAD.EXE

This says that two versions of the executable Notepad were found and the version that will be run first is the executable under system32.

Code Walkthrough

Initially we examine the options provided for the program and assign them to internal variables. The core of the program is the method Search which takes the executable name as a parameter.

C#
public void Search(string executableName)

Within Search, first we find the value of the 'PATH' environment variable. The various directories in this variable are where the system will search for the mentioned program. We also find the registered executable extensions by examining the PATHEXT environment variable.

C#
IDictionary  environmentVariables = Environment.GetEnvironmentVariables();
foreach (DictionaryEntry de in environmentVariables)
{
  if(de.Key.ToString().ToUpper().Equals("PATH"))
  {
    pathString = de.Value.ToString().Trim();
  }
  if (de.Key.ToString().ToUpper().Equals("PATHEXT"))
  {
    pathExt = de.Value.ToString().Trim().Split(new char[]{';'});
  }
}

If there are additional extensions provided, we append it to the pathExt variable.

C#
if (this.additionalExtensionsString != null && 
           this.additionalExtensionsString.Length>0)
{
  //a simple precaution to remove the last semicolon if there is one
  if (this.additionalExtensionsString.EndsWith(";"))
  {
     this.additionalExtensionsString = this.additionalExtensionsString.Remove(
                     this.additionalExtensionsString.Length-1, 1);
  }
  string[] aes = this.additionalExtensionsString.Split(new char[]{';'});
  ArrayList al = new ArrayList();
  al.AddRange(this.pathExt);
  al.AddRange(aes);
  this.pathExt = (string[])al.ToArray(typeof(string));
}

We then create a regular expression that will match the name of the executable.

C#
Regex regEx = new Regex(GetRegExString(executableName), RegexOptions.IgnoreCase);

Within GetRegExString, we check if the extension has already been provided or not. If it has not been, we add the probable extensions.

C#
if (execNameHasExtension || this.pathExt == null || this.pathExt.Length == 0)
{
   regexString += "$";
}
else
{
  regexString += "(?:";
  foreach(string oneExt in this.pathExt)
  {
    regexString += "\\"+oneExt+"|";
  }
  regexString += ")$";
}

GetPathsSplit function returns an array of all the components of the PATH. Within this, we also add the start up directory (".") to the list of paths, since Windows examines this first. Then we walk through each of the paths looking for files that match, writing out matches as we find them.

C#
string[] paths = pathString.Split(new char[]{Path.PathSeparator});
int count = 0;
foreach(string onePath in paths)
{
    string onePath2 = onePath.Trim();
    if (onePath2.Length == 0) continue;
    DirectoryInfo di = new DirectoryInfo(onePath2);
    if (!di.Exists) continue;
    foreach(FileInfo fi in di.GetFiles())
    {
        if (regEx.IsMatch(fi.Name))
        {
            Console.WriteLine(" "+ ++count + " " +fi.FullName);
        }
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
France France
~/sathishvj

Comments and Discussions

 
GeneralOrder problem Pin
ericksonbrian18-Oct-07 5:15
ericksonbrian18-Oct-07 5:15 
GeneralQuoted paths Pin
gewe12-Apr-06 3:23
gewe12-Apr-06 3:23 
Generalbatch file Pin
MCarter__17-Jul-05 17:04
MCarter__17-Jul-05 17:04 
GeneralRe: batch file Pin
SathishVJ20-Jul-05 22:21
SathishVJ20-Jul-05 22:21 
GeneralRe: batch file Pin
Sandeep Datta5-Dec-06 20:55
Sandeep Datta5-Dec-06 20:55 
Generalwhere.exe Pin
schirrmeister15-Jul-05 21:38
schirrmeister15-Jul-05 21:38 
GeneralCOOL Pin
eggie57-Jul-05 9:55
eggie57-Jul-05 9:55 
GeneralRe: COOL Pin
SathishVJ8-Jul-05 0:12
SathishVJ8-Jul-05 0:12 
Generalcomment and suggestion Pin
dfellman7-Jul-05 7:07
dfellman7-Jul-05 7:07 
comment: nice work; i use this type of thing all the time.

suggestion: use the PATHEXT for the types of 'executables'; don't hard-code them.

c:>set |find /i "pathext"
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.pyo;.pyc;.pyw;.py

you can probably pull this info from the registry.
GeneralRe: comment and suggestion Pin
SathishVJ8-Jul-05 0:16
SathishVJ8-Jul-05 0:16 
QuestionGUI? Pin
fwsouthern7-Jul-05 3:59
fwsouthern7-Jul-05 3:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.