Click here to Skip to main content
15,884,933 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
 public void button1_Click(object sender, EventArgs e)
        {
            try
            {

                //Define a Backup object variable.
                Backup sqlBackup = new Backup();

                //Specify the type of backup, the description, the name, and the database to be backed up.
                sqlBackup.Action = BackupActionType.Database;
                sqlBackup.BackupSetDescription = "BackUp of:" + "Garment.mdf" + "on" + DateTime.Now.ToShortDateString();
                sqlBackup.BackupSetName = "FullBackUp";
                sqlBackup.Database = "Garment.mdf";

                //Declare a BackupDeviceItem
                BackupDeviceItem deviceItem = new BackupDeviceItem("D:\\SQLBackup" + "Garment.bak", DeviceType.File);
                //Define Server connection
                ServerConnection connection = new ServerConnection(".\\SQLEXPRESS");
                //To Avoid TimeOut Exception
                Server sqlServer = new Server(connection);
                sqlServer.ConnectionContext.StatementTimeout = 60 * 60;
                Database db = sqlServer.Databases["Garment.mdf"];

                sqlBackup.Initialize = true;
                sqlBackup.Checksum = true;
                sqlBackup.ContinueAfterError = true;

                //Add the device to the Backup object.
                sqlBackup.Devices.Add(deviceItem);
                //Set the Incremental property to False to specify that this is a full database backup.
                sqlBackup.Incremental = false;

                sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
                //Specify that the log must be truncated after the backup is complete.
                sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

                sqlBackup.FormatMedia = false;
                //Run SqlBackup to perform the full database backup on the instance of SQL Server.
                sqlBackup.SqlBackup(sqlServer);
                //Remove the backup device from the Backup object.
                sqlBackup.Devices.Remove(deviceItem);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
Posted

1 solution

There are loads of possible reasons: See here: Backing up an SQL Database in C#[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900