如何从可执行文件中读取嵌入式程序集的版本号?

时间:2018-07-12 00:42:46

标签: c#

通过将以下内容添加到我的.csproj文件中,我已经将类库嵌入了可执行文件中。

  <Target Name="AfterResolveReferences">
    <ItemGroup>
      <EmbeddedResource Include="@(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'">
        <LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>
      </EmbeddedResource>
    </ItemGroup>

然后,我通过订阅AppDomain的{​​{1}}事件以编程方式加载程序集,如下所示:

AssemblyResolve

然后我以后在我的应用程序中希望读取嵌入式库的版本号。嵌入式库中有一个using System; using System.Reflection; using System.Windows.Forms; using xofz.Research.UI.Forms; internal static class EntryPoint { [STAThread] private static void Main(string[] args) { AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => loadEmbeddedAssembly(e.Name); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var bootstrapper = new FormsBootstrapper(); new FormsAppBase(bootstrapper).Run( args); } private static Assembly loadEmbeddedAssembly(string name) { var assemblyName = new AssemblyName(name); if (name.EndsWith("Retargetable=Yes")) { return Assembly.Load(assemblyName); } var container = Assembly.GetExecutingAssembly(); var path = assemblyName.Name + ".dll"; using (var stream = container.GetManifestResourceStream(path)) { if (stream == null) { return null; } var bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); return Assembly.Load(bytes); } } } 方法试图做到这一点:

ReadCoreVersion()

但是,当我尝试在应用程序的代码中调用此方法时,它抛出了public virtual string ReadCoreVersion() { var ea = Assembly.GetExecutingAssembly(); var vi = FileVersionInfo.GetVersionInfo( ea.Location); return vi.FileVersion; }

有什么办法读取嵌入式程序集的版本号?

编辑:检查程序集的Location属性组成之后,该属性为null或为空。如何获取嵌入式程序集的位置以获取其版本,还是必须先将程序集刷新到磁盘上?

2 个答案:

答案 0 :(得分:0)

您需要确保传递给FileVersionInfo.GetVersionInfo的路径是正确的格式。

  1. Assembly.Location returns UNC path
  2. FileVersionInfo.GetVersionInfo expects a fully-qualified path.

您将需要自己解析字符串以将路径转换为正确的格式,或者使用内置方法为您进行转换。

This page在不同格式上都有很好的分类。

答案 1 :(得分:0)

事实证明,AssemblyName在这里有很大帮助。通过如下修改ReadCoreVersion()方法,我能够获得它来显示嵌入式程序集的版本信息!

public virtual string ReadCoreVersion()
{
    var ea = Assembly.GetExecutingAssembly();
    var an = new AssemblyName(ea.FullName);
    var v = an.Version;
    var versionBuilder = new StringBuilder();
    versionBuilder.Append(v.Major);
    versionBuilder.Append('.');
    versionBuilder.Append(v.Minor);
    versionBuilder.Append('.');
    versionBuilder.Append(v.Build);
    versionBuilder.Append('.');
    versionBuilder.Append(v.Revision);

    return versionBuilder.ToString();
}