Load an Assembly from Bin in ASP.NET

2019-04-05 11:24发布

I have a file name, like "Foo.dll," for a library that I know is in the bin directory. I want to create an Assembly object for it. I'm trying to instantiate this object from a class that's not a page, so I don't have the Request object to get the path. How do I get the path I need to use Assembly.Load()?

4条回答
霸刀☆藐视天下
2楼-- · 2019-04-05 11:55

Does Assembly.LoadFile(...) work?

查看更多
该账号已被封号
3楼-- · 2019-04-05 11:58

From your description it sounds like this is an web application, so unless you are on an asynchronous thread you spawned from a request, you should still have access to the HttpContext. From there you can use Server.MapPath() to the file you need.

查看更多
乱世女痞
4楼-- · 2019-04-05 12:06

A complete example as I use, if it helps. Resources is a folder under the root of the DLL Library (Assembly)

        public static string ReadAssemblyResourceFile(string resourcefilename)
        {
using (var stream = Assembly.Load("GM.B2U.DAL").GetManifestResourceStream("GM.B2U.DAL.Resources."
    + resourcefilename))            {
                    if (stream == null) throw new MyExceptionDoNotLog($"GM.B2U.DAL.Resources.{resourcefilename} not found in the Assembly GM.B2U.DAL.dll !");
                    using (var reader = new StreamReader(stream))
                    {
                        return reader.ReadToEnd();
                    }           
                }
        }

to call the function:

[TestMethod()]
public void ReadAssemblyResourceFileTest()
{
    var res = SetupEngine.ReadAssemblyResourceFile("newdb.sql");
    Assert.IsNotNull(res);
}

ps. Do not forget to to mark the "Build Action" as "Embedded Resource" (in the properties window) of each resource file.

查看更多
家丑人穷心不美
5楼-- · 2019-04-05 12:14

Assembly.Load should not require a file path, rather it requires an AssemblyName. If you know that your assembly is in the standard search path (i.e. the bin directory), you should not need to know the disk path of the assembly...you only need to know its assembly name. In the case of your assembly, assuming you don't need a specific version, culture, etc., the assembly name should just be "Foo":

Assembly fooAssembly = Assembly.Load("Foo");

If you do need to load a specific version, you would do the following:

Assembly fooAssembly = Assembly.Load("Foo, Version=1.1.2, Culture=neutral");

Generally, you want to use Assembly.Load, rather than Assembly.LoadFrom or Assembly.LoadFile. LoadFrom and LoadFile work outside of the standard fusion process, and can lead to assemblies being loaded more than once, loaded from insecure locations, etc. Assembly.Load performs a "standard" load, searching the standard assembly locations such as bin, the GAC, etc., and applies all the standard security checks.

查看更多
登录 后发表回答