Programmatically Deleting Database Backup File Using C#

In this article you will learn how to programmatically delete database backup file using C#.

In this article we will see how to programmatically deleting database backup file using C#. We will do backup of database file daily or weekly by scheduling to some folder in our server. After few months or years lot of database backup file will get created in that folder and also the backup file will be using lots of storage space. We usually check for the old database “.bak” file and delete those file manually. To avoid the manual work to delete the “.bak” file here we will create simple program which will check for the “.bak” file from the given folder and delete those files.

The aim of this program is to delete the “.bak” file automatically from the given folder periodically. So here we will create a windows application and the program rule will be like the following,

  1. Don’t delete the current month “.bak” files.

  2. Keep weekly one “.bak” file (For example, don’t delete every week Monday “.bak” file) and delete all other days “.bak” file for past 2 months. So for 2 months keep every week Monday “.bak” file.

  3. Keep monthly one “.bak” file and delete all the other day “.bak” file for past 3 to 6 months.

  4. Delete all 6 months before “.bak” file.

For all this rule we will check the “.bak” file LastWriteTime which will give each “.bak” file creation date. In program we will create a text file with path to our database backup folder. This text file will be created in our root folder. User can give any path where the “.bak” file is located. We will also create a log file and write the status of deleted or not in text file at root folder.

To make this program automatically run daily, weekly or monthly as per your requirement you can create a Windows Schedule Task and run this program as per your requirement.

Here are few links which explain you on how to create a windows schedule Task and run your program periodically.

Prerequisites

Visual Studio 2015:
You can download it from here.

Code Part:

Create your Windows Application in Visual Studio 2015

After installing our Visual Studio 2015 click Start, then Programs and select Visual Studio 2015 - Click Visual Studio 2015.

Click New, then Project, select Windows and also select Windows Forms Application. Enter your Project Name and Click OK.

new project

Form Load

We will be calling deleteFiles() method from Form load event as we have planned to call this program exe from Windows Task Schedule and run daily, weekly or monthly as per our requirement.

  1. private void Form1_Load(object sender, EventArgs e)  
  2. {  
  3.     //Call the Delete file method to check and delete all the .bak file from the given folder  
  4.     deleteFiles();  
  5. }  
Delete Method

This is main method for our program as we perform all logic in this folder. In this method we first read the Database backup folder path from the text file from readFilePath() method.
  1. ////folder path read from text file  
  2. public String ReadFilePath()  
  3.     {  
  4.         string path = Application.StartupPath + @ "\filePath.txt";  
  5.         String readFilePath = "";  
  6.         if (!File.Exists(path))  
  7.         {  
  8.             using(StreamWriter tw = File.CreateText(path))  
  9.             {  
  10.                 tw.WriteLine(@ "D:\DB_Backup\");  
  11.                     tw.Close(); readFilePath = @ "D:\DB_Backup\";  
  12.                 }  
  13.             }  
  14.             else  
  15.             {  
  16.                 TextReader tr = new StreamReader(path);  
  17.                 readFilePath = tr.ReadLine();  
  18.                 tr.Close();  
  19.             }  
  20.             return readFilePath;  
  21.         }  
In this method we will check that the filepath text file is created or not. If not created then we will create a new text file in our root folder with default database backup path. User can also change as per there database folder path from the text file in root folder.

filepath

From this given path we will read all the “.bak” file and apply all the rules in our program. Also, we will check the file lastWriteTime with current month and check for the conditions and delete the files. In each condition we have commented its use,
  1. //Call the Delete file method to check and delete all the .bak file from the given folder  
  2. private void deleteFiles()  
  3. {  
  4.     try  
  5.     {  
  6.         string srcDir = ReadFilePath();  
  7.         string[] files = Directory.GetFiles(srcDir, "*.bak");  
  8.         //string[] files = Directory.GetFiles(srcDir);  
  9.         Boolean monthlyFileDelete = false;  
  10.         Boolean isFileDeleted = false;  
  11.         foreach(string file in files)  
  12.         {  
  13.             ////////FileInfo fi = new FileInfo(file);  
  14.             ////////if (fi.LastAccessTime < DateTime.Now.AddMonths(-3))  
  15.             //////// fi.Delete();  
  16.             FileInfo fi = new FileInfo(file);  
  17.             //string s = fi.LastAccessTime.ToString("dddd");  
  18.             if (fi.LastWriteTime.Month < DateTime.Now.Month)  
  19.             {  
  20.                 // to delete all file expect one file per week(Every week monday file not to delete)  
  21.                 if ((fi.LastWriteTime.Month == DateTime.Now.AddMonths(-1).Month) || (fi.LastWriteTime.Month == DateTime.Now.AddMonths(-2).Month))  
  22.                 {  
  23.                     // to delete all file expect one file per week(Every week monday file not to delete)  
  24.                     if ((int) fi.LastWriteTime.DayOfWeek != 1)  
  25.                     {  
  26.                         fi.Delete();  
  27.                         isFileDeleted = true;  
  28.                     }  
  29.                 }  
  30.                 else if ((fi.LastWriteTime.Month <= DateTime.Now.AddMonths(-3).Month) || (fi.LastWriteTime.Month <= DateTime.Now.AddMonths(-6).Month))  
  31.                 {  
  32.                     // to delete all file expect one file per Month  
  33.                     if (fi.LastWriteTime.Month == DateTime.Now.AddMonths(-3).Month)  
  34.                     {  
  35.                         //''Check for current week Monday and dont delete that file  
  36.                         if ((int) fi.LastWriteTime.DayOfWeek == 1 && fi.LastWriteTime.Day <= 7)  
  37.                         {}  
  38.                         else  
  39.                         {  
  40.                             fi.Delete();  
  41.                             isFileDeleted = true;  
  42.                         }  
  43.                     }  
  44.                     else if (fi.LastWriteTime.Month == DateTime.Now.AddMonths(-4).Month)  
  45.                     {  
  46.                         if ((int) fi.LastWriteTime.DayOfWeek == 1 && fi.LastWriteTime.Day <= 7)  
  47.                         {}  
  48.                         else  
  49.                         {  
  50.                             fi.Delete();  
  51.                             isFileDeleted = true;  
  52.                         }  
  53.                     }  
  54.                     else if (fi.LastWriteTime.Month == DateTime.Now.AddMonths(-5).Month)  
  55.                     {  
  56.                         if ((int) fi.LastWriteTime.DayOfWeek == 1 && fi.LastWriteTime.Day <= 7)  
  57.                         {}  
  58.                         else  
  59.                         {  
  60.                             fi.Delete();  
  61.                             isFileDeleted = true;  
  62.                         }  
  63.                     }  
  64.                     else if (fi.LastWriteTime.Month == DateTime.Now.AddMonths(-6).Month)  
  65.                     {  
  66.                         if ((int) fi.LastWriteTime.DayOfWeek == 1 && fi.LastWriteTime.Day <= 7)  
  67.                         {}  
  68.                         else  
  69.                         {  
  70.                             fi.Delete();  
  71.                             isFileDeleted = true;  
  72.                         }  
  73.                     }  
  74.                 }  
  75.                 else  
  76.                 {  
  77.                     // to delete all file which is beofre 6 month created  
  78.                     fi.Delete();  
  79.                     isFileDeleted = true;  
  80.                 }  
  81.             }  
  82.         }  
  83.         string message = "";  
  84.         if (isFileDeleted == true)  
  85.         {  
  86.             message = "File Delete Confirmed - Database .bak File Deleted on " + DateTime.Now.ToString();  
  87.         }  
  88.         else  
  89.         {  
  90.             message = "There is No .bak File to be delete on " + DateTime.Now.ToString();  
  91.         }  
  92.         WritetoLog(message);  
  93.         this.Close();  
  94.     }  
  95.     catch (Exception ex)  
  96.     {  
  97.         string message = "Error : " + ex.Message.ToString() + " on - " + DateTime.Now.ToString();  
  98.         WritetoLog(message);  
  99.         this.Close();  
  100.     }  
  101. }  
After deleting the file we will be creating a TextLog file and write the status like the following,

TextLog