开发者

Null Reference Exception with System.Reflection.Assembly

开发者 https://www.devze.com 2023-02-13 15:31 出处:网络
I have developed a Library for internal email reporting. When I am using that Library from another project (By Adding Reference).

I have developed a Library for internal email reporting. When I am using that Library from another project (By Adding Reference).

It gives NullReferenceException on the following line.

System.Reflectio开发者_如何转开发n.Assembly.GetEntryAssembly().GetName().Name

Any idea, why Assembly is null?


This is expected especially in the Windows Services where they are loaded by an unmanaged runtime.

Use:

  Process.GetCurrentProcess().MainModule.FileName

To get unmanaged entry point file.


Update

It seems you are looking for this:

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


problem is solved guys,

I am using

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

to get the EntryAssemblyName.
In this case I already has parameter which is taking Exception 'ex', so I solved it by using that.

Many Thanks Guys, specially @Aliostad

Cheers


Answering both the OP's and @Neeraj 's questions: sometimes it can also be useful to get the root of your assembly with Assembly.GetExecutingAssembly().Location (e.g. when the Resharper test runner is making your life hard when using GetEntryAssembly())

string rootDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string someFile = Path.Combine(
            rootDir ?? throw new InvalidOperationException(),
            "Foo",
            "Bar.txt");
0

精彩评论

暂无评论...
验证码 换一张
取 消