Прочитать на английском

Поделиться через


CompilerParameters.EmbeddedResources Свойство

Определение

Возвращает файлы ресурсов .NET для включения при компиляции вывода сборки.

public System.Collections.Specialized.StringCollection EmbeddedResources { get; }
[System.Runtime.InteropServices.ComVisible(false)]
public System.Collections.Specialized.StringCollection EmbeddedResources { get; }

Значение свойства

Коллекция, содержащая пути к файлам ресурсов .NET для включения в созданную сборку.

Атрибуты

Примеры

В следующем примере показано использование CompilerParameters для указания различных параметров и параметров компилятора. Этот пример входит в состав более крупного примера использования класса CompilerParameters.

public static bool CompileCode(CodeDomProvider provider,
    String sourceFile,
    String exeFile)
{

    CompilerParameters cp = new CompilerParameters();

    // Generate an executable instead of
    // a class library.
    cp.GenerateExecutable = true;

    // Set the assembly file name to generate.
    cp.OutputAssembly = exeFile;

    // Generate debug information.
    cp.IncludeDebugInformation = true;

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

    // Save the assembly as a physical file.
    cp.GenerateInMemory = false;

    // Set the level at which the compiler
    // should start displaying warnings.
    cp.WarningLevel = 3;

    // Set whether to treat all warnings as errors.
    cp.TreatWarningsAsErrors = false;

    // Set compiler argument to optimize output.
    cp.CompilerOptions = "/optimize";

    // Set a temporary files collection.
    // The TempFileCollection stores the temporary files
    // generated during a build in the current directory,
    // and does not delete them after compilation.
    cp.TempFiles = new TempFileCollection(".", true);

    if (provider.Supports(GeneratorSupport.EntryPointMethod))
    {
        // Specify the class that contains
        // the main method of the executable.
        cp.MainClass = "Samples.Class1";
    }

    if (Directory.Exists("Resources"))
    {
        if (provider.Supports(GeneratorSupport.Resources))
        {
            // Set the embedded resource file of the assembly.
            // This is useful for culture-neutral resources,
            // or default (fallback) resources.
            cp.EmbeddedResources.Add("Resources\\Default.resources");

            // Set the linked resource reference files of the assembly.
            // These resources are included in separate assembly files,
            // typically localized for a specific language and culture.
            cp.LinkedResources.Add("Resources\\nb-no.resources");
        }
    }

    // Invoke compilation.
    CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile);

    if(cr.Errors.Count > 0)
    {
        // Display compilation errors.
        Console.WriteLine("Errors building {0} into {1}",
            sourceFile, cr.PathToAssembly);
        foreach(CompilerError ce in cr.Errors)
        {
            Console.WriteLine("  {0}", ce.ToString());
            Console.WriteLine();
        }
    }
    else
    {
        Console.WriteLine("Source {0} built into {1} successfully.",
            sourceFile, cr.PathToAssembly);
        Console.WriteLine("{0} temporary files created during the compilation.",
            cp.TempFiles.Count.ToString());
    }

    // Return the results of compilation.
    if (cr.Errors.Count > 0)
    {
        return false;
    }
    else
    {
        return true;
    }
}

Комментарии

Внедренные ресурсы встроены в созданный выходной файл сборки. Включение файлов с помощью этого свойства похоже на аргумент командной /resource строки, поддерживаемый многими компиляторами .NET.

Не все компиляторы поддерживают файлы ресурсов .NET, поэтому следует проверить эту поддержку, вызвав Supports метод с флагом Resources.

Добавьте один или несколько путей к файлу ресурсов .NET, StringCollection чтобы внедрить ресурсы файлов в скомпилированную сборку. Добавление повторяющегося или недопустимого пути к файлу приводит к ошибкам компиляции; Убедитесь, что каждая строка указывает уникальный путь к допустимому файлу ресурсов .NET.

Используйте , EmbeddedResources чтобы включить ресурсы .NET по умолчанию или нейтральные язык и региональные параметры для сборки LinkedResources ; используйте свойство для ссылки на ресурсы .NET во вспомогательных сборках.

Применяется к

Продукт Версии
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

См. также раздел