How to get current assembly in C#

By FoxLearn 12/24/2024 7:31:13 AM   147
To get the current assembly name in C#, you can use the GetExecutingAssembly() method from the System.Reflection.Assembly class.

This method returns the assembly that contains the code currently being executed.

How to get current assembly in C#?

To get an Assembly object for the currently executing assembly, you can use the GetExecutingAssembly method.

// Gets the assembly of the currently executing code
Assembly currentAssembly = Assembly.GetExecutingAssembly();

How to get current assembly name in C#?

For example, get the assembly of the current executing code.

// c# get current assembly
// Gets the assembly of the currently executing code
Assembly currentAssembly = Assembly.GetExecutingAssembly();
// Get the full name of the assembly
Console.WriteLine(currentAssembly.FullName); // Output: ConsoleApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

How to get the full name of an assembly in C#?

If you know the assembly's file system path, you can call the AssemblyName.GetAssemblyName method to get the fully qualified assembly name.

string assemblyPath = @"C:\path\myAssembly.dll";

// Get the AssemblyName from the file path
AssemblyName assemblyName = AssemblyName.GetAssemblyName(assemblyPath);

// Display the full assembly name
Console.WriteLine("Assembly Full Name: " + assemblyName.FullName);

For example, get the assembly containing the type of the calling code.

// Gets the assembly of the code containing this type
Assembly currentAssembly = typeof(YourTypeName).Assembly;
Console.WriteLine(currentAssembly.FullName); // Output: ConsoleApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

Use when you want the assembly where a specific type is defined.

For example, get the entry assembly.

// Gets the entry assembly (e.g., the main application executable)
Assembly? entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
    Console.WriteLine(entryAssembly.FullName); // Output: ConsoleApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

Use when you want the assembly that contains the entry point of the application.