We help IT Professionals succeed at work.

Restore a local mdf file using vb.net

Hi I have a app that is now using a local mdf file which works great.
I can do a backup fine to .bak file but how can I restore it?
it says the file is in use and to use the master but its not on a server its just a local server file.
Watch Question

Assuming that you're referring to a SQL Server database (.mdf can be used for other things, but you've tagged this in the SQL Server topic area), you would execute a SQL Scalar command, like this:

        Dim connSQL As SqlClient.SqlConnection
        Dim strConn As String = "Data Source=" & Server & ";Integrated Security=SSPI;Initial Catalog=Master"
        connSQL.ConnectionString = strConn
        query = "RESTORE DATABASE " & strDB & " FROM DISK='" & strBackup & "' WITH REPLACE")
        Using cmd As New SqlCommand(query, connSQL)
            intReturn = cmd.ExecuteScalar()
        End Using

Open in new window

Server is the name of your SQL Server instance; strDB is the name of the SQL database; strBackup is the full path of the backup file. This code assumes Windows authentication; using SQL Server authentication requires a different connection string. If there's a problem, intReturn will give an error code.

This is almost the same as how you could do a backup; you just change the query command. Are you doing your backup in a different way?
Vitor MontalvãoIT Engineer
Distinguished Expert 2017

Your question isn't clear. The title is referring to .mdf file and you are describing .bak file.
Can you clarify?


yes sorry for the delay its a sql local mdf file that I want to be able to back up to a .bak file and restore it if necessary.
Vitor MontalvãoIT Engineer
Distinguished Expert 2017

Backups are made in SQL Server. SQL Server engine blocks any tentative to access a database file and that's why you are getting the error.
You need to run a BACKUP command inside the SQL Server and then you'll have the .bak file necessary to restore whenever and where you pretend.
The commands I showed work within VB.NET; they're actually run by the SQL Server instance under VB's control. I'm showing live code that I use in my software.


perfect sorry for the delay been away