Listing all available namespaces in AppDomain

I need to "scan" the active AppDomain for all loaded assemblies at runtime and get a list of unique namespaces available in these assemblies, does .NET support this?

The code must be executed during runtime for the code to be dynamic.

I just started writing code in C #, so I'm a little unsure where to start, so any help would be appreciated.

+5
source share
2 answers

In fact, I wrote code that allows you to do this a couple of days ago.

Use this class :

    public class NSScanner
    {
        public static List<Type> GetLoadedTypes(AppDomain appDomain)
        {
            return _getLoadedTypes(appDomain);
        }

        public static List<Type> GetPublicLoadedTypes(AppDomain appDomain)
        {
            return _getLoadedTypes(appDomain, true);
        }

        public static List<string> GetUniqueNamespaces(IEnumerable<Type> types)
        {
            var uniqueNamespaces = new ConcurrentBag<string>();

            Parallel.ForEach(types, type =>
            {
                if (!uniqueNamespaces.Contains(type.Namespace) && !string.IsNullOrEmpty(type.Namespace))
                    uniqueNamespaces.Add(type.Namespace);
            });

            var sortedList = uniqueNamespaces.OrderBy(o => o).ToList();

            return sortedList;
        }


        private static List<Type> _getLoadedTypes(AppDomain appDomain, bool onlyPublicTypes = false)
        {
            var loadedAssemblies = appDomain.GetAssemblies();

            var loadedTypes = new List<Type>();

            Parallel.ForEach(loadedAssemblies, asm =>
            {
                Type[] asmTypes;
                if (onlyPublicTypes)
                    asmTypes = asm.GetExportedTypes();
                else
                    asmTypes = asm.GetTypes();

                loadedTypes.AddRange(asmTypes);
            });

            return loadedTypes;
        }
    }

Using

var publicLoadedTypes = NSScanner.GetPublicLoadedTypes(AppDomain.CurrentDomain);
var namespaces = NSScanner.GetUniqueNamespaces(publicLoadedTypes);

Enjoy it!

+2
source

AppDomain (AppDomain.CurrentDomain ) GetAssemblies. types , , namespace, .

, LINQ, :

var namespaces = AppDomain.CurrentDomain
                     .GetAssemblies()
                     .SelectMany(a => a.GetTypes())
                     .Select(t => t.Namespace)
                     .Distinct()
                     // optionally .OrderBy(ns => ns) here to get sorted results
                     .ToList();
+4

All Articles