装载组件无法正常工作

我尝试在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 _cs.exe or _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; } 

这很好用,但如果我以后尝试加载程序集,我总是会遇到exception:

 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: 

我的加载方法如下所示:

 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"); } 

任何想法为什么它不起作用?

我认为你的语法错了。 Assembly.load(string)需要程序集名称

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

还要确保你正在使用正确的超载来满足你的需求(通常确实是Assembly.Load) http://blogs.msdn.com/b/suzcook/archive/2003/05/29/57143.aspx

编辑使用此:

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