由于某些原因,我必须将dll放在主可执行文件所在的同一文件夹中。我使用此处描述的方法https://stackoverflow.com/a/2864714/5492345。我的代码如下所示:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
namespace testnetwork
{
class Program
{
[DllImport("SomeLibrary.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, SetLastError = true)]
public static extern int SomeMethod([MarshalAs(UnmanagedType.AnsiBStr)] string someInput);
static void Main(string[] args)
{
string CurrentPath = Uri.UnescapeDataString(new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath);
var paths = new List<string>
{
CurrentPath + "/Folder1",
//CurrentPath + "/Folder2",
};
AddEnvironmentPaths(paths);
SomeMethod("myinput");
}
static void AddEnvironmentPaths(IEnumerable<string> paths)
{
var path = new[] { Environment.GetEnvironmentVariable("PATH") ?? string.Empty };
string newPath = string.Join(Path.PathSeparator.ToString(), path.Concat(paths));
Environment.SetEnvironmentVariable("PATH", newPath);
}
}
}
在我连接互联网之前,一切正常。当没有网络连接时,我收到错误
类型&#39; System.DllNotFoundException&#39;未处理的异常发生在testnetwork.exe中 其他信息:无法加载DLL&#39; SomeLibrary.dll&#39;:指定的网络名称不再可用。 (HRESULT异常:0x80070040)
似乎DllImport在PC与网络断开连接时的工作方式不同? 在我的%PATH%变量中,没有任何UNC路径。