简体   繁体   中英

Is there an way to add reference(dll) in parent path in C#?

== compile command ==

csc -r:"../Newtonsoft.Json.dll" test.cs

== exec command ==

mono test.exe

== exec result: dependency error ==

 System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, 
 PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies.

"Newtonsoft.Json.dll" this file is located in parent path. so I added a reference about dll and compile succeeded, but when I executed the exe file, it failed to get dll reference I added.

And when I put cs file and dll file together in the same directory, it worked very well, but that's not what I wanted.

Is there a solution to add a reference from dll file which is located in parent path using command line interface?

I used csc for compiler and mono for execution.

Thanks.

References are pathless. What that means is that wherever the assembly resides, all your program knows is that it has a reference to Newtonsoft.Json, Version=xxxx, Culture=... and so on. You can do some things with the application configuration ( application.config or myprogram.exe.config ) to organize things into subfolders (using the probing setting) or specify a URL location for the file (using the codebase setting). You can set up the environment to change the search path and so on.

Or you can add some runtime code that allows you to override the default behavior and the call Assembly.LoadFrom to provide a full path to the file. You can either do it as part of your initialization or in a handler for the AppDomain.AssemblyResolve event - which is generally better method since it will only be called when the assembly is actually needed.

For example:

using System.IO;
using System.Reflection;

static class ParentPathResolver
{
    public static void Init()
    {
        AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(Resolve);
    }

    private static Assembly? Resolve(object? sender, ResolveEventArgs args)
    {
        var filename = new AssemblyName(args.Name).Name + ".dll";
        var fullname = Path.GetFullPath(Path.Combine("..", filename));
        if (File.Exists(fullname))
            return Assembly.LoadFrom(fullname);
        return null;
    }
}

Of course you can add your own code to the Resolve method to search pretty much anywhere, just as long as you don't get caught in a resolution loop. I've used the AssemblyResolve event to do fun things like loading assemblies from compressed resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM