File Path as Command Line Argument
Asked Answered
C

7

8

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.

Cabernet answered 9/3, 2014 at 8:36 Comment(10)
You should post some code for us to see.Doggett
Can you post the relevant part of your code?Impulsion
"I am having no knowledge of c# thanks for helping." - with that in mind, are you sure you are in the correct position to be working on a program rather than reading tutorials and programming teaching books?Spoilsport
That notwithstanding, like the others said, you will need to show us the code where this is a relevant problem. Usually, user strings do not feature any escape characters; that is just their representation when writing them down within C# source code. In particular, I am not sure what kind of an operation is described by "when i give input" - are you invoking an application from within C#, passing strings as command line arguments to that other application?Spoilsport
Please, do not include information about a language used in a question title unless it wouldn't make sense without it. Tags serve this purpose.Blackman
Please see the Edits.Cabernet
Have you used MS .NET? It would work correct.Romansh
@HamletHakobyan yes..Cabernet
I think you have XY problem. Have you checked exactly same code as you have posted here?Romansh
@HamletHakobyan sorry but i don't understand what you mean to say? when i give command line argument "F:\\" it prints F:\ and when i give argument "F:\" it prints F:" while i want F:\.Cabernet
S
1

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\.

Sparks answered 9/3, 2014 at 9:11 Comment(8)
Just think "C:\ME DIA\" as input now what will happen?Cabernet
Well as with all command line apps in Windows the input should be wrapped with quotes. So you'd make a call like this listdir.exe "c:\my media" or listdir.exe "c:\my media\". You'll find that the c# console app will interpret it correctly and put `c:\my media` into your path variable.Sparks
Just consider second case in that case your print line will print c:\my media". and Directory.Exist() will return false even also the directory exist just because of double quotes at the end.Cabernet
@NiravKamani I see, the problems just clicked :) So why can't you trim the quote? eg string path = args[0].TrimEnd('"');Sparks
Any other solution? This is working but is it possible without modifying user input?Cabernet
@NiravKamani why is it so important to not modify the input? Sometimes you just have to make-do and get on with writing the rest of the app.Sparks
BTW Did you know that you can also use forward-slash, which won't casue problems but its not the convention so not really relevant.Sparks
I don't want to modify user input because logically user input is correct but it is the problem of backslash character.Cabernet
A
1

You should use Path class and specifically Path.GetFullPath method to get correct full path.

class Program
{
    static void Main(string[] args)
    {
        string path = Path.GetFullPath(args[0]);
        Console.WriteLine("trying path: " + path);
        if (Directory.Exists(path)){
            var files = Directory.GetFiles(path);
            foreach (var file in files) Console.WriteLine(file);
        }
        else
            Console.WriteLine("path doesn't exist");
    }
}

UPD. Paths with spaces should be passed in quotes. Or you should concat all your command line arguments, if path is the only input.

Alizaalizarin answered 9/3, 2014 at 9:15 Comment(1)
Path throws ArgumentException because of double quotation mark at last.Cabernet
S
1

Use Environment.GetCommandLineArgs(). It will clean up the path.

See this link for more info: http://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs(v=vs.110).aspx

Sherrisherrie answered 1/10, 2014 at 15:22 Comment(0)
S
0

Well, if I understand correctly. You can use string.Format . There are overload methods that could help you without modifying much user input.

Sample code:

string[] inputs = ...
string output = string.Format("F:\\{0}\\{1}", inputs[0], inputs[1]);
Stevenson answered 9/3, 2014 at 8:43 Comment(0)
A
0

C# interprets \ as an escape character. So \" is interpreted as " Possible way to fix it (if you are sure that there is no " inside arguments:

string a = args[0].Replace('"', '\\');
Aside answered 9/3, 2014 at 9:9 Comment(1)
Another way: you can set command line parameter without quotes.Aside
A
0

I think your over thinking this. Logically that isnt valid input. \ is an escape character on the command prompt just as it is in c# inside of a string. What you have entered ("F:\") is an invalid value and it IS on the user to correct. The user is saying at this point that they want the quote.

Aday answered 30/8, 2019 at 16:14 Comment(0)
C
0

Note that when you pass the filename in parameters, you need to have the access rights in the directory where file is placed, otherwise some parts of your application might fail unexpectedly and it might took you much time to figure out what's wrong there.

    var args1 = Environment.GetCommandLineArgs().Skip(1);
    if (args1 != null && args1.Count() > 0)
    {
        //do stuff
    }
Conchology answered 3/6, 2022 at 16:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.