WiXXeY
WiXXeY

Reputation: 1001

Finding Path of File from a string

I am getting list of startup applications, and wants to get only Path of application running at startup. The list of startup application also contain the parameter passed to the application, which are in different pattern; examples are

C:\Program Files (x86)\Internet Download Manager\IDMan.exe /onboot

"C:\Program Files\Process Hacker 2\ProcessHacker.exe" -hide

"C:\Program Files\CCleaner\CCleaner64.exe" /MONITOR

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --no-startup-window /prefetch:5

"C:\Program Files (x86)\GlassWire\glasswire.exe" -hide

C:\Program Files\IDT\WDM\sttray64.exe

I am trying to use following regex

Regex.Matches(input, "([a-zA-Z]*:[\\[a-zA-Z0-9 .]*]*)");

Kindly guide me how can I extract only application path ignoring all the parameters and other startup commands.

Upvotes: 4

Views: 473

Answers (3)

sameerkn
sameerkn

Reputation: 2259

There are many cases which can break the normal method of finding the complete executable path form a given string. Simply finding ".exe" won't work in general case. Atleast one space will separate the actual complete executable path from the parameters.

Note: This solution is based on assumption that the executable would be present on its intended path. Since, OP is having a list of paths of application running at startup this assumption holds.

public string GetPathOnly(string strSource)
{
    //removing all the '"' double quote characters
    strSource.Trim( new Char[] {'"'} );

    int i;
    string strExecutablePath = "";
    for(i = 0; i < strSource.Length; ++i)
    {
        if(strSource[i] == ' ')
        {
            if(File.Exists(strExecutablePath))
            {
                return strExecutablePath;
            }               
        }
        strExecutablePath.Insert(strExecutablePath.Length, strSource[i]);
    }

    if(File.Exists(strExecutablePath))
    {
        return strExecutablePath;
    }

    return "";  // no actual executable path found.
}

Upvotes: 1

MD. Nazmul Kibria
MD. Nazmul Kibria

Reputation: 1090

Try this simple approach:

string cmd = "\"C:\\Program Files (x86)\\GlassWire\\glasswire.exe\" -hide";

int index = cmd.ToLower().LastIndexOf(".exe");
string path = cmd.Substring(0, index+4);
index = path.IndexOf("\"");
if (index >= 0)
path = path.Substring(index + 1);

Upvotes: 2

sujith karivelil
sujith karivelil

Reputation: 29006

Since the expected input list will contains list of executable files, all are having the .exe extension, we can make use of that extension here By suing .Substring() method of String class. Sample usage will be like this:

 List<string> inputMessageStr = PopulateList(); // method that returns list of strings
 List<string> listofExePaths= inputMessageStr.Select(x=> x.Substring(0, x.IndexOf(".exe") + 4)).ToList();

Upvotes: 2

Related Questions