Get directory of an executing assembly in C# and Visual Basic


Continuing my series of short but useful tips and tricks, one usually needs to find the directory of an executing assembly. The simple console application below shows how to do this. The Visual Basic example is after the C# one.

C#

using System;
using System.IO;
using System.Reflection;
 
namespace ConsoleApplication2
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Directory: " + AssemblyDirectory());
Console.WriteLine("Location: " + Assembly.GetExecutingAssembly().Location);
Console.ReadKey();
}
 
public static string AssemblyDirectory()
{
var uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase);
return Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path));
}
 
}
}
 

Visual Basic

 

Imports System.Reflection
Imports System.IO
 
Module Module1
 
Sub Main()
Console.WriteLine("Directory: " + AssemblyDirectory())
Console.WriteLine("Location: " + Assembly.GetExecutingAssembly().Location)
Console.ReadKey()
End Sub
 
Public Function AssemblyDirectory() As String
Dim uri = New UriBuilder(Assembly.GetExecutingAssembly().CodeBase)
Return Path.GetDirectoryName(System.Uri.UnescapeDataString(uri.Path))
End Function
 
End Module