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
RT @CodeSnippetsNET: How to check if a file is a executable in .NET http://t.co/BGxk5z50aB #csharp #vb #dotnet