.NET Core load dynamic assembly

What to do:

  1. Put all assemblies into single folder
  2. Must add the following to project.json:
    "System.Runtime.Loader":"*",
    "Microsoft.Extensions.DependencyModel":"*"
    
  3. Create this class:
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Runtime.Loader;
    using Microsoft.Extensions.DependencyModel;
    
    namespace Dyn
    {
        public class DynamicLoader : AssemblyLoadContext
        {
            private string folderPath;
    
            public DynamicLoader(string folderPath)
            {
                this.folderPath = folderPath;
            }
    
            protected override Assembly Load(AssemblyName assemblyName)
            {
                var deps = DependencyContext.Default;
                var res = deps.CompileLibraries.Where(d => d.Name.Contains(assemblyName.Name)).ToList();
                if (res.Count > 0)
                {
                    return Assembly.Load(new AssemblyName(res.First().Name));
                }
                else
                {
                    var apiApplicationFileInfo = new FileInfo($"{folderPath}{Path.DirectorySeparatorChar}{assemblyName.Name}.dll");
                    if (File.Exists(apiApplicationFileInfo.FullName))
                    {
                        var asl = new DynamicLoader(apiApplicationFileInfo.DirectoryName);
                        return asl.LoadFromAssemblyPath(apiApplicationFileInfo.FullName);
                    }
                }
                return Assembly.Load(assemblyName);
            }
        }
    }
    
  4. Example usage:
    var bin = typeof(Program).GetTypeInfo().Assembly.Location;
    //var rootPath = bin.Substring(0,bin.LastIndexOf(Path.DirectorySeparatorChar));
    var rootPath = "/home/marcin/Programming/dotnet-dll/bin/release/netcoreapp1.1/publish";
    var loader = new DynamicLoader(rootPath);
    var path = Path.Combine(rootPath, "dotnet-dll.dll");
    var dll =loader.LoadFromAssemblyPath(path);
    
    
    Console.WriteLine(path);
    
    foreach (var type in dll.GetTypes())
    {
        Console.WriteLine(type.FullName);
        if (type.FullName.Contains("MyClass"))
        {
            var mx = Activator.CreateInstance(type) as IMyInterface;
            Console.WriteLine(mx?.Run());
        }
    }
    

String manipulation

Escape culture specific signs

public string RemoveDiacritics(string text) 
{
    var normalizedString = text.Normalize(NormalizationForm.FormD);
    var stringBuilder = new StringBuilder();

    foreach (var c in normalizedString)
    {
        var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
        if (unicodeCategory != UnicodeCategory.NonSpacingMark)
        {
            stringBuilder.Append(c);
        }
    }

    return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}

Source: https://stackoverflow.com/questions/249087/how-do-i-remove-diacritics-accents-from-a-string-in-net

Visual Studio

Load NuGet or external DLL in C# Interactive Window

#r "C:\PATH\TO\YOUR\LIBRARY.DLL"

File I/O

Force recursive delete folder / directory

 public static void DeleteDirectory(string dir, bool secondAttempt = false)
{
    // If this is a second try, we are going to manually 
    // delete the files and sub-directories. 
    if (secondAttempt)
    {
        // Interrupt the current thread to allow Explorer time to release a directory handle
        Thread.Sleep(0);

        // Delete any files in the directory 
        foreach (var f in Directory.GetFiles(dir, "*.*", SearchOption.TopDirectoryOnly))
            File.Delete(f);

        // Try manually recursing and deleting sub-directories 
        foreach (var d in Directory.GetDirectories(dir))
            DeleteDirectory(d);

        // Now we try to delete the current directory
        Directory.Delete(dir, false);
        return;
    }

    try
    {
        // First attempt: use the standard MSDN approach.
        // This will throw an exception a directory is open in explorer
        Directory.Delete(dir, true);
    }
    catch (IOException)
    {
        // Try again to delete the directory manually recursing. 
        DeleteDirectory(dir, true);
    }
    catch (UnauthorizedAccessException)
    {
        // Try again to delete the directory manually recursing. 
        DeleteDirectory(dir, true);
    } 
}

Windows specific

Get information about installed applications from Windows

ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Product where Name = 'Your Application Name'");
foreach (ManagementObject mo in mos.Get())
{
   Console.WriteLine($"{mo["Name"]} {mo["Version"]}");
}

Impersonate process (start process as different user)

var proc = new Process();
var ssPwd = new System.Security.SecureString();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = discovererPath;

var pathArg = processArgs;
proc.StartInfo.Arguments = pathArg;
var domainUsername = username.Split('\\');
proc.StartInfo.Domain = domainUsername[0];
proc.StartInfo.UserName = domainUsername[1];
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.WorkingDirectory = "C:\\";
foreach (char t in password)
{
    ssPwd.AppendChar(t);
}
proc.StartInfo.Password = ssPwd;
return proc;

Find firewall rule

bool inboundRule = true; //parameter
string name = "XYZ"; //parameter

bool foundRule = false;
dynamic firewallManager = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
foreach (dynamic rule in firewallManager.Rules)
{
    var isInbound = (int)rule.Direction == 1;
    if (rule.Name.ToString() == name && isInbound == inboundRule)
    {
        var isEnabled = (bool) rule.Enabled;
        if (isEnabled)
        {
            foundRule = true;
            break;
        }
    }
}
No matches...