Creating a Program that Can Self-destruct with .NET

Introduction

Have you ever wondered how you can delete a running program? Today, I will show you how to create a program and, whilst the program is running, delete its executable file. This is quite handy when you are creating an Uninstaller application or must reload your application after it was patched.

Practical

The object of this program is to demonstrate two different ways in which you can create a self-destruction application. Open Visual Studio and create either a C# or a Visual Basic.NET Windows Forms application. Design it as shown in Figure 1.

Design
Figure 1: Design

Add the necessary Namespaces so that you will be able to do file manipulation.

C#

using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

VB.NET

Imports System.IO

Create a Sub procedure aptly named SelfDestruct.

C#

   private void SelfDestruct()


      Process procDestruct = new Process();
      string strName = "destruct.bat";
      string strPath = Path.Combine(Directory
         .GetCurrentDirectory(), strName);
      string strExe = new FileInfo(Application.ExecutablePath)
         .Name;

      StreamWriter swDestruct = new StreamWriter(strPath);

      swDestruct.WriteLine("attrib \"" + strExe + "\"" +
         " -a -s -r -h");
      swDestruct.WriteLine(":Repeat");
      swDestruct.WriteLine("del " + "\"" + strExe + "\"");
      swDestruct.WriteLine("if exist \"" + strExe + "\"" +
         " goto Repeat");
      swDestruct.WriteLine("del \"" + strName + "\"");
      swDestruct.Close();

      procDestruct.StartInfo.FileName = "destruct.bat";

      procDestruct.StartInfo.CreateNoWindow = true;
      procDestruct.StartInfo.UseShellExecute = false;

      try
      {

         procDestruct.Start();

      }
      catch (Exception)
      {

         Close();

      }
   }

VB.NET

   Private Sub SelfDestruct()

      Dim procDestruct As Process = New Process()

      Dim strName As String = "destruct.bat"

      Dim strPath As String = Path.Combine _
         (Directory.GetCurrentDirectory(), strName)
      Dim strExe As String = New _
         FileInfo(Application.ExecutablePath).Name
      Dim swDestruct As StreamWriter = New StreamWriter(strPath)

      swDestruct.WriteLine("attrib """ & strExe & """" & _
         " -a -s -r -h")
      swDestruct.WriteLine(":Repeat")
      swDestruct.WriteLine("del " & """" & strExe & """")
      swDestruct.WriteLine("if exist """ & strExe & """" & _
         " goto Repeat")
      swDestruct.WriteLine("del """ & strName & """")

      swDestruct.Close()

      procDestruct.StartInfo.FileName = "destruct.bat"
      procDestruct.StartInfo.CreateNoWindow = True
      procDestruct.StartInfo.UseShellExecute = False

      Try

         procDestruct.Start()

      Catch ex As Exception

         Close()

      End Try

   End Sub

The SelfDestruct sub procedure creates a batch file named destruct.bat. A batch file is a computer file containing a list of instructions to be carried out in turn. The batch file you create will delete the running executable file.

Add the following code behind Button1.

C#

   private void button1_Click(object sender, EventArgs e)
   {

      SelfDestruct();
      Close();

   }

VB.NET

   Private Sub button1_Click(ByVal sender As Object, _
         ByVal e As EventArgs)

      SelfDestruct()

      Close()

   End Sub

The first button simply calls the SelfDestruct sub procedure and then calls the Close method to close the form.

Add the following code to your Button2.

C#

   Process.Start("cmd.exe", "/C choice /C Y /N /D Y /T 3 & Del "
         + Application.ExecutablePath);
      Application.Exit();

VB.NET

   Process.Start("cmd.exe", "/C choice /C Y /N /D Y /T 3 & Del " _
         & Application.ExecutablePath)
      Application.[Exit]()

This little piece of code spawns the Command prompt and executes the command to delete the currently running EXE file; then, it exits the application. This works, but the only problem is that it displays the Command Prompt window whilst deleting the file. To circumvent this, edit the preceding code to look like the following.

C#

   private void button2_Click(object sender, EventArgs e)
   {

      ProcessStartInfo piDestruct = new ProcessStartInfo();
      piDestruct.Arguments = "/C choice /C Y /N /D Y /T 3 & Del "
         + Application.ExecutablePath;

      piDestruct.WindowStyle = ProcessWindowStyle.Hidden;
      piDestruct.CreateNoWindow = true;

      piDestruct.FileName = "cmd.exe";

      Process.Start(piDestruct);

   }

VB.NET

   Private Sub button2_Click(ByVal sender As Object, _
         ByVal e As EventArgs)


      Dim piDestruct As ProcessStartInfo = New ProcessStartInfo()

      piDestruct.Arguments = "/C choice /C Y /N /D Y /T 3 & Del " _
         & Application.ExecutablePath
      piDestruct.WindowStyle = ProcessWindowStyle.Hidden
      piDestruct.CreateNoWindow = True
      piDestruct.FileName = "cmd.exe"

      Process.Start(piDestruct)

   End Sub

Here, you create a ProcessStartInfo object and supply its parameters as to what to execute as well as its Window Style.

Figure 2 shows the EXE still present while the program is running. Figure 3 doesn’t show the EXE after its deletion.

Running
Figure 2: Running

Deleted
Figure 3: Deleted

Conclusion

Although this is pretty useful when it comes to uninstalling and reinstalling applications, it is tricky territory. Windows is designed to not delete files that are running; circumventing this feature may open unwanted doors.

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read