2014-03-06 59 views

回答

7

MSDN上How to: Determine If a File Is an Assembly (C# and Visual Basic)

如何以編程方式確定一個文件是彙編

  1. 調用GetAssemblyName方法,傳遞文件的完整文件路徑和名稱,你是測試。
  2. 如果引發BadImageFormatException異常,則該文件不是程序集。

它甚至有一個VB.NET例如:

Try 
    Dim testAssembly As Reflection.AssemblyName = 
          Reflection.AssemblyName.GetAssemblyName("C:\Windows\Microsoft.NET\Framework\v3.5\System.Net.dll") 
    Console.WriteLine("Yes, the file is an Assembly.") 
Catch ex As System.IO.FileNotFoundException 
    Console.WriteLine("The file cannot be found.") 
Catch ex As System.BadImageFormatException 
    Console.WriteLine("The file is not an Assembly.") 
Catch ex As System.IO.FileLoadException 
    Console.WriteLine("The Assembly has already been loaded.") 
End Try 

,因爲它使用的控制流異常這是不理想的。

我也不確定它是如何在角落的情況下行爲,如文件是一個程序集,但不支持當前的CPU體系結構,或者如果它的目標是框架的不支持的變體。

+0

感謝您的超級快速回復:)這隻適用於.dll文件也適用於.exe文件?這是什麼意思,不是一個集會?不是託管文件? (本機一)?如果你能澄清^^ – nexno

+1

@nexno大會意味着被管理的.NET可執行文件,並且包含'.exe'和'.dll'文件,這將會很酷。 – Loki

+0

非常感謝你,對我來說工作正常:) – nexno

0

只是我已經寫一個通用的使用功能,以補充@Loki答案:檢查是否一個文件是一個.NET程序集]的

''' <summary> 
''' Determines whether an exe or dll file is an .Net assembly. 
''' </summary> 
''' <param name="File">Indicates the exe/dll file to check.</param> 
''' <returns><c>true</c> if file is an .Net assembly, <c>false</c> otherwise.</returns> 
Friend Function FileIsNetAssembly(ByVal [File] As String) As Boolean 

    Try 
     System.Reflection.AssemblyName.GetAssemblyName([File]) 
     ' The file is an Assembly. 
     Return True 

    Catch exFLE As IO.FileLoadException 
     ' The file is an Assembly but has already been loaded. 
     Return True 

    Catch exBIFE As BadImageFormatException 
     ' The file is not an Assembly. 
     Return False 

    End Try 

End Function 
相關問題