# Copy SQL database using vb



## iMan4274 (Sep 8, 2008)

I am doing a weekend database project. It is almost over, but one part is holding me back.

The application is connected to the database and i want to copy the database to another directory, but the application throws an error when copying:


```
System.IO.IOException was unhandled
  Message="The process cannot access the file 'C:\Documents and Settings\blah\Desktop\Thumb drive backup\Data\blah\again\bin\Debug\dbase.mdf' because it is being used by another process."
  Source="mscorlib"
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite)
       at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite)
       at Microsoft.VisualBasic.FileIO.FileSystem.CopyOrMoveFile(CopyOrMove operation, String sourceFileName, String destinationFileName, Boolean overwrite, UIOptionInternal showUI, UICancelOption onUserCancel)
       at Microsoft.VisualBasic.MyServices.FileSystemProxy.CopyFile(String sourceFileName, String destinationFileName)
       at badgeorder.MainForm.swBackupDatabase_LinkClicked(Object sender, LinkLabelLinkClickedEventArgs e) in C:\Documents and Settings\blah\Desktop\Thumb drive backup\Data\blah\again\MainForm.vb:line 2924
       at System.Windows.Forms.LinkLabel.OnLinkClicked(LinkLabelLinkClickedEventArgs e)
       at System.Windows.Forms.LinkLabel.OnMouseUp(MouseEventArgs e)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.Label.WndProc(Message& m)
       at System.Windows.Forms.LinkLabel.WndProc(Message& msg)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at badgeorder.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
```
Here is the code im using:


```
Private Sub swBackupDatabase_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles swBackupDatabase.LinkClicked
        '--- Configure the folder browser dialog
        With SelectFolder
            .Reset()
            .Description = "Choose where the database will be backed up"
            .ShowNewFolderButton = True
        End With

        '--- Get destination 
        SelectFolder.ShowDialog()

        Dim DestinationPath As String
        If SelectFolder.SelectedPath = "" Then Exit Sub
        DestinationPath = SelectFolder.SelectedPath

        '--- Get path of the current database
        Dim CurrentDBPath As String
        CurrentDBPath = GetDBPath()

        '--- Copy current db to the destination path
        My.Computer.FileSystem.CopyFile(CurrentDBPath, DestinationPath & "dbase.mdf")  --> Error
    End Sub
```
It is pretty clear the cause of this error is , but how can I copy the database without these errors?


----------



## Jimmy the Hand (Jul 28, 2006)

Just an idea: have you tried closing all connections to the DB beforehand?


----------



## iMan4274 (Sep 8, 2008)

I had that idea, and tried it out using the code below, but I don't think I did it the right way :

db.Close()

Any other way?


----------



## Aftab (Oct 15, 2003)

If you want to copy the MDF file in this way you need to detach from the database beforehand. ideally database backups should be done with SQL server. If you really want to copy the MDF file in code then have a look at using SMO, these are classes for working with SQL server objects. I haven't used it myself so I can't show you what to do but if you google SMO you'll find lots of info.

Hope this helps.


----------

