动态类创建 - FileNotFound异常

时间:2012-11-16 19:40:23

标签: c#

我在运行时尝试动态类创建,但是当我在最后一行运行程序时出现以下错误。有谁知道如何解决这个问题?我尝试在线搜索类似的问题,但没有一个解决方案帮助了我。在此先感谢您的任何帮助

无法加载文件或程序集'file:/// C:\ Users \ xxxx \ AppData \ Local \ Temp \ jelsfwqz.dll'或其依赖项之一。系统找不到指定的文件。

string code2 = "using System;" +
"using System.Collections.Generic;" +
"using System.Linq;" +
"using System.Text;" +
"" +

"    public sealed class CustomClass" +
"    {" +

"    }" 
;


        // Compiler and CompilerParameters
        CSharpCodeProvider codeProvider = new CSharpCodeProvider();

        CompilerParameters compParameters = new CompilerParameters();

        CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");

        // Compile the code
        CompilerResults res = codeProvider.CompileAssemblyFromSource(compParameters, code2);

        // Create a new instance of the class 'CustomClass'
        object myClass = res.CompiledAssembly.CreateInstance("CustomClass");

1 个答案:

答案 0 :(得分:2)

固定代码:

    string code2 = 
    "    public sealed class CustomClass" +
    "    {" +

    "    }"
    ;


    // Compiler and CompilerParameters
    CSharpCodeProvider codeProvider = new CSharpCodeProvider();

    CompilerParameters compParameters = new CompilerParameters();

    CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");

    **compParameters.ReferencedAssemblies.Add("System.dll");**


    // Compile the code
    CompilerResults res = codeProvider.CompileAssemblyFromSource(compParameters, code2);

    // Create a new instance of the class 'CustomClass'
        object myClass = res.CompiledAssembly.CreateInstance("CustomClass");