Derek Tomes
Derek Tomes

Reputation: 4007

How can I extract the path of a file without arguments from a string?

I have a string containing a path to an executable file that also may or may not have command line arguments in it.

For example:

"C:\Foo\Bar.exe"
"C:\Foo\Bar.exe /test"
"C:\Foo\Bar.exe {0}"
"C:\Foo\Bar.exe -snafu"

I'm trying to break the string up into path part and the arguments part. The arguments part may be in pretty much any format. But the IO.Path functions assume that the string is a path without arguements. For example, if I call:

IO.Path.GetFileName(path)      

It returns Bar.exe /test, Bar.exe {0} or Bar.exe -snafu

Windows can obviously tell the difference when I run this at a command prompt so there must be some way to leverage an existing function.

I can surround the path part of the string in quotes if I need to. But then the IO.Path calls fail. For example:

? IO.Path.GetFileName("""C:\Windows\write.exe"" {0}")

Throws an Arguement Exception: Illegal characters in path.

Upvotes: 2

Views: 362

Answers (2)

keyboardP
keyboardP

Reputation: 69372

CommandLineToArgvW would be the best approach as Sorceri mentioned (you can see example code here), but here's a naive implementation that might suffice for you. This assumes that a file extension will always be present.

string input = @"C:\Foo\Bar test\hello.exe {0}";
string[] split = input.Split(' ');

int index = 0;
string ext = String.Empty;
string path = "";
string arguments = "";

while (true)
{
    string testPath = String.Join(" ", split, 0, index);
    ext = Path.GetExtension(testPath);
    if (!String.IsNullOrEmpty(ext))
    {
        path = Path.GetFullPath(testPath);
        arguments = input.Replace(path, "").Trim();
        break;
    }

    index++;
}

Console.WriteLine(path + " " + arguments);

You can add handling such that the while loop doesn't run forever in the event of an extension not being found. I've only tested it with the three URLs in your post so you may want to test other scenarios.

Upvotes: 1

Sorceri
Sorceri

Reputation: 8033

Take a look at CommandLineToArgvW

Upvotes: 2

Related Questions