我开发了一个用于内部邮件报告的库。 当我从另一个项目中使用该库(通过添加引用)时,会在以下行上出现 NullReferenceException
。
System.Reflection.Assembly.GetEntryAssembly().GetName().Name
有什么想法,为什么Assembly是null吗?
我开发了一个用于内部邮件报告的库。 当我从另一个项目中使用该库(通过添加引用)时,会在以下行上出现 NullReferenceException
。
System.Reflection.Assembly.GetEntryAssembly().GetName().Name
有什么想法,为什么Assembly是null吗?
这在Windows服务中是很常见的情况,尤其是当它们被非托管运行时加载时。
请使用:
Process.GetCurrentProcess().MainModule.FileName
获取未托管的入口点文件。
看起来你正在寻找这个:
System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
Assembly.GetAssembly(ex.TargetSite.DeclaringType.UnderlyingSystemType).GetName().Name
获取EntryAssemblyName。
在这种情况下,我已经有一个参数'ex'来接受异常,所以我通过使用它来解决它。
非常感谢各位,特别是@Aliostad先生。
干杯
Assembly.GetExecutingAssembly().Location
获取程序集的根目录也是很有用的(例如,当Resharper测试运行器在使用GetEntryAssembly()
时让你感到困扰时)。string rootDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string someFile = Path.Combine(
rootDir ?? throw new InvalidOperationException(),
"Foo",
"Bar.txt");