Tuesday, 20 September 2011

Determining Path in which the Application is executing


System.Reflection.Assembly.GetExecutingAssembly().CodeBase will give you something like this:


System.Reflection.Assembly.GetExecutingAssembly().Location will give you something like this:

"C:\\Users\\username\\AppData\\Local\\Temp\\Temporary ASP.NET Files\\appname\\11ac36b5\\e67e91b4\\assembly\\dl3\\6b43be0f\\20cfa62a_4877cc01\\AppName.Project.DLL"

Taken from Suzanne Cook's .NET CLR Notes:
The CodeBase is a URL to the place where the file was found, while the Location is the path from where it was actually loaded. For example, if the assembly was downloaded from the internet, its CodeBase may start with "http://", but its Location may start with "C:\".
It’s also good to know that the CodeBase is not guaranteed to be set for assemblies in the GAC. Location will always be set for assemblies loaded from disk, however.
Returns the directory information for the specified path string.
For example, passing the path "C:\Directory\SubDirectory\test.txt" into the GetDirectoryName method will return "C:\Directory\SubDirectory"

So the preferred method to obtain the path of the executing assembly is:

String strPath = System.IO.Path.GetDirectoryName(

However, you may not want the physical path of where the Assembly is located.

You may just want to get the physical path of the Application Root folder so that you can dynamically create a new folder and put something in there, eg, a 'Logs' folder and put your applications log in there.

In which case, you'll want to use something like:


which will give you something like:

Then you can bang that string straight into a directory creation call and create your "Logs" folder like this:

string result = Path.Combine(System.Web.HttpContext.Current.Request.PhysicalApplicationPath, "Logs");
if (!System.IO.Directory.Exists(result))
    catch (Exception ex)
            // probably a permissions issue
            // could return the exception message to user interface
            // otherwise, cannot do much
            return "";



No comments:

Post a Comment