是否有可能使得一旦执行应用程序后,即使删除应用程序文件,应用程序仍将继续运行直到结束?
我有一个可移动的控制台应用程序,在可移动驱动器上运行,希望即使意外移除驱动器,它也能继续运行,这是否可行?
我看到了http://www.codeproject.com/Articles/13897/Load-an-EXE-File-and-Run-It-from-Memory,但似乎无效。
是否有可能使得一旦执行应用程序后,即使删除应用程序文件,应用程序仍将继续运行直到结束?
我有一个可移动的控制台应用程序,在可移动驱动器上运行,希望即使意外移除驱动器,它也能继续运行,这是否可行?
我看到了http://www.codeproject.com/Articles/13897/Load-an-EXE-File-and-Run-It-from-Memory,但似乎无效。
如果您的控制台应用程序有一些引用的程序集,那么它们可能只有在被使用时才会被加载。
您需要在主方法或引导程序/启动程序的某个地方加载所有相关的程序集:
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))));
void Main(string[] args)
内部,只需测试是否有一个字符串在 args
中是 "/nocopy"。最好进行不区分大小写的检查。 - Richard MathesonElmoDev001的评论帮助我达成了想要的结果。
虽然有错误,但这是一般的想法:
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);
}
}