我需要一些帮助来设置动态创建的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"));
}
}
}
谢谢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));
}
}
}
您需要使用反射属性将其分配给源代码文件。代码提供程序将查找它,提取它并添加所需的元数据。
按照如下方式装饰你的源类:
using System.Reflection;
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
public class Your_Class{}