feedwall
feedwall

Reputation: 1574

How do I strip quotes and commandline arguments out from a file path in C#?

I have filepaths in quotes with empty spaced foldernames like this with at least two command line parameters of different length and value appended:

"C:\My Program\Sample Folder\SubFolder2\MyApp1.exe" -parameter13XY1 -parameter101XZ2

I would like to have only the filename without quotes and without commandline arguments:

C:\My Program\Sample Folder\SubFolder2\MyApp1.exe

I would search functions like "StripQuotes" and "StripCommandLineArgs" in the framework, but I didn't find anything similar, since the framework has almost everything missing what would be needed. As for quotes it would maybe do a "Replace", but the commandline arguments can't be sorted out that way. The filename also contains spaces, so it is not possible to work with Split() as it would cut a part of the filename out.

In the end I would like to have only the filename without quotes and commandline arguments. Note that the filename can also contain empty spaces and hyphens and both combinations of it, like this:

"C:\My Program - Win64\Sample-Folder\Sub -Folder3\My App55- .exe -parameter1 -parameter2 para3"

I have no idea how to find out only the valid path in such cases. There could be also five commandline arguments attached or even 10.

Upvotes: 3

Views: 2655

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

You can use a regular expression "^\"([^\"]*)\".*$" to get the content of the quoted string, like this:

var s = "\"C:\\My Program\\Sample Folder\\SubFolder2\\MyApp1.exe\" -parameter13XY1 -parameter101XZ2";
var res = Regex.Replace(s, "^\"([^\"]*)\".*$", "$1");
Console.WriteLine(res);

Here is a link to ideone.

Upvotes: 2

akton
akton

Reputation: 14376

A slightly heavier answer is to use a command line parsing library like http://commandline.codeplex.com/. It handles all the parsing for you without needing to deal with regular expressions.

Upvotes: 1

Maciek Talaska
Maciek Talaska

Reputation: 1638

The very rough & quick solution:

string cmd = "\"C:\\My Program\\Sample Folder\\SubFolder2\\MyApp1.exe\" -parameter13XY1 -parameter101XZ2";
var allStrings = cmd.Split(new char[] {'"'} );

Upvotes: 0

jimbofreedman
jimbofreedman

Reputation: 412

String.Split can take a parameter for the character to split on - so if you try this:

var array = filename.Split('"');

You should get back an array with two elements:

array[0] = "C:\My Program\Sample Folder\SubFolder2\MyApp1.exe"
array[1] = "-parameter13XY1 -parameter101XZ2"

Upvotes: 0

Related Questions