2012-01-15 136 views
1

終止應用程序,我要終止使用通過vb.net完整的文件路徑的應用程序,所以我用這個代碼片斷使用完整路徑

Public Sub forceCopy() 
     Try 
      'Dim strDatabasePath As String = My.Computer.FileSystem.CombinePath(Application.UserAppDataPath, "LIC.mdf") 
      'Dim strdbLogPath As String = My.Computer.FileSystem.CombinePath(Application.UserAppDataPath, "LIC_log.ldf") 
      Dim strDatabasePath As String = My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, "LIC.mdf") 
      Dim strdbLogPath As String = My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, "LIC_log.ldf") 
      Dim path As String = My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, "LIC.mdf") 
      Dim matchingProcesses = New List(Of Process) 

      For Each process As Process In process.GetProcesses() 
       For Each m As ProcessModule In process.Modules 
        If String.Compare(m.FileName, path, StringComparison.InvariantCultureIgnoreCase) = 0 Then 
         matchingProcesses.Add(process) 
         Exit For 
        End If 
       Next 
      Next 

      For Each p As Process In matchingProcesses 
       p.Kill() 
      Next 
      My.Computer.FileSystem.CopyFile(strDatabasePath, "c:\backup\LIC.mdf", True) 

      My.Computer.FileSystem.CopyFile(strdbLogPath, "c:\backup\LIC_log.ldf", True) 

      MessageBox.Show("Backup taken successfully") 
     Catch ex As Exception 
      MsgBox(ex.Message) 
     End Try 


    End Sub 

我得到一個異常「訪問被拒絕」。任何想法爲什麼?編輯:我得到在這一行的錯誤:For Each m As ProcessModule In process.Modules

回答

1

您需要用Try/Catch包裝If String.Compare(m.FileName, ...)塊。有幾個虛擬和特權進程的FileName屬性不能訪問。

這樣殺死SQL Server是一個非常糟糕的想法。用ServiceController類很好地問。您需要UAC elevation才能這樣做。

+0

我只需要複製這些文件..任何方式對我來說都是好的......我不想回到/恢復數據庫..只是一個簡單的副本..但由於「文件被其他進程使用」錯誤...我不能複製...任何解決方案? – user1150440 2012-01-15 21:16:31

+2

提問並回答。除非你喜歡備份損壞的文件,否則不要*殺死進程。該文件被鎖定是有原因的。 – 2012-01-15 21:24:55

0

只有提升的進程可以枚舉加載你不擁有的進程模塊。

+0

那麼有沒有一種方法可以讓我知道哪個進程正在使用.mdf文件並殺死進程? – user1150440 2012-01-15 21:13:26

+0

使用卷影副本可能會更好。這至少會具有處於一致狀態的優勢。 – Neil 2012-01-16 21:58:04

+0

什麼是卷影副本??點我一些好的鏈接......謝謝。 – user1150440 2012-01-17 13:11:55