加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在使用Roslyn进行编译时设置程序集版本,文化和公钥令

发布时间:2020-12-15 23:26:15 所属栏目:百科 来源:网络整理
导读:我正在使用Roslyn将Visual Studio中的CSharpCompilation对象发送到文件.生成的DLL不包含除程序集元数据之外的任何程序集信息,并且我想添加版本并在可能的情况下对其进行签名.如何用Roslyn完成这些工作? 解决方法 您需要包含设置Assembly *属性的源代码,就像
我正在使用Roslyn将Visual Studio中的CSharpCompilation对象发送到文件.生成的DLL不包含除程序集元数据之外的任何程序集信息,并且我想添加版本并在可能的情况下对其进行签名.如何用Roslyn完成这些工作?

解决方法

您需要包含设置Assembly *属性的源代码,就像在VS C#项目模板中一样.如果您已经这样做,则设置.NET版本信息.您可以使用Reflection或ILSpy等工具阅读该信息.

这样Explorer就不会在其属性页面中显示任何版本信息.资源管理器仅显示Win32 VersionInfo而不是.NET版本信息.您需要使用Rosyln发出Win32资源代码来设置这些值.幸运的是,有一种方法可以从.NET自动生成Win32信息:CreateDefaultWin32Resources.

这是一个完整且有效的代码示例:

public void VersionInfoExample()
{
    // 1. Generate AssemblyInfo.cs-like C# code and parse syntax tree
    StringBuilder asmInfo = new StringBuilder();

    asmInfo.AppendLine("using System.Reflection;");
    asmInfo.AppendLine("[assembly: AssemblyTitle("Test")]");
    asmInfo.AppendLine("[assembly: AssemblyVersion("1.1.0")]");
    asmInfo.AppendLine("[assembly: AssemblyFileVersion("1.1.0")]");
    // Product Info
    asmInfo.AppendLine("[assembly: AssemblyProduct("Foo")]");
    asmInfo.AppendLine("[assembly: AssemblyInformationalVersion("1.3.3.7")]");

    var syntaxTree = CSharpSyntaxTree.ParseText(asmInfo.ToString(),encoding: Encoding.Default);

    // 2. Create compilation
    string mscorlibPath = typeof(object).Assembly.Location;
    MetadataReference mscorlib = MetadataReference.CreateFromFile(mscorlibPath,new MetadataReferenceProperties(MetadataImageKind.Assembly));
    CSharpCompilationOptions options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

    CSharpCompilation compilation = CSharpCompilation.Create("Test.dll",references: new[] { mscorlib },syntaxTrees: new[] { syntaxTree },options: options);

    // 3. Emit code including win32 version info
    using (MemoryStream dllStream = new MemoryStream())
    using (MemoryStream pdbStream = new MemoryStream())
    using (Stream win32resStream = compilation.CreateDefaultWin32Resources(
                                                                versionResource: true,// Important!
                                                                noManifest: false,manifestContents: null,iconInIcoFormat: null))
    {
        EmitResult result = compilation.Emit(
                                     peStream: dllStream,pdbStream: pdbStream,win32Resources: win32resStream);

        System.IO.File.WriteAllBytes("Test.dll",dllStream.ToArray());
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读