Programmatically deleting database backup file using C#
You can download the Source Code from this link Download Source Code
Introduction
In this article we will see how to programmatically deleting database backup file using C#. We will be do backup of database file daily or weekly by scheduling to some folder in our server. After few month or years there will be lot of database backup file will be 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.
This program aim 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 this,
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 month. So for 2 month 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 month.
4) Delete all 6 months before “.bak” file.
Building the Sample
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 is few links which explain you on how to create a windows schedule Task and run your program periodically.
http://windows.microsoft.com/en-in/windows/schedule-task#1TC=windows-7
http://www.sevenforums.com/tutorials/12444-task-scheduler-create-new-task.html
Prerequisites
Visual Studio 2015 - You can download it from here.
Description
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 Select Windows Forms Application. Enter your Project Name and Click OK.
https://code.msdn.microsoft.com/site/view/file/146156/1/0.PNG
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.
private void Form1_Load(object sender, EventArgs e)
{
//Call the Delete file method to check and delete all the .bak file from the given folder
deleteFiles();
}
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.
////folder path read from text file
public String ReadFilePath()
{
string path = Application.StartupPath + @"\filePath.txt";
String readFilePath = "";
if (!File.Exists(path))
{
using (StreamWriter tw = File.CreateText(path))
{ tw.WriteLine(@"D:\DB_Backup\");
tw.Close();
readFilePath = @"D:\DB_Backup\";
}
}
else
{
TextReader tr = new StreamReader(path);
readFilePath = tr.ReadLine();
tr.Close();
}
return readFilePath;
}
In this method we will check for 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.
https://code.msdn.microsoft.com/site/view/file/146157/1/1.PNG
From this given path we will read all the “.bak” file and apply all the rules in our program check the file lastWriteTime with current month and check for the conditions and delete the files. In each condition we have commented of its use.
//Call the Delete file method to check and delete all the .bak file from the given folder
private void deleteFiles()
{
try
{
string srcDir = ReadFilePath();
string[] files = Directory.GetFiles(srcDir, "*.bak");
//string[] files = Directory.GetFiles(srcDir);
Boolean monthlyFileDelete = false;
Boolean isFileDeleted = false;
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
if (fi.LastWriteTime.Month < DateTime.Now.Month)
{
// to delete all file expect one file per week(Every week monday file not to delete)
if ((fi.LastWriteTime.Month == DateTime.Now.AddMonths(-1).Month) || (fi.LastWriteTime.Month == DateTime.Now.AddMonths(-2).Month))
{
// to delete all file expect one file per week(Every week monday file not to delete)
if ((int)fi.LastWriteTime.DayOfWeek != 1)
{
fi.Delete();
isFileDeleted = true;
}
}
else if ((fi.LastWriteTime.Month <= DateTime.Now.AddMonths(-3).Month) || (fi.LastWriteTime.Month <= DateTime.Now.AddMonths(-6).Month))
{
// to delete all file expect one file per Month
if (fi.LastWriteTime.Month == DateTime.Now.AddMonths(-3).Month)
{
//''Check for current week Monday and dont delete that file
if ((int)fi.LastWriteTime.DayOfWeek == 1 && fi.LastWriteTime.Day <= 7)
{
}
else
{
fi.Delete();
isFileDeleted = true;
}
}
else if (fi.LastWriteTime.Month == DateTime.Now.AddMonths(-4).Month)
{
if ((int)fi.LastWriteTime.DayOfWeek == 1 && fi.LastWriteTime.Day <= 7)
{
}
else
{
fi.Delete();
isFileDeleted = true;
}
}
else if (fi.LastWriteTime.Month == DateTime.Now.AddMonths(-5).Month)
{
if ((int)fi.LastWriteTime.DayOfWeek == 1 && fi.LastWriteTime.Day <= 7)
{
}
else
{
fi.Delete();
isFileDeleted = true;
}
}
else if (fi.LastWriteTime.Month == DateTime.Now.AddMonths(-6).Month)
{
if ((int)fi.LastWriteTime.DayOfWeek == 1 && fi.LastWriteTime.Day <= 7)
{
}
else
{
fi.Delete();
isFileDeleted = true;
}
}
}
else
{
// to delete all file which is beofre 6 month created
fi.Delete();
isFileDeleted = true;
}
}
}
string message = "";
if (isFileDeleted == true)
{
message = "File Delete Confirmed - Database .bak File Deleted on " + DateTime.Now.ToString();
}
else
{
message = "There is No .bak File to be delete on " + DateTime.Now.ToString();
}
WritetoLog(message);
this.Close();
}
catch (Exception ex)
{
string message = "Error : " + ex.Message.ToString() + " on - " + DateTime.Now.ToString();
WritetoLog(message);
this.Close();
}
}
After deleting the file we will be creating a TextLog file and write the status like below.
https://code.msdn.microsoft.com/site/view/file/146158/1/2.PNG
You can download the Source Code from this link Download Source Code