user1144
user1144

Reputation:

splitting multiple paths in string

I have a command, which might resemble the following:

SYNC C:\Users\Fox Mulder\SyncClient C:\Users\Fox Mulder\SyncServer

This is a command that will be entered via a Console Application. It will be read by Console.ReadLine.

How can I parse the command so that I can get the two seperate directory path's?

I am unable to split on space, because that will result in a split at "Fox Mulder".

How can I parse this easily?

Upvotes: 0

Views: 335

Answers (4)

STW
STW

Reputation: 46434

The command should be space delimited, with each path wrapped in quotes to properly include their embedded strings:

SYNC "C:\Users\Fox Mulder\SyncClient" "C:\Users\Fox Mulder\SyncServer"

If you can't require quotes then things become much more ugly--consider paths such as

c:\documents and settings\mom and dad\documents\family vacations\2009\the bahama ramas\

String splitting on " " will be a headache. The brute force method would be to test the first portion of the path (c:\documents) on it's own, if it's invalid then append the next portion (c:\documents and), etc... of course it's ugly, non-performant, and full of potential issues (what if both "c:\documents" and "c:\documents and settings" are valid? Your code will end up very skittish and paranoid.

Upvotes: 7

user1228
user1228

Reputation:

Another option is to use a non-valid path character as a path delimeter.

SYNC C:\Users\Fox Mulder\SyncClient?C:\Users\Fox Mulder\SyncServer

Upvotes: 0

Scott P
Scott P

Reputation: 3772

How about this?

string testString = @"SYNC C:\Users\Fox Mulder\SyncClient C:\Users\Fox Mulder\SyncServer";

int firstIndex = testString.IndexOf(Path.VolumeSeparatorChar);
int secondIndex = testString.LastIndexOf(Path.VolumeSeparatorChar);
string path1, path2;

if (firstIndex != secondIndex  && firstIndex != -1)
{
    path1 = testString.Substring(firstIndex - 1, secondIndex - firstIndex);
    path2 = testString.Substring(secondIndex - 1);

    Console.WriteLine("Path 1 = " + path1);
    Console.WriteLine("Path 2 = " + path2);
} 

Upvotes: 0

Amirshk
Amirshk

Reputation: 8258

Using " would solve it

SYNC "C:\Users\Fox Mulder\SyncClient" "C:\Users\Fox Mulder\SyncServer"

this will be interperted as two seperate strings in the argv

Upvotes: 3

Related Questions