All the good time. Studying dynamic compilation I came across a problem - when adding some using to the code text of a compiled program, this code is not compiled, even if the classes from the new using themselves are not used. An example of code that is intended to compile a new program:

using System; using System.CodeDom.Compiler; using System.Collections.Generic; using Microsoft.CSharp; using System.Net.Mail; // intellisense считает ненужной //-----// Dictionary<string, string> providerOptions = new Dictionary<string, string> { {"CompilerVersion", "v3.5"} }; CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions); CompilerParameters compilerParams = new CompilerParameters { OutputAssembly = "D:\\Proga.EXE", GenerateExecutable = true }; compilerParams.ReferencedAssemblies.Add("System.Net.Mail"); CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source); 

Here is the line with the code that compiles normally:

 string source = @" using System; namespace PR { public class Prog { static void Main(string[] args) { Send.SayHello(); } } public class Send { public static void SayHello() { } } } 

But if we change the program very slightly, for example, we add

 using System.Net.Mail; 

enter image description here

the compiler will not work with an error: Could not find the metadata file "System.Net.Mail;"

Question: what is missing in the source code to compile a project with using'es other than System and containing classes of them? And the second question: how to connect DLLs from WinApi into the program so that they compile in a new executable file?

 [DllImport("mydll.dll")] 
  • the compiler will not work. - hinting that he will give some error? - Grundy
  • @Grundy is not at all. Will write that the name of the type or namespace 'Net' is not in the namespace 'System' - Sergey
  • Although according to msdn.microsoft.com/ru-ru/library/system.net.mail (v=vs.110).aspx Net is located exactly in the System - Sergey
  • Add the text of the error text, not a picture - Grundy
  • Isn't the picture clearer? - Sergey

1 answer 1

You need to add a link to the assembly so that its classes are available in code.

If you compile code through CodeDOM, then the references used by the assembly are set via CompilerParameters.ReferencedAssemblies

  • compilerParams.ReferencedAssemblies.Add ("using System.Net.Mail"); - Sergey
  • one
    @ Sergey, I don’t know if there is such an assembly. The assembly name may not coincide with the name of the namespace. But the word "using" part of the assembly name is not exact. - Pavel Mayorov
  • one
    @ Sergey: But it is better to peep in the documentation. In any case, the words “using” in the assembly name are definitely not. - VladD
  • one
    @ Sergey is not, there is a completely different mechanism. DllImport works at runtime, not at compile time; for a compiler, it's just an attribute like that. - Pavel Mayorov
  • one
    @ Sergey yes, similarly - Pavel Mayorov