是否有可能使其即使在删除应用程序文件后,应用程序一旦执行,仍将继续运行直到结束?
我有一个便携式控制台应用程序,它在可移动驱动器上运行,并希望它能够继续运行,即使驱动器被意外删除,是否可能?
我看到了http://www.codeproject.com/Articles/13897/Load-an-EXE-File-and-Run-It-from-Memory,但似乎无效。
答案 0 :(得分:2)
如果您的控制台应用程序有一些引用的程序集,那么在使用它们之前它们可能不会被加载。
您必须在main方法或引导程序/启动中的某个位置加载所有相关程序集:
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
var loadedPaths = loadedAssemblies.Select(a => a.Location).ToArray();
var referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
var toLoad = referencedPaths.Where(r => !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList();
toLoad.ForEach(path => loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path))));
答案 1 :(得分:1)
文章中的方法问题(从您的角度来看)是您需要从其他应用程序启动它,并且该应用程序的二进制文件必须始终存在,因此您无法启动那个来自同一个地方,或者你还没有摆脱这个问题。
一种机制可能是:
答案 2 :(得分:0)
ElmoDev001的评论让我达到了我想要的结果。
有错误,但这是一般的想法:
Program.cs(主要课程)
class Program {
static void Main(string[] args)
{
String Temp = System.IO.Path.GetTempPath();
String tmpDir = Temp + @"tmp\";
String fileName = String.Concat(Process.GetCurrentProcess().ProcessName, ".exe");
String filePath = Path.Combine(Extension.AssemblyDirectory, fileName);
String tempFilePath = Path.Combine(tmpDir, fileName);
if (!Directory.Exists(tmpDir)) { Directory.CreateDirectory(tmpDir); }
if (!(string.Equals(filePath, tempFilePath))) // if the application is not running at temp folder
{
if (!(File.Exists(tempFilePath))) // if the application does not exist at temp folder
{
ext.initFile();
}
else if (File.Exists(tempFilePath)) // if the application already exists at temp folder
{
File.Delete(tempFilePath);
ext.initFile();
}
}
else if (string.Equals(filePath, tempFilePath)) // if the application is running at temp folder
{
//main code
}
}
}
<强> Extension.cs 强>
class Extension
{
String Temp = System.IO.Path.GetTempPath();
String tmpDir = Temp + @"tmp\";
String fileName = String.Concat(Process.GetCurrentProcess().ProcessName, ".exe");
String filePath = Path.Combine(Extension.AssemblyDirectory, fileName);
String tempFilePath = Path.Combine(tmpDir, fileName);
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
public static void initFile()
{
File.Copy(filePath, tempFilePath);
Process.Start(tempFilePath);
System.Environment.Exit(0);
}
}