dcsimg

Creating Another Self-destruct Program

WEBINAR:
On-Demand

Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame


Introduction

You may find the title of this article somewhat misleading. Yes, I have written about this subject before, but as I have said many a time: There are many ways to skin a cat. What I will show you today will also make use of batch files to delete the program, but with one caveat. The program must first be closed.

Now, why should a program such as this exist?

Well, say for instance you have a allowed a user to use your application for a certain period of time. A trial application. When the trial expires, so can the program. This, however, doesn't solve the issue of uninstalling the application. Not all applications get installed similarly.

Practical

Create a new C# or Visual Basic.NET Console application. After the application has loaded, add these namespaces.

C#

using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;

VB.NET

Imports System.IO
Imports System.Reflection
Imports System.Threading

The namespaces import the Reflection and threading and file classes so that we can utilize them throughout our code.

Add the next code for the Sub Main procedure:

C#

   static void Main(string[] args)
   {
      string strBatch = string.Empty;
      string strEXE = Assembly.GetExecutingAssembly()
         .CodeBase.Replace("", string.Empty).Replace("/", "\\");

      strBatch += "@ECHO OFF\n";
      strBatch += "ping 127.0.0.1 > nul\n";
      strBatch += "echo j | del /F ";
      strBatch += strEXE + "\n";
      strBatch += "echo j | del DelApp.bat";
      File.WriteAllText("DelApp.bat", strBatch);

      Process.Start("DelApp.bat");

   }

VB.NET

   Private Sub Main(ByVal args As String())

      Dim strBatch As String = String.Empty
      Dim strEXE As String = Assembly.GetExecutingAssembly() _
         .CodeBase.Replace("", String.Empty).Replace("/", "\")

      strBatch += "@ECHO OFF" & vbLf
      strBatch += "ping 127.0.0.1 > nul" & vbLf
      strBatch += "echo j | del /F "
      strBatch += strEXE & vbLf
      strBatch += "echo j | del DelApp.bat"
      File.WriteAllText("DelApp.bat", strBatch)

      Process.Start("DelApp.bat")
   End Sub

A batch file gets created. It checks to see if the application is still open. If it is not open, it executes the created batch file.

Add another way.

C#

   static void SelfDestruct()
   {
      string strBatch = "DelApp.bat";
      using (StreamWriter swBatch = File.AppendText(strBatch))
      {
         swBatch.WriteLine(":Loop");
         swBatch.WriteLine("Tasklist /if \"PID eq " +
            Process.GetCurrentProcess().Id.ToString() + "\" |
            find \":\"");
         swBatch.WriteLine("if Errorlevel 1 (");
         swBatch.WriteLine("  Timeout /T 1 /Nobreak");
         swBatch.WriteLine("  Goto Loop");
         swBatch.WriteLine(")");
         swBatch.WriteLine("Del \"" + (new FileInfo((new
            Uri(Assembly.GetExecutingAssembly().CodeBase))
            .LocalPath)).Name + "\"");
      }

      Process.Start(new ProcessStartInfo() { Arguments = "/C " +
         strBatch + " & Del " + strBatch, WindowStyle =
         ProcessWindowStyle.Hidden, CreateNoWindow = true,
         FileName = "cmd.exe" });
   }

VB.NET

   Private Sub SelfDestruct()

      Dim strBatch As String = "DelApp.bat"

      Using swBatch As StreamWriter = File.AppendText(strBatch)

         swBatch.WriteLine(":Loop")

         swBatch.WriteLine("Tasklist /if ""PID eq " & _
            Process.GetCurrentProcess().Id.ToString() & _
            """ | find "":""")
         swBatch.WriteLine("if Errorlevel 1 (")
         swBatch.WriteLine("  Timeout /T 1 /Nobreak")
         swBatch.WriteLine("  Goto Loop")
         swBatch.WriteLine(")")
         swBatch.WriteLine("Del """ & (New FileInfo((New Uri _
            (Assembly.GetExecutingAssembly().CodeBase)) _
            .LocalPath)).Name & """")

      End Using

      Process.Start(New ProcessStartInfo() With {
             .Arguments = "/C " & strBatch & " & _
                Del " & strBatch,
             .WindowStyle = ProcessWindowStyle.Hidden,
             .CreateNoWindow = True,
             .FileName = "cmd.exe"
         })

   End Sub

When you call this sub procedure, it keeps on checking the task list to see if the application is open or not. If it is no longer open, it deletes it.

Conclusion

It is not difficult creating a self-destructing program, but use this with caution. As outlined above, ensure that there are valid reasons for this. Until next time, happy coding and destructing!



About the Author

Hannes DuPreez

Hannes du Preez is a self-taught developer who started learning to program in the days of QBasic. He has written several articles over the years detailing his programming quests and adventures. .NET is his second love, just after his wife and kid. He has always been an avid supporter of .NET since the beginning and is an expert in VB and C#. He was given the Microsoft Most Valuable Professional Award for .NET (2008–2017). He has worked as a moderator and an article reviewer on online forums and currently works as a C# developer and writes articles for CodeGuru.com, Developer.com, DevX.com, and the Database journal. His first book, Visual Studio 2019 in Depth... is currently on sale on Amazon.com.

Related Articles

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date