How to get the executable filename in C# and VB.NET

To get the executable filename in C# and VB.NET you can use one the following methods.

Sample C#

//prefered way to retrieve exe filename
Console.WriteLine(Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName));
 

Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); //can cause problems when using click once, also this property does not always returns the right result.

Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().Location)); //can fail when used in wcf application.
Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase)); //better if shadow copy feature is active, but can fail when used in wcf application
Console.WriteLine(Path.GetFileName(Assembly.GetEntryAssembly().Location));

Sample VB.NET

'prefered way to retrieve exe filename
Console.WriteLine(Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName))


Console.WriteLine(AppDomain.CurrentDomain.FriendlyName)
'can cause problems when using click once, also this property does not always returns the right result.
Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().Location))
'can fail when used in wcf application.
Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase))
'better if shadow copy feature is active, but can fail when used in wcf application
Console.WriteLine(Path.GetFileName(Assembly.GetEntryAssembly().Location))

How to check if a file is a executable in C# and VB.NET

To check if a file is a executable in C# and VB.NET you can use the follwing snippet.

Sample C#

public bool CheckIfFileIsExecutable(string file)
{
	try
	{
		var firstTwoBytes = new byte[2];
		using(var fileStream = File.Open(file, FileMode.Open))
		{
			fileStream.Read(firstTwoBytes, 0, 2);
		}
		return Encoding.UTF8.GetString(firstTwoBytes) == "MZ";
	}
	catch(Exception ex)
	{
		//handle the exception your way
	}   
	return false;
}

Sample VB.NET

Public Function CheckIfFileIsExecutable(file__1 As String) As Boolean
	Try
		Dim firstTwoBytes = New Byte(1) {}
		Using fileStream = File.Open(file__1, FileMode.Open)
			fileStream.Read(firstTwoBytes, 0, 2)
		End Using
		Return Encoding.UTF8.GetString(firstTwoBytes) = "MZ"
	Catch ex As Exception
                'handle the exception your way
	End Try
	Return False
End Function