1

I want to terminate an application using the full file path via vb.net,so i am using this code snippet

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

I get an exception "Access Is Denied" .Any idea why? EDIT: I get the error at this line : For Each m As ProcessModule In process.Modules

ItsPete
  • 2,363
  • 3
  • 27
  • 35
user1150440
  • 439
  • 2
  • 10
  • 23

2 Answers2

1

You'll need to wrap the If String.Compare(m.FileName, ...) block with Try/Catch. There are several fake and privileged processes whose FileName property you cannot access.

Killing SQL Server like this is otherwise a Really Bad Idea. Ask nicely with the ServiceController class. You will need UAC elevation to do so.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • i just need to copy this files..any way is good for me...i do not want to back/restore the DB..just a simple copy..but because of the "File is being used by another process" error...i cannot copy...any solutions for this?? – user1150440 Jan 15 '12 at 21:16
  • 2
    Asked and answered. Do *not* kill processes unless you like making backups of corrupt files. The file is locked for a reason. – Hans Passant Jan 15 '12 at 21:24
0

Only elevated processes can enumerate modules loaded by processes that you do not own.

Neil
  • 54,642
  • 8
  • 60
  • 72