Search code examples
c#stringcommand-line-argumentsfilepath

File Path as Command Line Argument


This is very common thing but i am very confused to get around this.

Taking file path as command line argument in c#.

If i give input "F:\\" then this works perfect.

But when i give input "F:\" it gives output like F:".

I know this is because of backslash escape character.

But my problem is how to get around this without modifying user input because logically user input is correct.

Is it possible without modifying user input get correct path in this situation?

I also know that there is @ character which can be used.

But as i said this is command line argument so the string is already in variable.

I also read some blogs but still i remain unable to resolve my problem.

C# Command-Line Parsing of Quoted Paths and Avoiding Escape Characters

EDIT :Actually my program is to list all the files inside directory so i am first checking for Directory.Exists(command line arguments) and then getting list of all the files if directory exist.

Ok so in that case when user gives Command line argument as i shown above logically the drive exist but just because of escape character it returns false.

Just think about printing the command line argument as follow.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("{0}", args[0]);

        Console.Read();
    }
}

I am having very less knowledge of c# thanks for helping.


Solution

  • Im not sure why your having a problem here. In M$ Windows, a directory can be specified with or without a back-slash so all of these are correct: c: and c:\ and c:\media and c:\media\. This is the same for Directory.Exists(path) and other functions like Directory.GetFiles(path).

    Ths following is a very simple app to list directory files and in my environment it works regardless of whether I put a slash on the end. So c:\media\ gives me all my media files.

    class Program
    {
        static void Main(string[] args)
        {
            string path = args[0];
            Console.WriteLine("trying path: " + path);
            if (Directory.Exists(path))
                Directory.GetFiles(path).ToList().ForEach(s => Console.WriteLine(s));
            else
                Console.WriteLine("path not found");
        }
    }
    

    One thing to note is that in visual studio, when using the debugger such as Quick Watch, it will show the escape character with backslashs. So if user enters c:\media\ the string will be stored as c:\media\ but when you quick watch the path in VS you'll see c:\\media\\; look deeper with the Text Visualisation feature and you'll see the path correctly shown as c:\media\.