Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Разработка Windows Forms > CSharp


Автор: desevg 1.3.2009, 02:41
Код

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.IO;
using System.Globalization;
using System.Security;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string sourceName = "D:\\test\\ConsoleApplication1\\ConsoleApplication1\\file.cs";
                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 <source>_cs.exe or <source>_vb.exe.

                    String exeName = String.Format(@"D:\{0}.exe", 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);
                    }

            }
            catch (SecurityException e)
            {
                Console.WriteLine(e);        
            }
        
    
        }
    }
}



использую пример из MSDN. но при компиляции выдает ошибки

http://ipicture.ru/


как можно указать программно ссылки на эти библиотеки для компилируемого динамически сборки?

Автор: Soah 1.3.2009, 16:45
http://msdn.microsoft.com/ru-ru/library/dz9199dk.aspx

Цитата

При создании проекта Visual Basic или Visual C# в Visual Studio ссылки на наиболее часто используемые библиотеки DLL (сборки), содержащие базовые классы, добавляются автоматически. Тем не менее, если необходимо использовать тип, находящийся в библиотеке DLL, ссылка на которую отсутствует, потребуется добавить ссылку на нее. Для добавления сборок служит диалоговое окно Добавление ссылки.

Автор: WarHog 1.3.2009, 17:20
По-моему, desevg использует command-line. Если так, то используй либо параметр командной строки /r (/r:System.Core.dll etc.) либо файл параметров (response file) - например, стандартный csc.rsp

Автор: desevg 1.3.2009, 20:19
по моему вопрос был не понят....

Исходный текст проги.
Код

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.IO;
using System.Globalization;
using System.Security;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string sourceName = "D:\\test\\ConsoleApplication1\\ConsoleApplication1\\file.cs";
                FileInfo sourceFile = new FileInfo(sourceName);

                CodeDomProvider provider = null;
               

                // 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 <source>_cs.exe or <source>_vb.exe.

                    String exeName = String.Format(@"D:\{0}.exe", 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);
                    }

                }
                
            }
            catch (SecurityException e)
            {
                Console.WriteLine(e);        
            }
        
    
        }
    }
}





Файл, который я динамически компилирую с помощью кода, который привел выше. При таком расположении дел, будет создан ехе файл, выполняющий код, приведеный ниже.
Код

using System;
using System.Collections.Generic;
using System.Text;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("asd");
            Console.ReadLine();
        }

    }
}



Если я добавлю в файл file.cs одно разрешение на пространство имен, на пример using System.Linq;, то мне при выполнении кода, компилирующего file.cs выдаст, что не хватает ссылки на System.Linq.. как мне программно указать ссыдку для компилируемой сборки...


надеюсь понятно изложил))

Автор: Kakadu 1.3.2009, 21:21
Код

    CompilerParameters cp = new CompilerParameters();
    // Add an assembly reference.
    cp.ReferencedAssemblies.Add( "System.dll" );

http://msdn.microsoft.com/ru-ru/library/system.codedom.compiler.compilerparameters.aspx

Автор: desevg 1.3.2009, 22:10
спасибо

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)