How to get the application path in SmartDevice Applications

It’s very common to get the application path in Windows/Web applications. When you want to access a file in your application directory, you have to use these codes:

VB:

My.Application.Info.DirectoryPath

C#:

Application.StartupPath

The question is how to get this path in SmartDevice applications because you don’t have any StartupPath or DirectoryPath when you’re working with SmartDeviceApplications?

In order to do such a thing, you need to work with System.Reflection.

The System.Reflection namespace contains types that retrieve information about assemblies, modules, members, parameters, and other entities in managed code by examining their metadata. These types also can be used to manipulate instances of loaded types, for example to hook up events or to invoke methods.

The System.Reflection namespace has an Assembly class which you can use in order to access your assemblies. That Assembly class has a GetExecutingAssembly() method that returns the assembly that is currently executing. When you get your assembly you need its name; so the GetName() method of GetExecutingAssembly() returns a class as AssemblyName. The last part is CodeBase property which returns the location of that assembly.

Now you have a path of your application. But this path contains your execution assembly too. In order to get the directory name of your application, you need to use System.IO.Path.GetDirectoryName() that returns only the directory name of a path.

Here is the complete code:

return Path.GetDirectoryName(
   Assembly.GetExecutingAssembly().GetName().CodeBase);