Fill Freeman Fill Freeman - 1 month ago 14
C# Question

How to use dynamically linked dll in c#

I imported the taglib-sharp dll (that had been copied to the bin/debug folder of my project) in my C# application and then used types and methods from the library in the following way:

using TagLib;

private void method()
{
TagLib.File file = TagLib.File.Create("C:\\temp\\some.mp3");
TagLib.Tag tag = file.GetTag(TagLib.TagTypes.Id3v2);
}


Now I want to link the dll dynamically. How can I implement the same functional in this case?

That, what I've tried:

using System.Reflection

private void method()
{
Assembly TagLib = Assembly.Load("taglib-sharp");

Type TagLibFile = TagLib.GetType("File");
dynamic LibFile = Activator.CreateInstance(TagLibFile);

TagLibFile file = LibFile.Create("c:\\temp\\some.mp3");
}


In this implementation, VisualStudio says that I can't use the tagLibFile variable as a type. I supposed that when I get a type from dll, I will be able to create variables of this type.

By the way, is this approach is correct?

P.S. Also, I tried to use the invoke method, but I was not sure what object I should pass as a first argument.

UPD



Based on @nawfal's awnser below, I've got the following working code:

using System.Reflection

private void method()
{
Assembly TagLib = Assembly.Load("taglib-sharp");

// get the File type
var fileType = TagLib.GetType("TagLib.File");
// get the overloaded File.Create method
var createMethod = fileType.GetMethod("Create", new[] { typeof(string) });

// get the TagTypes method that contains Id3v2 field
Type tagTypes = TagLib.GetType("TagLib.TagTypes");
// get the overloaded File.GetTag method
var getTagMethod = fileType.GetMethod("GetTag", new[] {tagTypes});
// obtain the file
dynamic file = createMethod.Invoke(null, new[] { "C:\\temp\\some.mp3" });
// obtain the Id3v2 field value
FieldInfo Id3TagField = tagTypes.GetField("Id3v2");
var Id3Tag = Id3TagField.GetValue(tagTypes);

// obtain the actual tag of the file
var tag = getTagMethod.Invoke(file, new[] { Id3Tag });
}

Answer

You should be doing something like this:

private void method()
{
    var assembly = Assembly.Load("taglib");
    var type = assembly.GetType("namespace.File"); // namespace qualified class name
    // assuming you only have one Create method, otherwise use reflection to resolve overloads
    var method = type.GetMethod("Create");

    dynamic file = method.Invoke(null, new[] { "C:\\temp\\some.mp3" }); // null for static methods
    var tag = file.GetTag(TagLib.TagTypes.Id3v2); // not sure if you can pass those params, 
                                                  // may be do reflection to get them too
}

Kindly rethink if you want it to be dynamic. If you can reference the dll then you can still get the benefits of strong typing.