Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to make application continue running even after application file is deleted

Tags:

c#

Is it possible to make it so that even after the application file is removed, the application once executed, will still continue running until the end?

I have a portable Console Application that runs on a removable drive and would like it to continue running even if the drive is accidentally removed, is that possible?

I saw http://www.codeproject.com/Articles/13897/Load-an-EXE-File-and-Run-It-from-Memory but it does not seem to work.

like image 321
pleasega Avatar asked Jun 06 '16 07:06

pleasega


2 Answers

If your console application has some referenced assemblies then they might not be loaded until they are used.

You have to load all related assemblies in your main method or somewhere in the bootstrapper/startup:

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))));
like image 73
Bassam Alugili Avatar answered Sep 30 '22 01:09

Bassam Alugili


The problem with the approach in the article (from your perspective) is that you need to launch it from another application, and that application's binary must be present at all times, so you can't launch that one from the same location, or you haven't got rid of the problem.

One mechanism could be:

  1. User starts app
  2. App copies itself to the temp folder.
  3. App launches the temp copy using Process.Start and a /nocopy parameter
  4. App closes itself.
  5. Temp app starts up, reads the /nocopy parameter and skips the copy and launches.
like image 42
Richard Matheson Avatar answered Sep 30 '22 01:09

Richard Matheson