.Net Dependency Tree

Date: 2017-06-23
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Newtonsoft.Json.Linq;

namespace DependencyTree {
    class Program {
        public static HashSet<string> ProcessedAssemblies = new HashSet<string> ();

        public static JObject GetDependencies (List<string> messages, Assembly assembly) {
            var tree = new JObject ();
            ProcessedAssemblies.Add (assembly.FullName);

            tree.Add ("Name", new JValue (assembly.GetName ().Name));
            tree.Add ("FullName", new JValue (assembly.FullName));

            var assemblies = assembly.GetReferencedAssemblies ();
            var references = new JArray ();
            tree.Add ("references", references);
            if (assemblies.GetLength (0) > 0) {
                foreach (var refAssembly in assemblies) {
                    if (!ProcessedAssemblies.Contains (refAssembly.FullName)) {
                        var fileName = Path.GetFullPath (refAssembly.Name + ".dll");
                        //messages.Add(String.Format("Checking for assembly: {0}", fileName));
                        if (File.Exists (fileName)) {
                            try {
                                var referencedAssembly = Assembly.LoadFile (fileName);
                                references.Add (GetDependencies (messages, referencedAssembly));
                            } catch (Exception e) {
                                messages.Add (String.Format ("An exception occurred: {0}", e.Message));
                                references.Add (new JValue (refAssembly.FullName));
                            }
                        } else {
                            references.Add (new JValue (refAssembly.FullName));
                        }
                    } else {
                        references.Add (new JValue (refAssembly.FullName));
                    }
                }
            }
            return tree;
        }

        static int Main (string[] args) {
            if (args.GetLength (0) < 1) {
                Console.WriteLine ("Add a single parameter that is your path to the file you want inspected.");
                return 1;
            }

            var messages = new List<string> ();
            try {
                var assembly = Assembly.LoadFile (Path.GetFullPath (args[0]));
                var obj = GetDependencies (messages, assembly);
                File.WriteAllText ("DependencyTree.json", obj.ToString ());
            } catch (Exception e) {
                messages.Add (String.Format ("An exception occurred: {0}", e.Message));
            }
            File.WriteAllText ("DependencyTreeMessages.txt", String.Join ("\n", messages));

            return 0;
        }
    }
}
7890cookie-check.Net Dependency Tree