Public voidBackup () {SqlConnection conn=NewSqlConnection ("server=.;D Atabase=master; User Id=sa; PASSWORD=1Q2W3E4R"); SqlCommand cmd=NewSqlCommand (); Cmd.commandtype=CommandType.Text; Cmd. Connection=Conn; Cmd.commandtext=@"Backup Database testbackup to disk= ' d:backupdb ' with init"; Try{Conn. Open (); Cmd. ExecuteNonQuery (); } Catch(Exception e) {//throw; } finally{Conn. Close (); Conn. Dispose (); } } Public voidRestore () {SqlConnection conn=NewSqlConnection ("server=.;D Atabase=master; User Id=sa; password=1q2w3e4r; Trusted_connection=false"); Conn. Open (); SqlCommand cmd=NewSqlCommand ("SELECT spid from sysprocesses, sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid and sysdatabases. Name= ' Testbackup '", conn); SqlDataReader Dr=cmd. ExecuteReader (); ArrayList List=NewArrayList (); while(Dr. Read ()) {list. ADD (Dr. GetInt16 (0)); } Dr. Close (); for(inti =0; I < list. Count; i++) {cmd=NewSqlCommand (string. Format ("KILL {0}", List[i]), conn); Cmd. ExecuteNonQuery (); } SqlCommand C=NewSqlCommand (); C.commandtype=CommandType.Text; C.connection=Conn; //With REPLACE very importantC.commandtext =@"Restore Database Testbackup from disk= ' d:backupdb ' with REPLACE"; Try{c.executenonquery (); } Catch(Exception e) {//throw; } finally{Conn. Close (); } }
C # Backup Restore MSSQL Database