Code to restore SQL Server databases in VB.NET

I am unable to restore a SQL Server database using Visual Basic.Net (VB.Net) code. Could you please provide a code for restoring databases in VB.Net?
It's hard to tell exactly what the problem is without seeing your code. Executing RESTORE from VB.Net is not much different than executing from SQL Server. You need to construct a SQL Server statement and execute it with ADO.NET. Here is a sample for restoring the Northwind database:

Dim sql As String = "RESTORE DATABASE [Northwind] " & _
"FROM DISK = N'C:SQL Server DatabasesNorthwind.bak' " & _
"WITH FILE = 1," & _
"Move N'Northwind' TO N'C:SQLNorthwind.mdf',"

To continue reading for free, register below or login

Requires Membership to View

To gain access to this and all member only content, please provide the following information:

By submitting your registration information to SearchSQLServer.com you agree to receive email communications from the TechTarget network of sites, and/or third party content providers that have relationships with TechTarget, based on your topic interests and activity, including updates on new content, event notifications, new site launches and market research surveys. Please verify all information and selections above. You may unsubscribe at any time from one or more of the services you have selected by editing your profile, unsubscribing via email or by contacting us here

  • Your use of SearchSQLServer.com is governed by our Terms of Use
  • We designed our Privacy Policy to provide you with important disclosures about how we collect and use your registration and other information. We encourage you to read the Privacy Policy, and to use it to help make informed decisions.
  • If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States.

& _
"Move N'Northwind_log' TO N'C:SQLNorthwind_1.ldf'," & _
"NOUNLOAD, STATS = 10"

Dim cn As SqlConnection = New SqlConnection("Data Source=rrehak;Initial
Catalog=master;Integrated Security=SSPI;")
cn.Open()
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.ExecuteNonQuery()

Make sure the account you use in the connection string has sufficient privileges for the RESTORE command. If the database does not exist, the user needs CREATE DATABASE privileges. If the database already exists, the user has to be a member of the sysadmin or dbcreator server roles, or be the owner (dbo) of the database.

This was first published in February 2008