C#/.NET – GetExecutablePath – borrowed a bit from the Delphi 2006 RTL
Posted by jpluimers on 2009/07/15
Somehow, at every client I need a function like GetExecutablePath.
Maybe you do too, so here is the code that I adapted a long time ago from the Delphi 2006 RTL:
using System;
using System.Diagnostics;
using System.Reflection;
namespace bo.Reflection
{
public class AssemblyHelper
{
public static string GetExecutablePath()
{
// borrowed from D2006\source\dotNet\rtl\Borland.Delphi.System.pas function ParamStr():
string result;
Assembly entryAssembly = Assembly.GetEntryAssembly();
if (null != entryAssembly)
{
result = entryAssembly.Location;
}
else
{
Process currentProcess = Process.GetCurrentProcess();
ProcessModule mainModule = currentProcess.MainModule;
result = mainModule.FileName;
}
return result;
}
}
}
Enjoy :-)
–jeroen






brad said
I do something similiar to get an ASP.Net dll path.
string DllPath = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
But for ASP.Net assemblies you get it in URL form, so sometimes I cheat and do…
DllPath = DllPath.Replace(“file:\\”, “”);
jpluimers said
You are right; in ASP.NET applications, GetEntryAssembly is null, so you can use GetExecutingAssembly as an alternative.
However, GetExecutingAssembly might not return the main assembly of your ASP.NET application.
This post explains it well: Fogcreek software on Assembly.GetEntryAssembly() in ASP.NET.
In Delphi they choose to use getting the MainModule of Process.GetCurrentProcess, which works always works.
Hence that is what I used as well.
–jeroen