18

我开发了一个用于内部电子邮件报告的库。当我从另一个项目中使用该库时(通过添加引用)。

NullReferenceException在下一行给出。

System.Reflection.Assembly.GetEntryAssembly().GetName().Name

任何想法,为什么大会是空的?

4

3 回答 3

27

这在由非托管运行时加载的 Windows 服务中尤其如此。

采用:

  Process.GetCurrentProcess().MainModule.FileName

获取非托管入口点文件。


更新

看来您正在寻找这个:

  System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
于 2011-02-25T12:23:02.870 回答
2

问题解决了各位

我在用

Assembly.GetAssembly(ex.TargetSite.DeclaringType.UnderlyingSystemType).GetName().Name 

获取 EntryAssemblyName。
在这种情况下,我已经有参数采用异常'ex',所以我通过使用它来解决它。

非常感谢伙计们,特别是@Aliostad

干杯

于 2011-02-25T16:27:45.177 回答
0

回答 OP 和 @Neeraj 的问题:有时获取程序集的根也很有用Assembly.GetExecutingAssembly().Location(例如,当 Resharper 测试运行器在使用时让您的生活变得艰难时GetEntryAssembly()

string rootDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string someFile = Path.Combine(
            rootDir ?? throw new InvalidOperationException(),
            "Foo",
            "Bar.txt");
于 2019-02-01T15:11:06.550 回答