2010-10-30 28 views
8

Tôi cố gắng tải một assembly vào mã nguồn của tôi trong C#. Vì vậy, tôi lần đầu tiên biên dịch tập tin nguồn:Lắp ráp tải không hoạt động chính xác

private bool testAssemblies(String sourceName) 
     { 
      FileInfo sourceFile = new FileInfo(sourceName); 
      CodeDomProvider provider = null; 
      bool compileOk = false; 

      // Select the code provider based on the input file extension. 
      if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".CS") 
      { 
       provider = CodeDomProvider.CreateProvider("CSharp"); 
      } 
      else if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".VB") 
      { 
       provider = CodeDomProvider.CreateProvider("VisualBasic"); 
      } 
      else 
      { 
       Console.WriteLine("Source file must have a .cs or .vb extension"); 
      } 

      if (provider != null) 
      { 

       // Format the executable file name. 
       // Build the output assembly path using the current directory 
       // and <source>_cs.exe or <source>_vb.exe. 

       String exeName = String.Format(@"{0}\{1}.exe", 
        System.Environment.CurrentDirectory, 
        sourceFile.Name.Replace(".", "_")); 

       CompilerParameters cp = new CompilerParameters(); 

       // Generate an executable instead of 
       // a class library. 
       cp.GenerateExecutable = true; 

       // Specify the assembly file name to generate. 
       cp.OutputAssembly = exeName; 

       // Save the assembly as a physical file. 
       cp.GenerateInMemory = false; 

       // Set whether to treat all warnings as errors. 
       cp.TreatWarningsAsErrors = false; 

       // Invoke compilation of the source file. 
       CompilerResults cr = provider.CompileAssemblyFromFile(cp, 
        sourceName); 

       if (cr.Errors.Count > 0) 
       { 
        // Display compilation errors. 
        Console.WriteLine("Errors building {0} into {1}", 
         sourceName, cr.PathToAssembly); 
        foreach (CompilerError ce in cr.Errors) 
        { 
         Console.WriteLine(" {0}", ce.ToString()); 
         Console.WriteLine(); 
        } 
       } 
       else 
       { 
        // Display a successful compilation message. 
        Console.WriteLine("Source {0} built into {1} successfully.", 
         sourceName, cr.PathToAssembly); 
       } 

       // Return the results of the compilation. 
       if (cr.Errors.Count > 0) 
       { 
        compileOk = false; 
       } 
       else 
       { 
        compileOk = true; 
       } 
      } 
      return compileOk; 
     } 

này hoạt động tốt, nhưng nếu sau này tôi cố gắng tải lắp ráp, tôi luôn luôn có được một ngoại lệ:

System.Reflection.TargetInvocationException was unhandled 
    Message=Exception has been thrown by the target of an invocation. 
    Source=mscorlib 
    StackTrace: 
     at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) 
     at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) 
     at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) 
     at System.Delegate.DynamicInvokeImpl(Object[] args) 
     at Microsoft.Surface.Shell.ApiEventManager.EventSubscriberInfo.InvokeCallback(Object arg) 
     at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) 
     at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) 
     at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) 
     at System.Windows.Threading.DispatcherOperation.InvokeImpl() 
     at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state) 
     at System.Threading.ExecutionContext.runTryCode(Object userData) 
     at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) 
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
     at System.Windows.Threading.DispatcherOperation.Invoke() 
     at System.Windows.Threading.Dispatcher.ProcessQueue() 
     at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
     at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
     at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) 
     at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) 
     at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) 
     at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) 
     at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) 
     at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg) 
     at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) 
     at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) 
     at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) 
     at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) 
     at System.Windows.Threading.Dispatcher.Run() 
     at System.Windows.Application.RunDispatcher(Object ignore) 
     at System.Windows.Application.RunInternal(Window window) 
     at System.Windows.Application.Run(Window window) 
     at System.Windows.Application.Run() 
     at Prototype_Ver1.App.Main() in C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Ver1\Prototype_Ver1\obj\Debug\App.g.cs:line 0 
     at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) 
     at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) 
     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
     at System.Threading.ThreadHelper.ThreadStart_Context(Object state) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
     at System.Threading.ThreadHelper.ThreadStart() 
    InnerException: System.IO.FileLoadException 
     Message=Could not load file or assembly 'C:\\Users\\Roflcoptr\\Desktop\\hello.cs' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047) 
     Source=mscorlib 
     FileName=C:\\Users\\Roflcoptr\\Desktop\\hello.cs 
     FusionLog="" 
     StackTrace: 
      at System.Reflection.AssemblyName.nInit(Assembly& assembly, Boolean forIntrospection, Boolean raiseResolveEvent) 
      at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) 
      at System.Reflection.Assembly.Load(String assemblyString) 
      at Prototype_Ver1.SurfaceWindow1.OnApplicationActivated(Object sender, EventArgs e) in C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Ver1\Prototype_Ver1\MainWindow.xaml.cs:line 91 
     InnerException: 

Phương pháp tải của tôi trông như thế này:

if (testAssemblies("C:\\Users\\Roflcoptr\\Desktop\\hello.cs")) 
      { 
       Assembly a = Assembly.Load("C:\\Users\\Roflcoptr\\Documents\\Visual Studio 2008\\Projects\\Prototype_Ver1\\Prototype_Ver1\\bin\\Debug\\hello_cs.exe"); 
      } 

Bất kỳ ý tưởng nào tại sao nó không hoạt động?

Trả lời

22

Tôi nghĩ cú pháp của bạn sai. Assembly.load (string) dự kiến ​​lắp ráp tên

Assembly.Load("SampleAssembly, Version=1.0.2004.0, Culture=neutral, PublicKeyToken=8744b20f8da049e3"); 

Ngoài ra hãy chắc chắn rằng bạn đang sử dụng quá tải phù hợp với nhu cầu của bạn (mà thường thực sự là Assembly.Load) http://blogs.msdn.com/b/suzcook/archive/2003/05/29/57143.aspx

EDIT sử dụng điều này:

AssemblyName an = AssemblyName.GetAssemblyName(filePath); 
Assembly.Load(an); 
+0

Ah ok tôi thấy trong ví dụ này http://msdn.microsoft.com/en-us/library/ky3942xh.aspx. Nhưng làm thế nào tôi có thể biết phiên bản nào và khóa nào? – RoflcoptrException

+3

Hãy thử tải quá tải LoadFrom(), mặc dù tôi nghĩ Load() vẫn tốt hơn. Tôi nhớ Có một cách để sử dụng nó, hãy để tôi tìm thấy nó ... –

+0

Và tôi đã theo liên kết này http://msdn.microsoft.com/en-us/library/25y1ya39.aspx. Chỉ có một đối số duy nhất cho phương pháp tải. – RoflcoptrException

Các vấn đề liên quan