2012-05-01 52 views
6

我不太確定該怎麼做。總體目標是能夠獲取用戶腳本,並在.NET環境中執行它。我有大部分的代碼編寫和東西工作提供我不會嘗試加載我自己的程序集。但是,爲了安全地讓用戶訪問系統的內部部分,已經創建了代理DLL。這是問題出現的地方。使用CompileAssemblyFromSource加載自定義程序集

現在這個代理DLL有一件事,它是一個接口。

CompilerParameters options = new CompilerParameters(); 
options.GenerateExecutable = false; 
options.GenerateInMemory = true; 
options.ReferencedAssemblies.Add("System.dll"); 
options.ReferencedAssemblies.Add("ScriptProxy.dll"); 

Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); 
CompilerResults result = provider.CompileAssemblyFromSource(options, script); 

// This line here throws the error: 
return result.CompiledAssembly; 

運行上面的代碼,它引發以下錯誤:

System.IO.FileNotFoundException : Could not load file or assembly 'file:///C:\Users...\AppData\Local\Temp\scts5w5o.dll' or one of its dependencies. The system cannot find the file specified.

當然,我首先想到的是,「......什麼是scts5w5o.dll?」

這是ScriptProxy.dll加載不正常,還是ScriptProxy.dll本身試圖加載依賴項,它們在某個臨時文件中?或者是完全不同的東西?

我應該提到,我從NUnit測試運行器執行此代碼。我不確定這是否有所作爲。

回答

7

這是因爲編譯步驟失敗了,你有沒有檢查錯誤...

static Assembly Compile(string script) 
    { 
     CompilerParameters options = new CompilerParameters(); 
     options.GenerateExecutable = false; 
     options.GenerateInMemory = true; 
     options.ReferencedAssemblies.Add("System.dll"); 
     options.ReferencedAssemblies.Add("ScriptProxy.dll"); 

     Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); 
     CompilerResults result = provider.CompileAssemblyFromSource(options, script); 

     // Check the compiler results for errors 
     StringWriter sw = new StringWriter(); 
     foreach (CompilerError ce in result.Errors) 
     { 
      if (ce.IsWarning) continue; 
      sw.WriteLine("{0}({1},{2}: error {3}: {4}", ce.FileName, ce.Line, ce.Column, ce.ErrorNumber, ce.ErrorText); 
     } 
     // If there were errors, raise an exception... 
     string errorText = sw.ToString(); 
     if (errorText.Length > 0) 
      throw new ApplicationException(errorText); 

     return result.CompiledAssembly; 
    } 
+0

這將是有道理的。我現在就試試看。 –

+1

我打算把這個標記爲答案,因爲它雖然沒有解決每個問題的問題,但它確實幫助我獲得了真正的錯誤信息,這幾乎同樣有幫助! –

+0

那麼你如何解決實際問題! – Moumit

3

我不認爲標記爲answer後真是答案! ......不過,我找到了答案here

parameters.ReferencedAssemblies.Add(typeof(<TYPE FROM DOMAIN.DLL>).Assembly.Location); 

它的意思是,如果你想添加dll參考是第三方(有時.NET的DLL還贈送例外),那麼只需將其複製executable folder ..它會正常工作..否則你也可以定義完整路徑..

相關問題