Creating SQL Server backup file (.bak) with c# to any location

后端 未结 5 1736
感动是毒
感动是毒 2021-02-03 13:35

I\'m trying to write simple application in C# which will allow me to backup, zip and send over ftp my SQL Server database. One problem I have encountered is that I\'m not able t

5条回答
  •  时光取名叫无心
    2021-02-03 13:55

    Here is a procedure is use for back up in C#.Hope it helps

       public void BackupDatabase (string BackUpLocation, string BackUpFileName, string 
       DatabaseName, string ServerName )
       {
    
            DatabaseName = "[" + DatabaseName + "]";
    
            string fileUNQ = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() +"_"+ DateTime.Now.Hour.ToString()+ DateTime.Now .Minute .ToString () + "_" + DateTime .Now .Second .ToString () ;
    
            BackUpFileName = BackUpFileName + fileUNQ + ".bak";
            string SQLBackUp = @"BACKUP DATABASE " + DatabaseName + " TO DISK = N'" + BackUpLocation + @"\" + BackUpFileName + @"'";
    
            string svr = "Server=" + ServerName + ";Database=master;Integrated Security=True";
    
            SqlConnection cnBk = new SqlConnection(svr);
            SqlCommand cmdBkUp = new SqlCommand(SQLBackUp, cnBk);
    
            try
            {
                cnBk.Open();
                cmdBkUp.ExecuteNonQuery();
                Label1.Text = "Done";
                Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + @"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
            }
    
            catch (Exception ex)
            {
                Label1.Text = ex.ToString();
                Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + @"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
            }
    
            finally
            {
                if (cnBk.State == ConnectionState.Open)
                {
    
                    cnBk .Close(); 
                } 
          } 
        }
    

提交回复
热议问题