How to backup Sql Database Programmatically in C#

后端 未结 10 1874
说谎
说谎 2020-12-23 11:48

I want to write a code to backup my Sql Server 2008 Database using C# in .Net 4 FrameWork. Can anyone help in this.

10条回答
  •  既然无缘
    2020-12-23 12:17

    I have new method without SMO problems

    1. Create .bat File with backup sqlcmd command

    for backup

    SqlCmd -E -S Server_Name –Q “BACKUP DATABASE [Name_of_Database] TO DISK=’X:PathToBackupLocation[Name_of_Database].bak'”
    

    for restore

    SqlCmd -E -S Server_Name –Q “RESTORE DATABASE [Name_of_Database] FROM DISK=’X:PathToBackupFile[File_Name].bak'”
    

    2. Run the the bat file with WPF/C# code

            FileInfo file = new FileInfo("DB\\batfile.bat");
            Process process = new Process();
            process.StartInfo.FileName = file.FullName;
            process.StartInfo.Arguments = @"-X";
            process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            process.StartInfo.UseShellExecute = false; //Changed Line
            process.StartInfo.RedirectStandardOutput = true;  //Changed Line
            process.Start();
            string output = process.StandardOutput.ReadToEnd(); //Changed Line
            process.WaitForExit(); //Moved Line
    

提交回复
热议问题