【问题标题】:System.BadImageFormatException when getting the AssemblyVersion获取 AssemblyVersion 时出现 System.BadImageFormatException
【发布时间】:2017-05-14 11:42:06
【问题描述】:

所以我尝试为我的应用程序实现自动更新程序,from this thread

我已将我的设置文件上传到我的服务器,当我尝试获取文件的 AssemblyVersion 时,我得到了 System.BadImageFormatException,更准确地说:

System.BadImageFormatException occurred
  HResult=0x8007000B
  Message=Det går inte att läsa in filen eller sammansättningen Setup1.msi eller ett av dess beroenden. Ett försök att läsa in ett program med ogiltigt format gjordes.
  Source=mscorlib
  StackTrace:
   at System.Reflection.AssemblyName.nGetFileInformation(String s)
   at System.Reflection.AssemblyName.GetAssemblyName(String assemblyFile)
   at WindowsFormsApp1.Form1..ctor() in C:\Users\Gustav\Documents\Visual Studio 2017\Projects\WindowsFormsApp1\WindowsFormsApp1\Form1.cs:line 50
   at WindowsFormsApp1.Program.Main() in C:\Users\Gustav\Documents\Visual Studio 2017\Projects\WindowsFormsApp1\WindowsFormsApp1\Program.cs:line 22

Inner Exception 1:
BadImageFormatException: Det går inte att läsa in filen eller sammansättningen Setup1.msi eller ett av dess beroenden. Ett försök att läsa in ett program med ogiltigt format gjordes.

我听说这是因为一个 x64 应用程序试图运行一个 x86 DLL,但事实并非如此,因为它是我试图从中获取信息的完全相同的应用程序?

    string remoteUri = "http://<URL>/downloads/";
    string fileName = "Setup1.msi", myStringWebResource = null;
    // Create a new WebClient instance.
    WebClient myWebClient = new WebClient();
    // Concatenate the domain with the Web resource filename.
    myStringWebResource = remoteUri + fileName;
        myWebClient.DownloadFile(myStringWebResource, fileName);

        if (AssemblyName.GetAssemblyName("Setup1.msi").Version > Assembly.GetExecutingAssembly().GetName().Version)
        {
            logger.Add("Update found!");
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "Setup1.msi";
            Process.Start(startInfo);
            this.Close();
        }

我的设置是 x86,应用程序也是 x86。

【问题讨论】:

  • .msi 不是 .NET 文件,为什么要用AssemblyVersion检查它?
  • 哇,我太笨了,所以不可能用 .msi 文件来做这个?
  • using FileVersionInfo 怎么样?

标签: c#


【解决方案1】:

从我的旧答案开始,似乎没有简单的方法来设置 MSI 包的文件版本。那么解决方案就是实际查询 MSI 文件属性表,这需要更多的工作并且需要外部依赖。

要使此代码正常工作(确实如此,我已经根据正确的 MSI 文件对其进行了检查),您需要来自 WiX Toolset SDK 的程序集 Microsoft.Deployment.WindowsInstaller.dllMicrosoft.Deployment.WindowsInstaller.Linq.dll。如果您安装了整个工具集,您可以在their releases 的压缩版本或安装文件夹中找到这些文件。

using(var database = new QDatabase("node-v6.10.3-x64.msi", DatabaseOpenMode.ReadOnly)) {
    var productVersion = database.Properties.AsEnumerable().FirstOrDefault(p => p.Property == "ProductVersion");

    if(productVersion != null)
        Console.WriteLine($"Product version is {productVersion.Value}");
}

【讨论】:

  • 谢谢,虽然当我在我的 MSI 文件上执行此操作时每个字段都是空白的,
  • 是的,在二进制文件上获取真正的 FileVersion 属性似乎真的很难,所以我用另一种方法更新了我的答案,该方法从 msi 清单中读取属性。
猜你喜欢
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
  • 2016-07-12
  • 2011-09-03
相关资源
最近更新 更多