本文整理汇总了C#中Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromFile方法的典型用法代码示例。如果您正苦于以下问题:C# CSharpCodeProvider.CompileAssemblyFromFile方法的具体用法?C# CSharpCodeProvider.CompileAssemblyFromFile怎么用?C# CSharpCodeProvider.CompileAssemblyFromFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CSharp.CSharpCodeProvider
的用法示例。
在下文中一共展示了CSharpCodeProvider.CompileAssemblyFromFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Compile
public Tuple<StringCollection, Assembly> Compile(string[] dllFiles, string[] sourceFiles, string outputAssemblyPath)
{
var providerOptions = new Dictionary<string,
string> { {
"CompilerVersion",
"v4.0"
}
};
CodeDomProvider codeProvider = new CSharpCodeProvider(providerOptions);
var compilerParameters = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true,
IncludeDebugInformation = true
};
compilerParameters.ReferencedAssemblies.AddRange(dllFiles);
compilerParameters.ReferencedAssemblies.Add("System.dll");
compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
compilerParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
compilerParameters.ReferencedAssemblies.Add("System.ComponentModel.dll");
compilerParameters.ReferencedAssemblies.Add("System.Xml.Serialization.dll");
var result = codeProvider.CompileAssemblyFromFile(compilerParameters, sourceFiles);
return new Tuple<StringCollection,
Assembly>(result.Output, result.Errors.Count > 0 ? null : result.CompiledAssembly);
}
示例2: CompileSiteModels
public void CompileSiteModels()
{
DirectoryInfo di = new DirectoryInfo(SysPath.SiteModelsDirectory);
FileInfo[] fiar = di.GetFiles("*.cs");
String[] fisar = new String[fiar.Length];
for (int i = 0; i < fiar.Length; i++)
{
fisar[i] = fiar[i].FullName;
}
CompilerParameters parameters = new CompilerParameters(new String[] { "System.dll", "NStag.dll", "nhibernate.dll" });
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
parameters.OutputAssembly = this.DomainName;
parameters.CompilerOptions = String.Concat("/lib:", SysPath.GetLibDirectory());
CSharpCodeProvider cprovider = new CSharpCodeProvider();
CompilerResults results = cprovider.CompileAssemblyFromFile(parameters, cspath);
if (results.Errors.HasErrors)
{
throw new Exception(results.Errors[0].ErrorText);
}
}
示例3: Compile
/// <summary>
/// Compiles the source files found within the scriptRepository directory matching the ICompiler.ScriptExtension
/// The Compiler defaults to the C# 4.0 compiler if none other is supplied via the ICompiler.CompilerOptions argument.
/// </summary>
/// <param name="param">Compiler Parameters that can be supplied to customize the compilation of the source.</param>
/// <returns>Returns true if the compilation was completed without error.</returns>
public Boolean Compile(CompilerParameters param, String scriptRepository)
{
// Make sure we have a compiler version supplied.
if (!CompilerOptions.ContainsKey("CompilerVersion"))
CompilerOptions.Add("CompilerVersion", "v4.0");
// Instance a reference to the C# code provider, this is what will perform the compiling.
CSharpCodeProvider provider = new CSharpCodeProvider(CompilerOptions);
// Create an array of script files found within the ScriptRepository matching the ScriptExtension properties.
if (!Directory.Exists(scriptRepository))
Directory.CreateDirectory(scriptRepository);
String[] scripts = Directory.GetFiles(scriptRepository, "*" + this.ScriptExtension, SearchOption.AllDirectories);
if (scripts.Length > 0)
{
// Compile the scripts and provide the Results property with a reference to the compilation results.
Results = provider.CompileAssemblyFromFile(param, scripts);
// if the compiler has errors, return false.
if (Results.Errors.HasErrors)
return false;
else
return true;
}
else
{
Results = new CompilerResults(new TempFileCollection());
return false;
}
}
示例4: CompileCDir
public CompilerResults CompileCDir(string path, string dllName)
{
// ArrayList refs = new ArrayList();
//refs.Add("System");
//refs.Add("System.Collections.Generic");
//refs.Add("System.Text");
string Output = dllName;
CSharpCodeProvider provider = new CSharpCodeProvider();
string[] files = GetScripts(path, "*.cs");
// CodeDomProvider dom = CodeDomProvider.CreateProvider("CSharp");
// string[] refers = (string[])refs.ToArray(typeof(string));
CompilerParameters param = new CompilerParameters(null,Output,false);
//System.CodeDom.Compiler.CompilerParameters param = new CompilerParameters();
param.GenerateExecutable = false;
//param.OutputAssembly = Output;
//CompilerResults results = dom.CompileAssemblyFromSource(param, sources);
CompilerResults results = provider.CompileAssemblyFromFile(param, files);
if (results.Errors.Count > 0)
{
foreach (CompilerError Comperr in results.Errors)
{
errors = errors + "Line " + Comperr.Line + ": " + Comperr.ErrorText + "\n";
}
return results;
}
return results;
}
示例5: Compile
public string Compile(string sourcePath, IEnumerable<string> referencedLibraries = null)
{
using(var provider = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v4.0" } }))
{
var outputFileName = TemporaryFilesManager.Instance.GetTemporaryFile();
var parameters = new CompilerParameters { GenerateInMemory = false, GenerateExecutable = false, OutputAssembly = outputFileName };
parameters.ReferencedAssemblies.Add("mscorlib.dll");
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
parameters.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(Machine)).Location); // Core
parameters.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(Serializer)).Location); // Migrant
if(referencedLibraries != null)
{
foreach(var lib in referencedLibraries)
{
parameters.ReferencedAssemblies.Add(lib);
}
}
var result = provider.CompileAssemblyFromFile(parameters, new[] { sourcePath });
if(result.Errors.HasErrors)
{
var errors = result.Errors.Cast<object>().Aggregate(string.Empty,
(current, error) => current + ("\n" + error));
throw new RecoverableException(string.Format("There were compilation errors:\n{0}", errors));
}
return outputFileName;
}
}
示例6: Compile
public void Compile(string[] sources)
{
var compilerParams = new CompilerParameters
{
CompilerOptions = "/target:library /optimize",
GenerateExecutable = false,
GenerateInMemory = true,
IncludeDebugInformation = true
};
compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
compilerParams.ReferencedAssemblies.Add("System.dll");
compilerParams.ReferencedAssemblies.Add("System.Core.dll");
compilerParams.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
foreach (var library in Directory.GetFiles(_libraryLocation, "*.dll"))
{
compilerParams.ReferencedAssemblies.Add(library);
}
CodeDomProvider codeProvider = new CSharpCodeProvider();
CompilerResults results = codeProvider.CompileAssemblyFromFile(compilerParams, sources);
if(results.Errors.Count > 0)
{
Console.WriteLine("Error found while recompiling your files:");
foreach (string line in results.Output)
{
Console.WriteLine(line);
}
}
}
示例7: CompilesWithoutErrors
/// <summary>Verifies that the specified files compile without errors.</summary>
/// <param name="files">The files to compile.</param>
/// <param name="references">Te assemblies to reference during compilation.</param>
public static void CompilesWithoutErrors(IEnumerable<FileInfo> files, params Assembly[] references)
{
if (files == null || !files.Any())
{
throw new AssertionException("No files specified.");
}
using (var provider = new CSharpCodeProvider())
{
var parameters = new CompilerParameters();
foreach (var reference in references)
{
parameters.ReferencedAssemblies.Add(reference.Location);
}
var selected = files.Select(file => file.FullName).ToArray();
var results = provider.CompileAssemblyFromFile(parameters, selected);
foreach (var error in results.Errors.OfType<CompilerError>())
{
Console.WriteLine("{0}{1}{2:0000}: {3}",
Path.GetFileName(error.FileName),
Environment.NewLine,
error.Line,
error.ErrorText);
}
var errorCount = results.Errors.OfType<CompilerError>().Count(e => !e.IsWarning);
var warnCount = results.Errors.OfType<CompilerError>().Count(e => e.IsWarning);
Assert.IsFalse(results.Errors.HasErrors, "With {0} error(s). See console output for details.", errorCount);
Assert.IsFalse(results.Errors.HasWarnings, "With {0} warning(s). See console output for details.", warnCount);
}
}
示例8: Compile
public static CompilerResults Compile(this DirectoryInfo[] compileTargets, string fileName, string[] referenceAssemblies, bool executable)
{
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = executable;
parameters.OutputAssembly = fileName;
List<string> compilerOptions = new List<string>();
foreach (string referenceAssembly in referenceAssemblies)
{
compilerOptions.Add("/reference:" + referenceAssembly);
}
parameters.CompilerOptions = compilerOptions.ToArray().ToDelimited(" ");
List<string> fileNames = new List<string>();
foreach (DirectoryInfo targetDirectory in compileTargets)
{
foreach (FileInfo fileInfo in FsUtil.GetFilesWithExtension(targetDirectory.FullName, ".cs"))
{
fileNames.Add(fileInfo.FullName);
}
}
return codeProvider.CompileAssemblyFromFile(parameters, fileNames.ToArray());//.CompileAssemblyFromFileBatch(parameters, fileNames.ToArray());
}
示例9: BuildAssemblyFromHbm
public static Assembly BuildAssemblyFromHbm(string assemblyName,params string[] mappings)
{
//uses hbm2net to create classes files.
FileInfo configFile = new FileInfo(Path.GetTempFileName());
List<string> hbms = new List<string>();
// the mapping file needs to be written to the same
// directory as the config file for this test
foreach (var hbm in mappings)
{
FileInfo mappingFile = new FileInfo(Path.Combine(configFile.DirectoryName, hbm));
if (mappingFile.Exists)
mappingFile.Delete();
ResourceHelper.WriteToFileFromResource(mappingFile, hbm);
hbms.Add(mappingFile.FullName);
}
TestHelper.CreateConfigFile(configFile, T4DefaultTemplate, T4Renderer, "unused", "clazz.GeneratedName+\".generated.cs\"");
List<string> args = new List<string>();
args.Add("--config=" + configFile.FullName);
args.AddRange(hbms);
FileObserver fo = new FileObserver();
CodeGenerator.Generate(args.ToArray(), fo);
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters options = new CompilerParameters();
options.GenerateInMemory = true;
options.ReferencedAssemblies.Add(typeof(ISet).Assembly.Location);
options.OutputAssembly = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyName + ".dll");
options.GenerateInMemory = false;
CompilerResults res = provider.CompileAssemblyFromFile(options, fo.Files);
foreach (var e in res.Errors)
Console.WriteLine("Compiler Error:" + e);
Assert.AreEqual(0, res.Errors.Count);
return res.CompiledAssembly;
}
示例10: MainThreadEntry
internal static void MainThreadEntry(object state)
{
var args = (string[])state;
if (args.Length < 2)
throw new Exception("Dunno what to run.");
var appDirectory = Path.GetFullPath(args[1]);
var appFile = Path.Combine(appDirectory, "App.cs");
var appConfigFile = Path.Combine(appDirectory, "BlazeApp.json.config");
if (!File.Exists(appConfigFile))
throw new Exception("App configuration file was not found.");
if (!File.Exists(appFile))
throw new Exception("No app entry found.");
var appConfigFileContent = File.ReadAllText(appConfigFile);
var appConfig = JsonConvert.DeserializeObject<AppConfiguration>(appConfigFileContent);
var tempAssemblyPath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
var codeProvider = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", appConfig.CompilerVersion } });
var compilerParameters = new CompilerParameters(appConfig.References, tempAssemblyPath, false)
{
GenerateInMemory = true
};
var compilerResult = codeProvider.CompileAssemblyFromFile(compilerParameters, new[] { appFile });
if (compilerResult.Errors.Count > 0)
throw new Exception("There were errors during compilation.");
// TODO: Invoke compiled entry method -- http://stackoverflow.com/questions/14479074/c-sharp-reflection-load-assembly-and-invoke-a-method-if-it-exists
}
示例11: BuildParser
private Assembly BuildParser(string code)
{
var source = Path.Combine(Path.GetDirectoryName(typeof(Grammar).Assembly.Location), "TestGrammarParser.cs");
var output = Path.Combine(Path.GetDirectoryName(typeof(Grammar).Assembly.Location), "TestGrammarParser.dll");
File.WriteAllText(source, code);
File.Delete(output);
var cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Core.dll");
cp.ReferencedAssemblies.Add(typeof(Grammar).Assembly.Location);
cp.OutputAssembly = output;
cp.IncludeDebugInformation = true;
cp.GenerateInMemory = false;
cp.TreatWarningsAsErrors = false;
var csp = new CSharpCodeProvider();
var cr = csp.CompileAssemblyFromFile(cp, source);
if (cr.Errors.Count > 0)
{
throw new Exception(cr.Errors[0].ErrorText);
}
else
{
return Assembly.LoadFile(output);
}
}
示例12: CompileC
public bool CompileC(string[] sources, string dllName)
{
string Output = dllName;
CSharpCodeProvider provider = new CSharpCodeProvider();
// CodeDomProvider dom = CodeDomProvider.CreateProvider("CSharp");
System.CodeDom.Compiler.CompilerParameters param = new CompilerParameters();
param.GenerateExecutable = false;
param.OutputAssembly = Output;
//CompilerResults results = dom.CompileAssemblyFromSource(param, sources);
CompilerResults results = provider.CompileAssemblyFromFile(param, sources);
if (results.Errors.Count > 0)
{
foreach(CompilerError Comperr in results.Errors)
{
errors = errors + "Line " + Comperr.Line + ": " + Comperr.ErrorText + "\n";
}
return false;
}
return true;
}
示例13: Compile
public static void Compile(string finalOutputAssembly, string[] sources, string[] referencedAssemblies, string compilerVersion, string compilerOptions = null)
{
//string finalOutputAssembly = "test";
//string[] sources = new string[] { };
//string[] referencedAssemblies = new string[] { };
//string compilerOptions = null;
Dictionary<string, string> providerOption = new Dictionary<string, string>();
//"v4.0"
providerOption.Add("CompilerVersion", compilerVersion);
CSharpCodeProvider provider = new CSharpCodeProvider(providerOption);
CompilerParameters options = new CompilerParameters();
options.CompilerOptions = compilerOptions;
options.GenerateInMemory = false;
options.OutputAssembly = finalOutputAssembly;
options.GenerateExecutable = true;
options.IncludeDebugInformation = true;
// WarningLevel : from http://msdn.microsoft.com/en-us/library/13b90fz7.aspx
// 0 Turns off emission of all warning messages.
// 1 Displays severe warning messages.
// 2 Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members.
// 3 Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false.
// 4 (the default) Displays all level 3 warnings plus informational warnings.
options.WarningLevel = 4;
foreach (string referencedAssembly in referencedAssemblies)
options.ReferencedAssemblies.Add(referencedAssembly);
CompilerResults results = provider.CompileAssemblyFromFile(options, sources);
}
示例14: CreateModel
/// <summary>
/// Creates data model object
/// </summary>
/// <param name="modelName">a name of model in configuration</param>
/// <param name="uid">Data base unique Id</param>
/// <returns>Data nmodel object</returns>
public static IModel CreateModel(String modelName, Object uid)
{
String cspath = SysPath.GetModelSourceFile(modelName);
CompilerParameters parameters = new CompilerParameters(new String[] { "System.dll", "NStag.dll", "nhibernate.dll" });
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
parameters.CompilerOptions = String.Concat("/lib:", SysPath.GetLibDirectory());
CSharpCodeProvider cprovider = new CSharpCodeProvider();
CompilerResults results = cprovider.CompileAssemblyFromFile(parameters, cspath);
if (results.Errors.HasErrors)
{
throw new Exception(results.Errors[0].ErrorText);
}
Type[] types = results.CompiledAssembly.GetExportedTypes();
foreach (Type t in types)
{
Type[] interfaces = t.GetInterfaces();
foreach (Type i in interfaces)
{
if (i == typeof(IModel))
{
//OrmHelper.GetCurrentSession().SessionFactory.
return (IModel)OrmHelper.GetCurrentSession().Get(t, uid);
}
}
}
return null;
}
示例15: CompileMigration
protected override Type CompileMigration(MigrationReference migrationReference)
{
Dictionary<string, string> providerOptions = new Dictionary<string, string>();
if (!String.IsNullOrEmpty(_configuration.CompilerVersion))
{
providerOptions["CompilerVersion"] = _configuration.CompilerVersion;
}
CodeDomProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.OutputAssembly = Path.Combine(_workingDirectoryManager.WorkingDirectory,
Path.GetFileNameWithoutExtension(migrationReference.Path) + ".dll");
parameters.ReferencedAssemblies.Add(typeof (IDatabaseMigration).Assembly.Location);
parameters.ReferencedAssemblies.Add(typeof (SqlMoney).Assembly.Location);
parameters.IncludeDebugInformation = true;
foreach (string reference in _configuration.References)
{
parameters.ReferencedAssemblies.Add(reference);
}
_log.InfoFormat("Compiling {0}", migrationReference);
CompilerResults cr = provider.CompileAssemblyFromFile(parameters, GetFiles(migrationReference.Path).ToArray());
if (cr.Errors.Count > 0)
{
foreach (CompilerError error in cr.Errors)
{
_log.ErrorFormat("{0}", error);
}
throw new InvalidOperationException();
}
if (cr.CompiledAssembly == null)
{
throw new InvalidOperationException();
}
return MigrationHelpers.LookupMigration(cr.CompiledAssembly, migrationReference);
}