2012-01-15 213 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