Thursday, September 6, 2007

Programmatically determine if a File is an assembly


We can take help of System.Reflection.AssemblyName class to determine if a file is an assembly or not.


Call the method 'GetAssemblyName' with the full path & file name. If this statement executes successfully the file is an assembly, if it throws 'BadImageFormatException' the specified file is not an assembly.

GetAssemblyName can also throw an exception if the assembly is already loaded.


class TestAssembly
{
   
static void Main()
   {
       
try
       {
           System.Reflection.AssemblyName testAssembly =
               System.Reflection.AssemblyName.GetAssemblyName(@
"C:\Bharati\test.dll");

           System.Console.WriteLine(
"Yes, the file is an Assembly.");
       }

       
catch (System.IO.FileNotFoundException e)
       {
           System.Console.WriteLine(
"The file cannot be found.");
       }

       
catch (System.BadImageFormatException e)
       {
           System.Console.WriteLine(
"The file is not an Assembly.");
       }

       
catch (System.IO.FileLoadException e)
       {
           System.Console.WriteLine(
"The Assembly has already been loaded.");
       }
   }
}

No comments: