How can I use a .bak database backup file (backed up via a query in SQL Server) programmatically?
I want my application to back up my database to a location (which I can already do) and I also want it to be able to load a backed up database (the .bak file).
How can I do this using C#?
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:
For this to work, you need to have the following project references
and the namespace
Microsoft.SqlServer.SmoExtendedis implemented in the assembly calledMicrosoft.SqlServer.SmoExtended.dllwhich should be found in the directoryC:\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 here for SQL Server 2008 or here for SQL Server 2008 R2 (there’s also an older version for SQL Server 2005)