2017-01-23 46 views
0

我想用CSharpCodeProvider動態編譯代碼。在引用的程序集中,我爲typeof(Program).Assembly.CodeBase)添加了一個引用參數,正如建議的here,但它不起作用。我還得到一個錯誤說CSharpCodeProvider如何引用當前程序集

error CS0006: Metadata file 'file:///C:/Code/MyProject/bin/MyProject.DLL' could not be found; 

使用該名稱的文件不存在的 - 唯一不同的是,文件擴展名顯示在小寫文件瀏覽器(「.DLL」),但除此之外,從錯誤信息的文件名匹配我想引用的dll的名稱和路徑。

任何想法爲什麼編譯器在這種情況下將無法看到引用的DLL?
這裏是我的代碼的相關章節:

 CompilerResults result = null; 
     CompilerParameters parms = new CompilerParameters(); 
     parms.GenerateExecutable = false; 
     parms.GenerateInMemory = true; 
     parms.OutputAssembly = "MyOutputAssembly"; 
     parms.ReferencedAssemblies.Add("System.dll"); 
     parms.ReferencedAssemblies.Add("System.Data.dll"); 
     parms.ReferencedAssemblies.Add("mscorlib.dll"); 
     parms.ReferencedAssemblies.Add(typeof(Program).Assembly.CodeBase); // Reference the current assembly 

     // Lock because CSharpCodeProvider can only compile the code once per time slot 
     lock (lockCompile) 
     { 
      using (CSharpCodeProvider codeProvider = new CSharpCodeProvider()) 
      { 
       result = codeProvider.CompileAssemblyFromSource(parms, new string[] { code.ToString() }); 
      } 
     } 
+0

嘗試使用'typeof(Program).Assembly.Location'而不是'.CodeBase'。程序集上的'.Location'屬性將返回一條直線路徑,而'.CodeBase'則以URI形式返回該位置。我不確定,但我認爲可能存在與加載遠程託管代碼有關的情況,其中'.Location'不會給你任何東西,'.CodeBase'可能會給出例如。一個'http' URI,但在你的場景中,這聽起來像你的程序集總是本地化的,所以你應該總是有一個有效的'.Location'值。 :-) –

+0

完成了,謝謝:-) –

+0

謝謝!這工作 - 如果你添加一個答案,我會標記爲答案 - 和檢索從.CodeBase一個非常不同的路徑 - 基本代碼檢索的bin文件夾的位置,而位置得到了一個臨時目錄:C:\\的Windows \\ Microsoft.NET \\ \\ Framework64 \\ v4.0.30319 ASP.NET臨時文件\\ \\ myIISDirName \\ 65307448 \\ ec575f43組裝\\ \\ DL3 \\ d46288d9 \\ 3e71eb5a_c275d201 MyProject.dll。這篇文章(http://stackoverflow.com/questions/864484/getting-the-path-of-the-current-assembly)似乎表明,.Location拉到陰影複製之前的地址,讓我有點糊塗了當位置是安全的... – user756366

回答

1

嘗試使用的typeof(Program).Assembly.Location代替.CodeBase。程序集上的.Location屬性將返回一個直接加載的實際文件的路徑,而.CodeBase以URI形式返回caonical位置。我不確定,但我認爲可能會出現與加載遠程託管代碼有關的情況,其中.Location不會給你任何東西,.CodeBase可能會給出例如一個http URI,但在您的場景中,它聽起來像您的程序集始終是本地的,所以您應始終擁有有效的.Location值。 :-)

+0

最後我要與新的System.Uri(Assembly.GetExecutingAssembly()。EscapedCodeBase).LocalPath每個優點張貼在http://stackoverflow.com/questions/864484/getting-在路的最電流組裝,但在任何情況下,「標記」的回答上面也工作,讓我有! – user756366

相關問題