I am trying to pass a file path into a C# Console Application
but am having problems with the string being incorrect by the time it reaches the console application.
If I run my application from the command line, with a file path parameter:
MyApp "C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject\"
A windows dialogue pops up and informs me that my application has stopped working, and when I click the Debug option, I can see that the result of args[0]
is:
C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject"
Note there is still a trailing quote at the end.
If I pass a second argument:
MyApp "C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject\" "any old string"
I get an error again, and after viewing in debug I see that args[0] is:
C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject" any
I am baffled as to why this is happening. My only guess is that the backslashes in the string are causing some kind of escape sequence from the string? Edit: I notice that the same is happening in the string example above! It seems \" is causing problems here.
I just want to pass in the file path of the current solution directory and am calling my app from a pre-build event using $(SolutionDir), and know that I can get the path of the current solution in other ways. But this is simplest and I am curious as to why it does not work as expected.
Yes, the rules for commandline arguments are a little murky.
The \
is the escape char and you can use it to escape quotes ("
). You'll have to escape a backslash but only when it is preceding a quote. So use (note the '\\' at the end):
MyApp "C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject\\"
or, simpler but you'll have to deal with it in C# somehow:
MyApp "C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject"
Also see this question
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With