WinForm The program, back up the database + and compress + and delete the previous backup

Source: Internet
Author: User
Tags rar sorts

Note: In order to periodically back up the database on the server and compress to the specified directory, easy to download to local and write a program. With the task schedule of Windows, you can achieve the purpose of backing up the database regularly.

The program needs to reference SQLDMO.DLL, such as SQL Server installed on your computer, which can be found in C:\Program Files\Microsoft SQL Server\80\tools\binn\

String ServerName = system.configuration.configurationsettings.appsettings["ServerName"];//database server name
         string UserName = system.configuration.configurationsettings.appsettings[" UserName "];//database user name
        string Password = system.configuration.configurationsettings.appsettings["Password"];//password
         string strdbname = system.configuration.configurationsettings.appsettings["strDbName"];//database name
        string Filepathbak = system.configuration.configurationsettings.appsettings["Filepathbak"];//File Save path (. bak) after backup, not including file name
         string filepathrar = system.configuration.configurationsettings.appsettings[" Filepathrar "];//compressed file save path, this does not include the compressed filename

        public Form1 ()
        {
            InitializeComponent ();

BOOL backup = backupdb (ServerName, UserName, Password, strDbName, Filepathbak);
if (Backup)
{
RAR (Filepathbak, Filepathrar);
Del ();
}
System.Environment.Exit (0);//This is the most thorough exit method, no matter what thread is forced to quit, the program ends very clean.
}


<summary>
Backing Up the database
</summary>
<param name= "ServerName" > Server name </param>
<param name= "UserName" > Login account </param>
<param name= "Password" > Password </param>
<param name= "strDbName" > Database name to be backed up </param>
<param name= "Filepathbak" > File save path after backup </param>
<returns></returns>
public bool BackupDB (string ServerName, String UserName, String Password, String strDbName, String filepathbak)
{
SQLDMO. SQL Server SVR = new SQLDMO. Sqlserverclass ();
SQLDMO. Backup bak = new SQLDMO. Backupclass ();
Try
{
Svr. LoginSecure = false;
Svr. Connect (ServerName, UserName, Password);
Bak. Action = 0; SQLDMO. Sqldmo_backup_type. Sqldmobackup_database;
Bak. Initialize = true;

                Bak. Files = filepathbak + strDbName + System.DateTime.Now.ToString ("yyyyMMdd") + ". Bak";//File save path after backup + file name (f:\\databack\\ Fireweb20100810.bak)
                 Bak. Database = strDbName;
                Bak. BackupSetName = strDbName;
                Bak. backupsetdescription = "Database Backup";
                Bak. SQLBackup (SVR);

                return true;
           }
            catch (Exception err)
             {
                 Throw (New Exception ("Backup database Failed" + Err.) Message));
           }
            finally
             {
                 SVR. DisConnect ();
           }
       }

<summary>
Compresses the specified file to the specified folder
</summary>
<param name= "path" > The path of the compressed file, the file itself is indicated in the method, because the file name is determined by the current time </param>
<param name= "Rarpath" > Save path after compression </param>
<returns></returns>
public bool RAR (string path, String rarpath)
{
BOOL flag = FALSE;
System.Diagnostics.Process Pc1 = new System.Diagnostics.Process ();
Pc1.StartInfo.FileName = "Winrar.exe";
Pc1.StartInfo.CreateNoWindow = false;
String fileName = strDbName + System.DateTime.Now.ToString ("yyyyMMdd") + ". Bak";
String rarfilename = strDbName + System.DateTime.Now.ToString ("yyyyMMdd") + ". rar";
Path + = filename;//file paths before decompression + filename
Rarpath + = rarfilename;//extracted path + file name
Pc1.StartInfo.Arguments = "A-ep" + Rarpath + "+" + PATH;//-EP: Exclude path from name, i.e. no layers directory when compressing
Pc1.start ();
if (pc1.hasexited)
{
int iexitcode = Pc1.exitcode;
if (Iexitcode = = 0)
{
Flag = true;
}
Else
{
Flag = false;
}
Pc1.kill ();
Pc1.close ();
Pc1.dispose ();
}
return flag;
}

<summary>
Due to backup once a day, so the redundant backup files and compressed files are deleted, only the latest 5
</summary>
public void Del ()
{
Delete bak file
int count1 = 0;
ArrayList al1 = new ArrayList ();
DirectoryInfo Dipathbak = new DirectoryInfo (Filepathbak);
foreach (FileInfo fi in Dipathbak.getfiles ())
{
if (FI. Name.length > 12)//The file name length of bak for each backup must be greater than (20100808.bak)
{
if (FI. Name.substring (0, Fi. Name.length-fi. EXTENSION.LENGTH-8). Equals (strDbName) && fi. Extension.equals (". bak"))
{
count1++;
Al1. Add (FI. Name);
if (Count1 > 5)
{
string filename = al1[0]. ToString ();//delete the first (because the GetFiles () method sorts the files in ascending order by name, that is, the oldest one is deleted)
File.delete (dipathbak + filename);
Al1. RemoveAt (0);
count1--;
}
}
}
}


Delete rar file
int count = 0;
ArrayList al = new ArrayList ();
DirectoryInfo Dipathrar = new DirectoryInfo (Filepathrar);
foreach (FileInfo fi in Dipathrar.getfiles ())
{
if (FI. Name.length > 12)//The file name length of bak for each backup must be greater than (20100808.bak)
{
if (FI. Name.substring (0, Fi. Name.length-fi. EXTENSION.LENGTH-8). Equals (strDbName) && fi. Extension.equals (". rar"))
{
count++;
Al. Add (FI. Name);
if (Count > 5)
{
string filename = al[0]. ToString ();//delete the first (because the GetFiles () method sorts the files in ascending order by name, that is, the oldest one is deleted)
File.delete (dipathrar + filename);
Al. RemoveAt (0);
count--;
}

}
}
}
}

WinForm The program, back up the database + and compress + and delete the previous backup

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.