进程无法访问文件,因为它被另一个进程使用...任何想法?

时间:2012-01-14 14:44:13

标签: sql-server vb.net

我正在使用以下代码段来复制/备份数据库

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

但是我收到错误 *“进程无法访问文件,因为它被另一个进程使用” *任何想法如何复制/备份文件?

1 个答案:

答案 0 :(得分:1)

除非先关闭SQL Server服务,否则无法复制该文件。

话虽如此,确实没有理由使用SQLDMO或上述方法来备份数据库;它可以使用简单的Transact SQL命令完成:

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

这会将数据库备份到SQL Server的默认备份目录(我相信您在安装时指定)。

备份命令提供了大量选项,this MSDN entry是学习更多内容的一个很好的起点。