使用Native Dll将C#解决方案部署到单个EXE中
发布时间:2021-01-25 23:49:23 所属栏目:系统 来源:网络整理
导读:我有一个C#Visual Studio 2012解决方案,它依赖于我使用PInvoke访问的本机DLL.部署应用程序时,我必须确保此Dll位于app文件夹中. 无论如何我可以将这个Dll合并到可执行文件中吗? 也许作为一种资源? 我听说过ILMerge,但我被告知它无法应对本机代码. 任何帮
|
我有一个C#Visual Studio 2012解决方案,它依赖于我使用PInvoke访问的本机DLL.部署应用程序时,我必须确保此Dll位于app文件夹中. 无论如何我可以将这个Dll合并到可执行文件中吗? 也许作为一种资源? 我听说过ILMerge,但我被告知它无法应对本机代码. 任何帮助,将不胜感激. 解决方法您可以使用Visual Studio创建一个 Setup package项目,将所有文件部署到正确的位置或使用其他第三方打包软件(如完整的InstallShield或 alternatives)但是,您的问题在Open Hardware Monitor项目中提醒我,它们将驱动程序包含为嵌入式资源,并在用户启动应用程序时将其解压缩.它的工作原理如下:他们将WinRing0.sys和WinRing0x64.sys添加到项目中并将其Build Action设置为Embedded Resource,然后他们有一个从资源中提取驱动程序的方法: private static bool ExtractDriver(string fileName) {
string resourceName = "OpenHardwareMonitor.Hardware." +
(OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" :
"WinRing0.sys");
string[] names =
Assembly.GetExecutingAssembly().GetManifestResourceNames();
byte[] buffer = null;
for (int i = 0; i < names.Length; i++) {
if (names[i].Replace('','.') == resourceName) {
using (Stream stream = Assembly.GetExecutingAssembly().
GetManifestResourceStream(names[i]))
{
buffer = new byte[stream.Length];
stream.Read(buffer,buffer.Length);
}
}
}
if (buffer == null)
return false;
try {
using (FileStream target = new FileStream(fileName,FileMode.Create)) {
target.Write(buffer,buffer.Length);
target.Flush();
}
} catch (IOException) {
// for example there is not enough space on the disk
return false;
}
// make sure the file is actually writen to the file system
for (int i = 0; i < 20; i++) {
try {
if (File.Exists(fileName) &&
new FileInfo(fileName).Length == buffer.Length)
{
return true;
}
Thread.Sleep(100);
} catch (IOException) {
Thread.Sleep(10);
}
}
// file still has not the right size,something is wrong
return false;
}
他们将资源读入缓冲区,将该缓冲区写入磁盘并等待文件刷新到磁盘. (编辑:佛山站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |


