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?
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.
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
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);
}
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
精彩评论