Windows Mobile Current Directory

Another area when programming on Windows CE/Mobile devices is “How do I find the current directory?”  CE devices don’t have a concept of a current directory.  This means that relative paths don’t have meaning on a CE device (all paths are absolute).  Because of the lack or relative paths  some files (such as help files) are loaded to the Windows directory (personally I absolutely hate copying anything specific to an application to the Windows Directory).

It follows that since there is no concept of a current directory on a Windows Mobile device how would one locate a resource for which only a relative path is known?  A .Net program always has access to the modules of which it is composed (usually a .Net component is composed of one module packaged in a DLL or EXE file). The following line will return the absolute path to the currently executing assembly.

string modulePath = this.GetType().Assembly.GetModules()[0].FullyQualifiedName;

To get the absolute path to the folder that contains the assembly simple string manipulation is required.  The assembly name appears after the last directory seperator. While the directory seperator is usually the backslash (\) character, for better compatibility across other operating systems that may run .Net (ex: Mono[^] on Linux, OS X, or Solaris) use System.IO.Path.DirectorySeparator to represent the directory separator charactor.

string solutionFolder = modulePath.Substring(0, modulePath.LastIndexOf(Path.DirectorySeparatorChar) );

Once the folder to your program is known use Path.Combine to build the fully qualified file name for files in your folder.  Path.Combine takes into account the directory separator for the operating system on which your program is run.  So if you had data in a file named MyFile.txt you would use

string myFilePath = Path.Combine(solutionFolder,”MyFile.txt”);

Update 1 : I received a simpler way to accomplish the same thing from John Spraul in the comment section.  Thanks. John!

Update 2: If you are developing using the native APIS use the following:
GetModuleFileName(GetModuleHandle(NULL),    pszFullPath, MAX_PATH);

Path.GetDirectoryName(this.GetType().Assembly.GetModules()[0].FullyQualifiedName)

or

Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName)

if you do not want to load the type.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s