Cannot find file path

3.4k Views Asked by At

I'm using Windows CE 6.0. I'm developping an application that needs to read a XML file (bar.xml) that is placed right next to my executable (foo.exe).

I try to access it with the following method, called right after my Main() :

private void ParseXmlFile(string _sFileName)
{
    XmlDocument l_doc = new XmlDocument();
    l_doc.Load(_sFileName);
}

Now, when launching my application from the Windows CE console with :

foo.exe bar.xml

All I receive is an exception stating : Cound not find file '\bar. Notice the '\' here. I also tried :

foo.exe bar.xml
foo.exe .\bar.xml
foo.exe ./bar.xml

My application is under \Hard Disk\ftp\Test\

If I put my file under the "Hard Disk" folder, everything is fine. Of course, I don't want my file here. How can I tell my application to look up this file in the same folder as my application ?

Edit :
After comment from @Thomas, I checked my path and saw that I was indeed in the correct folder (\Hard Disk\ftp\Test).

I had to use the following code to get the path (because of Compact framework 2.0) :

string l_sFullAppName = Assembly.GetCallingAssembly().GetName().CodeBase;
string l_sFullAppPath = Path.GetDirectoryName(l_sFullAppName);

XmlDocument l_doc = new XmlDocument();
l_doc.Load(_l_sFullAppPath + '\\bar.xml');

It works but doesn't seem to be very convenient to me. Any other ideas ?

1

There are 1 best solutions below

2
On BEST ANSWER
  1. Determine full executable directory. See HOW TO: Determine the Executing Application's Path. The contents is applicable to .NET Compact Framework. Note, that System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase returns location of the assembly as a URL, but System.Reflection.Assembly.GetExecutingAssembly().Location returns full path or UNC location (see here).
  2. Use Path.Combine() method for combining strings into a result path.

As result your code may be like this:

var fullPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var fullFileName = System.IO.Path.Combine(fullPath, _sFileName);