Restoring a DB using C#
I am trying to restore a DB from one server to the other using Microsoft.SqlServer.Management.Smo. The issue is I keep getting an error stating that it ca开发者_开发技巧nnot find the .MDF file. THe reason for that is that it is trying to find it in a the data folder for the Instance name of SQL from whence it came rather than looking in the data folder of another instance of SQL. Is there a way to to tell it which folder to search for the mdf rather than assuming it is the one tagged to the BAK file? This is so frustrating
Take a look at this article by Bappi M Ahmed. It shows a complete method for restoring a database file. Here is the method it shows:
public void RestoreDatabase(String databaseName, String filePath,
String serverName, String userName, String password,
String dataFilePath, String logFilePath)
{
Restore sqlRestore = new Restore();
BackupDeviceItem deviceItem = new BackupDeviceItem(filePath, DeviceType.File);
sqlRestore.Devices.Add(deviceItem);
sqlRestore.Database = databaseName;
ServerConnection connection = new ServerConnection(serverName, userName, password);
Server sqlServer = new Server(connection);
Database db = sqlServer.Databases[databaseName];
sqlRestore.Action = RestoreActionType.Database;
String dataFileLocation = dataFilePath + databaseName + ".mdf";
String logFileLocation = logFilePath + databaseName + "_Log.ldf";
db = sqlServer.Databases[databaseName];
RelocateFile rf = new RelocateFile(databaseName, dataFileLocation);
sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName+"_log", logFileLocation));
sqlRestore.ReplaceDatabase = true;
sqlRestore.Complete += new ServerMessageEventHandler(sqlRestore_Complete);
sqlRestore.PercentCompleteNotification = 10;
sqlRestore.PercentComplete +=
new PercentCompleteEventHandler(sqlRestore_PercentComplete);
sqlRestore.SqlRestore(sqlServer);
db = sqlServer.Databases[databaseName];
db.SetOnline();
sqlServer.Refresh();
}
Perhaps you have to add RelocateFile
objects to the RelocateFiles
ArrayList Property on the Restore
object. Have you tried this?
精彩评论