如何触发“BadImageFormatException“?

问题描述 投票:-1回答:2

我需要建立在我的地方了“BadimageFormatException”测试一些缓存的问题。如何创建“BadImageFormatException”?

c# .net
2个回答
2
投票

正如在评论中已经规定,你可以创建并抛出此异常:

throw new BadImageFormatException();

如果你想自然导致此异常,然后按MSDN documentation

当一个动态链接库文件(.dll文件)或可执行文件(.exe文件)的文件格式不符合公共语言运行时期望的格式,则抛出该异常

这意味着你可以尝试加载一个无效的汇编文件造成的:

string tempPath = Path.GetTempFileName();

using (var file = File.OpenWrite(tempPath))
using (var sw = new StreamWriter(file))
{
    sw.WriteLine("I am not an assembly");
}

Assembly.LoadFile(tempPath);

感谢@ Xiaoy312的意见。还有一个更简单的方法来做到这一点使用Assembly.Load

Assembly.Load(new byte[] { 0 });

0
投票

如果新到这一点,那么一个方式也是加载例如Notepad.exe的非托管组件。

try
    {
        // path to notepad.exe.
        string path = Environment.ExpandEnvironmentVariables("%windir%") + @"\System32\notepad.exe";
        Assembly assembly = Assembly.LoadFile(path);
    }
    catch (System.BadImageFormatException exception)
    {
       // catch an exception.
    }

由于记事本是托管型而非.NET编译,.NET心不是很开心,抛出异常。

有趣的琐事,BadImageFormatException无关与像gifsjpegs但其异常糟糕的图像格式时净尝试加载DLLexe其心不是与CLR兼容。

此外,所有的异常是从System.Exception的。 BadImageFormatException距离System.Exception继承。

© www.soinside.com 2019 - 2024. All rights reserved.