AsifM
AsifM

Reputation: 699

How can I resolve the path of a command (e.g.- gacutil) progmatically?

I need to progmatically call gacutil to uninstall some binaries from GAC.

To be able to use gacutil commands from cmd I had to add the gacutil path to the PATH variable. But now that I'm trying to run gacutil from code, I need to dynamically resolve the path of the gacutil to be able to start the process. But I couldn't find a way to resolve the gacutil path yet. Is there any?

I did try expanding the PATH environment variable like suggested in this answer, but since PATH variable has multiple directories on it (separated by semicolons), there's no simple way to resolve the gacutil path.

But obviously when I type gacutil in cmd it somehow resolves the path searching through all the available directories in the PATH variable. How can I make that happen from code?

Upvotes: 2

Views: 283

Answers (4)

lit
lit

Reputation: 16226

If you want to find all of the executables in the PATH, the following cmd.exe script will identify them.

@SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
@SET EXITCODE=1

:: Needs an argument.

@IF "x%1"=="x" (
    @ECHO Usage: %0 ^<progName^>
    GOTO TheEnd
)

@set newline=^


@REM Previous two (2) blank lines are required. Do not change!

@REM Ensure that the current working directory is first
@REM because that is where DOS looks first.
@PATH=.;!PATH!

@FOR /F "tokens=*" %%i in ("%PATH:;=!newline!%") DO @(
    @IF EXIST %%i\%1 (
        @ECHO %%i\%1
        @SET EXITCODE=0
    )

    @FOR /F "tokens=*" %%x in ("%PATHEXT:;=!newline!%") DO @(
        @IF EXIST %%i\%1%%x (
            @ECHO %%i\%1%%x
            @SET EXITCODE=0
        )
    )
)

:TheEnd
@EXIT /B %EXITCODE%

Upvotes: 1

Pikoh
Pikoh

Reputation: 7703

Of course, if it's in the path you don't need to search it as @nopeflow answered. But if you really want to get the path of any file in the PATH environment variable,you could do something like this:

string[] PathDirs = Environment.GetEnvironmentVariable("PATH").Split(';');
string GACdir="";
foreach (string path in PathDirs)
{
     if (File.Exists(Path.Combine(path,"gacutil.exe")))
     {
            GACdir=path;
     }
}

Upvotes: 1

user6522773
user6522773

Reputation:

Using this, start it using Process.Start and read the output:

WHERE gacutil

Upvotes: 1

pwas
pwas

Reputation: 3373

If path is specified in PATH environment variable, you do not need to know the path:

Process p = new Process();
p.StartInfo.FileName = "gacutil";
p.Start();    
//it automatically resolves path basin on PATH environment variable

.

Upvotes: 1

Related Questions