如何从已从字节加载的程序集获取FileVersion ?

本文关键字:程序集 获取 FileVersion 加载 字节 | 更新日期: 2023-09-27 18:13:44

我有一些程序集存储在数据库中的Oracle BLOB字段中。我正在加载程序集,创建类的实例等都成功。然而,我想访问加载程序集的AssemblyFileVersion,但似乎无法找到如何做到这一点。

我尝试了很多东西,包括下面的代码:

var assembly = Assembly.Load(plugInBytes);
var version = FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion;

但是,当程序集从字节加载时,assembly.Location为空,之后没有任何好的事情发生。

只是在寻找正确的方向。

如何从已从字节加载的程序集获取FileVersion ?

如果已经应用了AssemblyFileVersion属性,不能直接使用:

var version = assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)
                      .Cast<AssemblyFileVersionAttribute>()
                      .Select(attr => attr.Version)
                      .FirstOrDefault();
if (version != null)
{
    // Got the version number...
}

你可以试试

 public bool GetVersion(string fileName)
 {
       Assembly asm = null;
       try
       {
               asm = Assembly.LoadFrom(fileName);
        }
        catch (Exception err)
        {
               this._errMsg = err.Message;
               return false;
         }
         if (asm != null)
         {
               this._info = new AssemblyInformation();
               this._info.Name = asm.GetName().Name;
               this._info.Version = asm.GetName().Version.ToString();
              this._info.FullName = asm.GetName().ToString();
         }
         else
         {
               this._errMsg = "Invalid assembly";
               return false;
          } 
          return GetReferenceAssembly(asm);
  }
  public bool GetVersion(Assembly asm)
  {
         if (asm != null)
         {
              this._info = new AssemblyInformation();
              this._info.Name = asm.GetName().Name;
             this._info.Version = asm.GetName().Version.ToString();
             this._info.FullName = asm.GetName().ToString();
         }
         else
          {
             this._errMsg = "Invalid assembly";
             return false;
          }
          return GetReferenceAssembly(asm);
    }

只需获取相同的字节,保存到临时文件,如果需要文件版本则获取文件版本。汇编版本可能是相同的,更容易获得(参见Jon的回复)。