-
Notifications
You must be signed in to change notification settings - Fork 1
/
trashbox_windows.go
98 lines (86 loc) · 2.61 KB
/
trashbox_windows.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//go:build windows
// +build windows
/*
Copyright © 2024 Kei-K23 <[email protected]>
*/
package trashbox
import (
"fmt"
"path/filepath"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
const (
FO_DELETE = 3 // File operation: delete
FOF_ALLOWUNDO = 0x40 // Allow to move to Recycle Bin
FOF_NOCONFIRMATION = 0x10 // No confirmation dialog
)
// SHFILEOPSTRUCT represents the structure used in SHFileOperationW.
type SHFILEOPSTRUCT struct {
WFunc uint32
PFrom *uint16
PTo *uint16
FFlags uint16
AnyOps bool
HNameMap uintptr
LpszProgressTitle *uint16
}
var (
shell32 = syscall.NewLazyDLL("shell32.dll")
procSHFileOperationW = shell32.NewProc("SHFileOperationW")
)
func shFileOperation(op *SHFILEOPSTRUCT) error {
ret, _, _ := procSHFileOperationW.Call(uintptr(unsafe.Pointer(op)))
if ret != 0 {
return fmt.Errorf("failed to move file to Recycle Bin, error code: %d", ret)
}
return nil
}
// MoveToTrash moves the specified file or directory to the Windows Recycle Bin.
//
// This function takes the path of a file or directory as an argument,
// converts it to an absolute path, and then moves it to the Windows
// Recycle Bin using the Shell API. If the provided path does not
// exist or cannot be accessed, an error will be returned.
//
// The function uses the SHFileOperationW function from the Windows
// Shell API to perform the move operation. It sets the appropriate
// flags to allow undo and suppress confirmation dialogs. If the
// operation is successful, the file or directory will no longer exist
// at the original path and will be relocated to the Recycle Bin for
// potential recovery.
//
// Parameters:
// - path: The path of the file or directory to be moved to the
// Recycle Bin.
//
// Returns:
// - error: Returns nil on success. If an error occurs during the
// process (e.g., if the file does not exist or the move fails),
// an error will be returned explaining the reason for failure,
// including any relevant error codes from the Windows API.
//
// Example:
//
// err := MoveToTrash("C:\\path\\to\\your\\file.txt")
// if err != nil {
// log.Fatalf("Failed to move to Recycle Bin: %v", err)
// }
func MoveToTrash(path string) error {
// Get the absolute file path of delete file
absPath, err := filepath.Abs(path)
if err != nil {
return err
}
wPathPtr, err := windows.UTF16PtrFromString(absPath + "\x00")
if err != nil {
return err
}
op := &SHFILEOPSTRUCT{
WFunc: FO_DELETE,
PFrom: wPathPtr,
FFlags: FOF_ALLOWUNDO | FOF_NOCONFIRMATION,
}
return shFileOperation(op)
}