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 Oct 5, 2012 at 19:38
  • What is the path that you are passing in on the CommandLine
    – Mark Hall
    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"));
2
  • 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 :) Oct 5, 2012 at 19:43
  • Works great! Thank you! A note in case anyone comes across this solution...make sure to include 'using System.Reflection;' =P Oct 5, 2012 at 19:49
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
  • 1
    Be careful though. Current directory is not necessarily the same as the directory containing the executable file. Oct 5, 2012 at 19:39
  • @DavidHeffernan - True, though I can't ever recall the recommended way to get the application path.
    – Oded
    Oct 5, 2012 at 19:41
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.

0

Use this code to get application directory:

var rootDirectory = AppDomain.Current.BaseDirectory;

Good luck!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.