1

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.

2
  • 2
    Print appPath to the console and see what it is Commented Oct 5, 2012 at 19:38
  • What is the path that you are passing in on the CommandLine Commented Oct 5, 2012 at 19:39

4 Answers 4

3
string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
FileInfo fi = new FileInfo(Path.Combine(appPath, "Books.xml"));
Sign up to request clarification or add additional context in comments.

2 Comments

This will only work if the code above is in the exe, which is probably good enough. Don't do it from a DLL though unless it's in the same directory :)
Works great! Thank you! A note in case anyone comes across this solution...make sure to include 'using System.Reflection;' =P
1

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.

2 Comments

Be careful though. Current directory is not necessarily the same as the directory containing the executable file.
@DavidHeffernan - True, though I can't ever recall the recommended way to get the application path.
0

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.

Comments

0

Use this code to get application directory:

var rootDirectory = AppDomain.Current.BaseDirectory;

Good luck!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.