8

我想在用户删除任何目录上的文件时拦截,方法是将所需的 API 函数与在消息框“ Really Would you like to Delete this file?”中询问简单布尔问题的可用性挂钩,这个问题是表达我想的一个例子控制文件,删除它或防止删除。

我的操作系统是Windows 8 x64,但我想为其他 Windows 操作系统及其架构中的通用用法编写一种方法(如果这不认为更难做到的话)。

在这个 SO question 中,我读到最好的选择是挂钩NtSetFileInformation函数Intercept FIleSytemCall 进行删除,因为我看到存在一个名为 WinAPI 的函数DeleteFile以及接口ICopyHook,但我不知道它们之间的区别,但是无论如何我真的不知道如何开始这样做......

我想澄清一下,我正在寻找一个 VBNET 解决方案,我很头疼,因为这些 API-Hooking 库通过 Google 没有任何 VBNET 代码示例,并且当复杂的代码是涉及。

编辑:我找到了一个EasyHook库示例,NtSetFileInformation它似乎非常适合我的需求,但它是 C# 代码,我试图翻译它但没有成功: Hooking NtCreateFile API from ntdll.dll with EasyHook (c#)

所以,我已经用图书馆 2.6 试过这个Deviare,但什么也没做:

Public Class Form1

    Private _mgr As Deviare2.NktSpyMgr = Nothing
    Private WithEvents _hook As Deviare2.NktHook = Nothing
    Private _proc As Deviare2.INktProcess = Nothing

    Private Shadows Sub Shown() Handles MyBase.Shown

        _mgr = New Deviare2.NktSpyMgr()
        _hook = _mgr.CreateHook("ntdll.dll!NtSetFileInformation", Nothing)
        _hook.Hook()

    End Sub

    Private Sub OnFunctionCalled(ByVal proc As Deviare2.INktProcess,
                                 ByVal callInfo As Deviare2.INktHookCallInfo,
                                 ByVal rCall As Deviare.IRemoteCall) Handles _hook.OnFunctionCalled

        MsgBox("Caught function call in " & proc.Name)

    End Sub

End Class

@mazoula基本上上面的代码与这里回答的相同,在 vb.net 中挂钩另一个程序对 winapi 函数的调用,他说该代码对他有用,但我已经按原样尝试过(没有进行上面的修改)并向我扔了一个_hook.Attach(_mgr.Processes)指令中的异常。

我也试过这个库EasyHook但是当我从 Explorer.exe 或 CMD 中删除一个文件时再次没有做任何事情,代码是这个 C# 代码的翻译http://www.codeproject.com/Questions/528094/DeleteFileplushookingpluswithplusEasyHookplussucce

Imports System.Runtime.InteropServices
Imports EasyHook

Public Class Form1

    <DllImport("kernel32.dll", CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.StdCall)>
    Private Shared Function DeleteFile(filename As String) As Integer
    End Function

    <UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet:=CharSet.Unicode)>
    Private Delegate Function DeleteFileHandler(filename As String) As Integer

    Private Shared deleted As Boolean = False

    public Function DeleteFileHookInstance(filename As String) As Integer
        MsgBox("works?")
        If deleted Then
            deleted = False
            Return 1
        End If
        If MessageBox.Show((Convert.ToString("Do you really want to delete file ") & filename) + "?", "Confirm delete file", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
            deleted = True
            Return DeleteFile(filename)
        Else
            Return 1
        End If
        'Assume the call is successfull
    End Function

    Public Sub Run()

        Dim hook As EasyHook.LocalHook

        Try
            MsgBox("Creating...")
            hook = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "DeleteFileW"), New DeleteFileHandler(AddressOf DeleteFileHookInstance), Me)
            'It stops here, the main interface receives the reported status 'Creating...' seemly forever, I understand that is for the unexpected restarting of explorer.exe
            MsgBox("Completing...")
            hook.ThreadACL.SetExclusiveACL(New Integer() {0})
            RemoteHooking.WakeUpProcess()
            MsgBox("OK")
        Catch ex As Exception
            MsgBox("CreateHook failed: " + ex.Message)
            System.Diagnostics.Process.GetCurrentProcess().Kill()
        End Try
        While True
            Application.DoEvents()
        End While
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Run()
    End Sub

End Class
4

3 回答 3

2

几天前我写了这个方法来临时解决问题,但我不是 100% 确保该方法在所有场景中都能正常工作(例如,用户可以按ctrl+z恢复文件删除和我的方法逻辑使用文件的 datetime 属性来尝试选择我不是 100% 安全的最后删除的文件),这现在有效,但我想学习如何使用 API 挂钩而不是这样做。

同样显然这不适用于永久文件删除。

Imports System.IO
Imports Shell32

Public Class Test

    Private SH As New Shell
    Private RecycleBin As Folder = SH.NameSpace(ShellSpecialFolderConstants.ssfBITBUCKET)
    Private WithEvents FSW As New FileSystemWatcher

    Private Shadows Sub Load() _
    Handles MyBase.Load

        With FSW
            .Path = "C:\Test"
            .IncludeSubdirectories = True
            .Filter = "*"
            .NotifyFilter = NotifyFilters.FileName Or NotifyFilters.DirectoryName
            .EnableRaisingEvents = True
        End With

    End Sub

    Private Sub OnItemDeleted(sender As FileSystemWatcher, e As FileSystemEventArgs) _
    Handles FSW.Deleted

        Dim DeletedItems As IEnumerable(Of FolderItem) =
            RecycleBin.Items.Cast(Of FolderItem).
                             Where(Function(Item) Item.Name = e.Name).
                             OrderBy(Function(Item) Item.ModifyDate)

        Dim LastDeletedItem As Shell32.FolderItem = DeletedItems.LastOrDefault

        If LastDeletedItem IsNot Nothing Then

            If (LastDeletedItem.IsFolder AndAlso Directory.Exists(e.FullPath)) _
               OrElse (Not LastDeletedItem.IsFolder AndAlso File.Exists(e.FullPath)) Then

                Throw New Exception(String.Format("¿ Item has been restored ?: {0}", e.FullPath))
                Exit Sub

            End If

            LastDeletedItem.InvokeVerb("undelete")

        End If

    End Sub

End Class
于 2014-01-06T03:47:15.293 回答
2

如果是我,我会重新审视我的架构,看看我是否真的需要防止任何和所有文件删除。可能您只需要防止删除一些敏感目录(可能只是这些目录中的一些敏感文件)。这应该可以减少烦人的 UI。

于 2014-01-06T00:57:29.270 回答
1

你需要的是一个目录观察者。Visual Studio 中有内置功能。试试下面的代码:

Imports System.IO

Module Watcher

Const DirectoryName As String = "C:\Database\2010Admin Updated"

Private intCreated As Integer



Sub Main()

Dim Watcher As New FileSystemWatcher(DirectoryName)

Try

' Add delegates for events

AddHandler Watcher.Created, New FileSystemEventHandler(AddressOf Watcher_Created)

AddHandler Watcher.Changed, New FileSystemEventHandler(AddressOf Watcher_Changed)

AddHandler Watcher.Deleted, New FileSystemEventHandler(AddressOf Watcher_Deleted)

AddHandler Watcher.Renamed, New RenamedEventHandler(AddressOf Watcher_Renamed)

' Must do this

Watcher.EnableRaisingEvents = True

' Display instructions and wait to exit

Console.WriteLine("Make changes to the " & DirectoryName & "directory.")

Console.WriteLine("You will see the events generated.")

Console.WriteLine("Press ENTER to exit.")

Console.ReadLine()

Finally

Watcher.Dispose()

End Try

End Sub

Private Sub Watcher_Created(ByVal sender As Object, ByVal e As FileSystemEventArgs)

Dim objWriter As New System.IO.StreamWriter("C:\dbupdated.txt", True)

Console.WriteLine("Event: File {0} {1}", e.FullPath, e.ChangeType)

objWriter.WriteLine(Now() & "Event: File {0} {1}", e.FullPath, e.ChangeType)

objWriter.WriteLine()

objWriter.Close()

intCreated += 1

If intCreated Mod 2 = 0 Then

MsgBox("File Created: " & e.FullPath)

End If

End Sub

Private Sub Watcher_Changed(ByVal sender As Object, ByVal e As FileSystemEventArgs)

Dim objWriter As New System.IO.StreamWriter("C:\dbupdated.txt", True)

Console.WriteLine("Event: File {0} {1}", e.FullPath, e.ChangeType)

objWriter.WriteLine(Now() & "Event: File {0} {1}", e.FullPath, e.ChangeType)

objWriter.WriteLine()

objWriter.Close()

End Sub

Private Sub Watcher_Deleted(ByVal sender As Object, ByVal e As FileSystemEventArgs)

Dim objWriter As New System.IO.StreamWriter("C:\dbupdated.txt", True)

Console.WriteLine("Event: File {0} {1}", e.FullPath, e.ChangeType)

objWriter.WriteLine(Now() & "Event: File {0} {1}", e.FullPath, e.ChangeType)

objWriter.WriteLine()

objWriter.Close()

End Sub

Private Sub Watcher_Renamed(ByVal sender As Object, ByVal e As RenamedEventArgs)

Dim objWriter As New System.IO.StreamWriter("C:\dbupdated.txt", True)

Console.WriteLine("Event: File {0} {1} to {2}", e.OldFullPath, e.ChangeType, e.FullPath)

objWriter.WriteLine(Now() & "Event: File {0} {1} to {2}", e.OldFullPath, e.ChangeType, e.FullPath)

objWriter.WriteLine()

objWriter.Close()

End Sub



End Module

尝试运行它(作为控制台应用程序)。

于 2013-12-31T23:10:10.970 回答