forked from saltosystems/winrt-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storagefile_test.go
88 lines (77 loc) · 2.47 KB
/
storagefile_test.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
package storage
import (
"fmt"
"log"
"os"
"path/filepath"
"testing"
"unsafe"
"github.com/go-ole/go-ole"
"github.com/saltosystems/winrt-go"
"github.com/saltosystems/winrt-go/windows/foundation"
"github.com/stretchr/testify/require"
)
func init() {
err := ole.RoInitialize(1)
if err != nil {
log.Fatal(err)
}
}
func cleanupCOM() {
ole.CoUninitialize()
}
// GetFileFromPath retrieves a StorageFile from a given file path using StorageFile.GetFileFromPathAsync api
// https://docs.microsoft.com/en-us/uwp/api/windows.storage.storagefile.getfilefrompathasync
func GetFileFromPath(fp string) (*StorageFile, error) {
// Create an AsyncOperationCompletedHandler to retrieve the StorageFile
var storageFile *StorageFile
var err error
waitChan := make(chan struct{})
onCompleteCB := func(instance *foundation.AsyncOperationCompletedHandler, asyncInfo *foundation.IAsyncOperation, asyncStatus foundation.AsyncStatus) {
defer close(waitChan)
if asyncStatus != foundation.AsyncStatusCompleted {
log.Printf("Async operation did not complete successfully: status %d", asyncStatus)
err = fmt.Errorf("async operation did not complete successfully: status %d", asyncStatus)
return
}
// Retrieve the StorageFile result from asyncInfo
var resultPtr unsafe.Pointer
resultPtr, err = asyncInfo.GetResults()
if err != nil {
log.Printf("Failed to get async operation result: %v", err)
return
}
// Cast the result to a StorageFile
storageFile = (*StorageFile)(resultPtr)
log.Printf("Retrieved StorageFile: %+v", storageFile)
}
iid := winrt.ParameterizedInstanceGUID(foundation.GUIDAsyncOperationCompletedHandler, SignatureStorageFile)
handler := foundation.NewAsyncOperationCompletedHandler(ole.NewGUID(iid), onCompleteCB)
defer handler.Release()
// this is an async operation
fileAsyncOp, err := StorageFileGetFileFromPathAsync(fp)
if err != nil {
return nil, err
}
err = fileAsyncOp.SetCompleted(handler)
if err != nil {
return nil, err
}
// Wait until async operation has stopped, and finish.
<-waitChan
return storageFile, err
}
func Test_GetStorageFileFromPath(t *testing.T) {
tempDir, err := os.MkdirTemp("", "someDir")
require.NoError(t, err)
fpath := filepath.Join(tempDir, "someFile.txt")
f, err := os.Create(fpath)
require.NoError(t, err)
require.NotNil(t, f)
sfile, err := GetFileFromPath(fpath)
require.NoError(t, err)
require.NotNil(t, sfile)
name, err := sfile.GetName()
require.NoError(t, err)
require.Equal(t, filepath.Base(fpath), name)
}