user1721879
user1721879

Reputation: 47

ArgumentException: 'Illegal characters in path' in C#

The error I am receiving upon executing my code is: 'ArgumentException was unhandled. Illegal characters in path.'

I am using the following code to access my .xml file.

string appPath = Path.GetDirectoryName(System.Environment.CommandLine);
FileInfo fi = new FileInfo(appPath + @"\Books.xml");

I am doing this for a console application, as opposed to a WinForm. I have been exhaustively googling, as well as searching SO, for some time.

This is part of a homework project. This is the only problem I am running into however.

Upvotes: 1

Views: 3781

Answers (4)

xtmq
xtmq

Reputation: 3693

Use this code to get application directory:

var rootDirectory = AppDomain.Current.BaseDirectory;

Good luck!

Upvotes: 0

kprobst
kprobst

Reputation: 16651

The format of the EXE path returned by CommandLine is funky, so you need to do something like this:

string appPath = Path.GetDirectoryName(System.Environment.CommandLine.Trim('"', ' '));

That should work.

Upvotes: 0

Furqan Safdar
Furqan Safdar

Reputation: 16698

string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
FileInfo fi = new FileInfo(Path.Combine(appPath, "Books.xml"));

Upvotes: 3

Oded
Oded

Reputation: 498934

System.Environment.CommandLine does not return a path - it returns the value of the command line that was executed to run the application.

You probably need to use Assembly.GetExecutingAssembly().Location (as Furqan Safdar posted in his answer) instead.

Upvotes: 1

Related Questions