The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,858 other subscribers

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

2 Responses to “C#/.NET – GetExecutablePath – borrowed a bit from the Delphi 2006 RTL”

  1. brad's avatar

    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's avatar

      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

Leave a reply to brad Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.