2012-01-14 110 views
1

我用下面的代碼片段複製/備份數據庫進程無法訪問該文件,因爲它正在被另一個進程使用......任何想法?

Public Sub backupData() 
     Try 

      Dim s As StreamWriter 

      Dim portfolioPath As String = Environment.CurrentDirectory 
      'MsgBox(Application.UserAppDataPath) 
      If Not Directory.Exists(LIC.My.Settings.BackupDirectory) Then 

       Directory.CreateDirectory(LIC.My.Settings.BackupDirectory) 

       File.Create(LIC.My.Settings.BackupDirectory & "\LIC.Mdf").Close() 

       File.Create(LIC.My.Settings.BackupDirectory & "\Backup log.rtf").Close() 

       s = New StreamWriter(LIC.My.Settings.BackupDirectory & "\Backup log.rtf", True) 

       s.WriteLine("This backup was initially taken on - " & Date.Now) 

       s.Flush() 

       s.Close() 

       FileCopy(portfolioPath & "\LIC.mdf", LIC.My.Settings.BackupDirectory & "\LIC.Mdf") 

       s = New StreamWriter(LIC.My.Settings.BackupDirectory & "\Backup log.rtf", True) 

       MsgBox("New directory and backup file created") 

      Else 
       FileCopy(portfolioPath & "\LIC.mdf", LIC.My.Settings.BackupDirectory & "\LIC.Mdf") 

       s = New StreamWriter(LIC.My.Settings.BackupDirectory & "\Backup log.rtf", True) 

       s.WriteLine("This backup was latest updated on - " & Date.Now) 

       s.Flush() 

       s.Close() 

       MsgBox("Back up completed successfully") 

      End If 



     Catch ex As Exception 

      Dim MessageString As String = "Report this error to the system administrator: " & ControlChars.NewLine & ex.Message 

      Dim TitleString As String = "Data Backup Failed" 

      MessageBox.Show(MessageString, TitleString, MessageBoxButtons.OK, MessageBoxIcon.Error) 

     End Try 
    End Sub 

,但我得到一個錯誤*「該進程無法訪問該文件,因爲它正被另一個進程使用」 *任何想法如何能我複製/備份文件?

+0

如果查看文件,則無法訪問它。在這種情況下的原因可能是因爲它在閱讀時可能會改變。要備份數據庫,最好在sql server上運行備份sql腳本,而不是手動嘗試複製文件 – Mharlin 2012-01-14 14:46:59

+0

什麼樣的數據庫? – Jason 2012-01-14 14:47:16

+0

.mdf文件...... – 2012-01-14 14:48:59

回答

1

除非先關閉SQL Server服務,否則將無法複製該文件。

話雖如此,真的沒有理由使用SQLDMO或上述方法來備份數據庫;它可以用一個簡單的處理SQL命令來完成:

BACKUP DATABASE MyDatabase TO DISK = 'MyDatabase.bak' WITH FORMAT 

這將備份將數據庫SQL Server的默認備份目錄(我相信你在安裝時指定)。

備份命令有大量的選項可用,this MSDN entry是瞭解更多信息的非常好的起點。