Search code examples
c#command-line-argumentsverbatim-string

Escaping command line arguments in C# for Urls and Local and Network Paths


How do I provide an input string with automatic escaping to a console application?

I mean inside my code, I can do

public static void main(string[] args)
{
     string myURL; 
     myFolder = @"C:\temp\january\";  //just for testing
     myFolder = args[0]; // I want to do this eventually
}

How can I provide values to myFolder without me having to escape it manually via command line?

If possible, I want to avoid calling this app like this:

C:\test> myapplication.exe "C:\\temp\\january\\" 

EDIT: instead I'd prefer calling the app like this if possible

    C:\test> myapplication.exe @"C:\temp\january\" 

Thank you.

EDIT:

This is actually for a console application that calls Sharepoint Web services. I tried

  string SourceFileFullPath, SourceFileName, DestinationFolder, DestinationFullPath;

            //This part didn't work. Got Microsoft.SharePoint.SoapServer.SoapServerException
            //SourceFileFullPath = args[0]; // C:\temp\xyz.pdf
            //SourceFileName = args[1];     // xyz.pdf
            //DestinationFolder = args[2]; // "http://myserver/ClientX/Performance" Reports


            //This worked.   
            SourceFileFullPath = @"C:\temp\TestDoc2.txt";
            SourceFileName = @"TestDoc2.txt";
            DestinationFolder = @"http://myserver/ClientX/Performance Reports";
            DestinationFullPath = string.Format("{0}/{1}", DestinationFolder, SourceFileName); 

Solution

  • The requirement to escape \ inside a string if it is not a verbatim string (one that starts with @) is a C# feature. When you start your application from a console, you are outside of C#, and the console does not consider \ to be a special character, so C:\test> myapplication.exe "C:\temp\january" will work.

    Edit: My original post had "C:\temp\january\" above; however, the Windows command line seems to also handle \ as an escape character - but only when in front of a ", so that command would pass C:\temp\january" to the application. Thanks to @zimdanen for pointing this out.

    Please note that whatever you put between quotes in C# is a representation of a string; the actual string may be different - for instance, \\ represents a single \. If you use other means to get strings into the program, such as the command line arguments or by reading from a file, the strings do not need to follow C#'s rules for string literals. The command line has different rules for representation, in which a \ represents itself.