You need to first make sure you have the SMO (SQL Server Management Objects) installed and available to you on your dev box. This is typically the case, if you have installed some version of SQL Server on it.
If you have the SMO library available, you can use this code snippet for your operation:
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
static void Main(string[] args)
{
// create instance of SMO Server object
Server myServer = new Server("(local)");
// create new instance of "Restore" object
Restore res = new Restore();
res.Database = "SMO"; // your database name
// define options
res.Action = RestoreActionType.Database;
res.Devices.AddDevice(@"C:\SMOTest.bak", DeviceType.File);
res.PercentCompleteNotification = 10;
res.ReplaceDatabase = true;
// define a callback method to show progress
res.PercentComplete += new PercentCompleteEventHandler(res_PercentComplete);
// execute the restore
res.SqlRestore(myServer);
}
// method to show restore progress
static void res_PercentComplete(object sender, PercentCompleteEventArgs e)
{
// do something......
}
For this to work, you need to have the following project references
and the namespace Microsoft.SqlServer.SmoExtended
is implemented in the assembly called Microsoft.SqlServer.SmoExtended.dll
which should be found in the directory C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\
if you have SMO installed.
If you don't have SMO installed, you can go fetch it from http://tinyurl.com/sql2008smo for SQL Server 2008 or http://tinyurl.com/sql2008r2smo for SQL Server 2008 R2 (there's also an older version for SQL Server 2005)