我需要一些帮助,在动态创建的dll上设置版本。
我使用CodeDomProvider创建dll,但我无法设置输出程序集的版本。
我在一些博客中看到,只有在设置编译器参数以生成可执行文件而非内存中时才能完成。
我的代码是:
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Linq;
namespace dynamicDll
{
class Program
{
static void Main(string[] args)
{
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
parameters.IncludeDebugInformation = true;
parameters.OutputAssembly = "Dynamic.dll";
var assemblies = AppDomain.CurrentDomain.GetAssemblies()
.Where(a => !a.IsDynamic)
.Select(a => a.Location);
parameters.ReferencedAssemblies.AddRange(assemblies.ToArray());
CompilerResults cr = CodeDomProvider.CreateProvider("CSharp")
.CompileAssemblyFromSource(parameters, @"
namespace Dynamic
{
public class DynamicDllClass
{
public int X { get {return 7;}}
}
}");
cr.CompiledAssembly.GetName().Version = new Version("1.0.0.0");
var instance = cr.CompiledAssembly.CreateInstance("Dynamic.DynamicDllClass");
int x = (int) instance.GetType().GetProperty("X").GetGetMethod().Invoke(instance, null);
Debug.Assert(x==7);
Debug.Assert(cr.CompiledAssembly.FullName.Contains("1.0.0.0"));
}
}
}
答案 0 :(得分:2)
您需要使用反射属性将其分配给源代码文件。代码提供程序将查找它,提取它并添加所需的元数据。
按如下方式装饰您的源类:
using System.Reflection;
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
public class Your_Class{}
答案 1 :(得分:1)
谢谢linuser!
以下代码效果很好!
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace dynamicDll
{
class Programs
{
static void Mains(string[] args)
{
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
parameters.IncludeDebugInformation = true;
parameters.OutputAssembly = "Dynamic.dll";
var assemblies = AppDomain.CurrentDomain.GetAssemblies()
.Where(a => !a.IsDynamic)
.Select(a => a.Location);
parameters.ReferencedAssemblies.AddRange(assemblies.ToArray());
var versionString = "1.0.0.0";
CompilerResults cr = CodeDomProvider.CreateProvider("CSharp")
.CompileAssemblyFromSource(parameters, @"
using System.Reflection;
[assembly: AssemblyVersion(" + "\"" + versionString + "\"" + @")]
namespace Dynamic
{
public class DynamicDllClass
{
public int X { get {return 7;}}
}
}");
var instance = cr.CompiledAssembly.CreateInstance("Dynamic.DynamicDllClass");
int x = (int) instance.GetType().GetProperty("X").GetGetMethod().Invoke(instance, null);
Debug.Assert(x==7);
Debug.Assert(cr.CompiledAssembly.FullName.Contains(versionString));
}
}
}