user2411670
user2411670

Reputation:

C# Console application, safest way to get the correct path to file in args

I have a console application that is in the environment path that can be run from anywhere. If a user types

Program filename

From the directory where the file exits

File.Exists(args[0])

Will tell me the file exists. But when passing args[0] it is only the file name, so I am going to assume that C# prepends:

Environment.CurrentDirectory

Because the application can be run from anywhere, and the command line can have a great deal of possible input from relative paths to absolute paths I am wondering what is the safest way to get the proper directory where the file exists.

The following seems to work just fine, but am wonderig if I am missing something, is thier a better way.

string dir = Path.GetDirectoryName(args[0]);
if (String.IsNullOrEmpty(dir))
dir = Environment.CurrentDirectory;

Many thanks in advance.

Upvotes: 1

Views: 875

Answers (1)

Jens Meinecke
Jens Meinecke

Reputation: 2940

Use Path.GetFullPath(args[0]) - that will resolve the file name into it's full name for you.

Upvotes: 3

Related Questions