将本机DLL手动复制到Shadow Copy目录是否安全?

时间:2017-12-13 15:20:13

标签: asp.net sql-server pinvoke shadow-copy

我在ASP.NET应用程序中使用Microsoft.SqlServer.Types库。该库依赖于必须通过P / Invoke加载LoadLibrary()的本机DLL。

库的文档建议从Server.MapPath("~/bin")加载本机DLL,但这会导致本机DLL被锁定,从而阻止了应用程序的新部署。

因此我考虑使用Assembly.GetExecutingAssembly().Location检索主网站DLL的卷影副本位置,将本机DLL复制到该位置,然后从那里加载。

这样做是否安全?或者是否有更安全的方法应该使用?

1 个答案:

答案 0 :(得分:1)

我已经实现了这一点,似乎工作正常。部署时没有锁定问题。

示例代码如下。您可能需要根据您的环境对其进行修改,它是为OWIN中托管的Web API 2编写的。

private void LoadSqlServerTypes()
{
    var shadowCopyDirectoryPath = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;
    var nativeDllDirectory = new DirectoryInfo(HostingEnvironment.MapPath("~/bin/SqlServerTypes"));
    var nativeDllShadowCopyDirectory = Path.Combine(shadowCopyDirectoryPath, "SqlServerTypes");
    if (Directory.Exists(nativeDllShadowCopyDirectory) == false)
    {
        nativeDllDirectory.CopyTo(nativeDllShadowCopyDirectory, true);
    }

    SqlServerTypes.Utilities.LoadNativeAssemblies(shadowCopyDirectoryPath);
}

CopyTo方法是https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories

代码的修改版本
public static partial class DirectoryInfoExtensions
{
    /*
     * Source adapted from https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories
     */
     /// <summary>
     /// Copy a directory and its contents to a specified location.
     /// </summary>
     /// <param name="sourceDirectory">The directory to copy.</param>
     /// <param name="destinationDirectoryPath">The path of the new directory to create.</param>
     /// <param name="recursive">True if subdirectories must be copied; otherwise, false.</param>
    public static void CopyTo(this DirectoryInfo sourceDirectory, string destinationDirectoryPath, bool recursive)
    {
        if (Directory.Exists(destinationDirectoryPath) == false)
        {
            Directory.CreateDirectory(destinationDirectoryPath);
        }

        var files = sourceDirectory.GetFiles();
        foreach (var file in files)
        {
            string destinationFilePath = Path.Combine(destinationDirectoryPath, file.Name);
            file.CopyTo(destinationFilePath, false);
        }

        if (recursive == true)
        {
            var subdirectories = sourceDirectory.GetDirectories();
            foreach (DirectoryInfo directory in subdirectories)
            {
                string destinationSubdirectoryPath = Path.Combine(destinationDirectoryPath, directory.Name);
                CopyTo(new DirectoryInfo(directory.FullName), destinationSubdirectoryPath, recursive);
            }
        }
    }
}