I use SQL Server SMO to restore a .bak to a new database, but failed to work.
sql server is 2012 and smo object version is from the latest sdk version 11.0
file .bak was created using sql management studio 2012, same local pc, on the same coding pc as well.
The error message I get is:
Restore failed for Server 'SERVER'.
What's wrong with my code?
string dbPath = Path.Combine(@"d:\my data", dbName + "_db" + ".mdf");
string logPath = Path.Combine(@"d:\my data", dbName + "_db" + "_Log.ldf");
Restore restore = new Restore();
BackupDeviceItem deviceItem = new BackupDeviceItem("d:\template.BAK", DeviceType.File);
restore.Devices.Add(deviceItem);
restore.Database = dbName + "_db";
RelocateFile relocateDataFile = new RelocateFile("Data", dbPath);
RelocateFile relocateLogFile = new RelocateFile("Log", logPath);
restore.RelocateFiles.Add(relocateDataFile);
restore.RelocateFiles.Add(relocateLogFile);
restore.Action = RestoreActionType.Database;
restore.ReplaceDatabase = true;
restore.SqlRestore(server);
UPDATED: I surrended SMO solutions, and tried
using (SqlConnection connection = new SqlConnection("Data Source=server;user id=sa;password=xxxxx;"))
{
using (SqlCommand command = new SqlCommand(@"RESTORE DATABASE beauty01 FROM DISK = 'd:\template.bak' WITH RECOVERY, MOVE 'beauty1' TO 'D:\MyData\beauty01_Data.mdf', MOVE 'beauty1_log' TO 'd:\Mydata\beauty01_Log.ldf', REPLACE", connection))
{
connection.Open();
// Add the parameters for the SelectCommand.
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
} >> work good.
Thanks all.
dbName
, you could have data and log files with the same name - try checking to see if the file exists first, and if it does, don't try creating it again. – Irresoluted:\template.BAK
exist, and do you have access to it? Is D a network drive? If so, try moving it to a local disk. – IrresoluteRelocateFile
stuff and it should work just fine ;p (that is if you dont need it) – Mena