Zoli
Zoli

Reputation: 911

How to get runtime the VS debug Modules list for a c# app

I am trying to get the same modules list during runtime what I get during debugging in VS 2022 Modules window. However

Process.GetCurrentProcess().Modules

returns totally different than VS Debug>Modules window. Modules window contains 11 modules, and this one looks fine.
While the GetCurrentProcess().Modules returns 50(!) modules, and they are even different ones. enter image description here

How can I get programmatically the same modules list what VS > Debug > Modules window shows?

Upvotes: 0

Views: 27

Answers (2)

shingo
shingo

Reputation: 27342

When mixed-mode debugging is disabled, the modules window only contains managed modules.

Process.Modules returns both unmanaged and managed modules, you can filter out unmanaged modules with ProcessModule.FileName and PEReader.HasMetadata.

Example:

var modules = Process.GetCurrentProcess().Modules.Cast<ProcessModule>().Where(m =>
{
    using var fs = File.OpenRead(m.FileName);
    using var reader = new System.Reflection.PortableExecutable.PEReader(fs);
    return reader.HasMetadata;
});

If you want to get the same result as the modules window, you need to run this twice because the first run will load additional dlls.

Upvotes: 1

Zoli
Zoli

Reputation: 911

I think I found the reason why the missing modules, see: Getting a list of DLLs currently loaded in a process C#

"After CLR v4, the accepted answer will show only unmanaged assemblies."
Using Microsoft.Diagnostics.Runtime will show managed assemblies too. Although the numbers are still different, but now I have all.

Upvotes: 0

Related Questions