Skip to content

Commit 7369577

Browse files
committed
[Windows] Fix FileManager.removeItem
- Get the fsr of the passed in path before using it - Add the correct path to the directory stack
1 parent 5828ea9 commit 7369577

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

Foundation/FileManager+Win32.swift

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -405,30 +405,37 @@ extension FileManager {
405405
guard alreadyConfirmed || shouldRemoveItemAtPath(path, isURL: isURL) else {
406406
return
407407
}
408-
let faAttributes = try windowsFileAttributes(atPath: path)
408+
let url = URL(fileURLWithPath: path)
409+
var fsrBuf: UnsafeMutableBufferPointer<WCHAR> = UnsafeMutableBufferPointer.allocate(capacity: path.length * 2)
410+
defer { fsrBuf.deallocate() }
411+
_CFURLGetWideFileSystemRepresentation(url._cfObject, false, fsrBuf.baseAddress, path.length * 2)
412+
let length = url.firstIndex(where: {$0 == 0}) ?? (path.length * 2)
413+
let fsrPath = String(utf16CodeUnits: fsrBuf.baseAddress!, count: length)
414+
415+
let faAttributes = try windowsFileAttributes(atPath: fsrPath)
409416
if faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) == 0 {
410-
if !path.withCString(encodedAs: UTF16.self, DeleteFileW) {
417+
if !fsrPath.withCString(encodedAs: UTF16.self, DeleteFileW) {
411418
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
412419
}
413420
return
414421
}
415-
var dirStack = [path]
422+
var dirStack = [fsrPath]
416423
var itemPath = ""
417424
while let currentDir = dirStack.popLast() {
418425
do {
419426
itemPath = currentDir
420427
guard alreadyConfirmed || shouldRemoveItemAtPath(itemPath, isURL: isURL) else {
421428
continue
422429
}
423-
guard !path.withCString(encodedAs: UTF16.self, RemoveDirectoryW) else {
430+
guard !itemPath.withCString(encodedAs: UTF16.self, RemoveDirectoryW) else {
424431
continue
425432
}
426433
guard GetLastError() == ERROR_DIR_NOT_EMPTY else {
427434
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
428435
}
429-
dirStack.append(path)
436+
dirStack.append(itemPath)
430437
var ffd: WIN32_FIND_DATAW = WIN32_FIND_DATAW()
431-
let h: HANDLE = (path + "\\*").withCString(encodedAs: UTF16.self, {
438+
let h: HANDLE = (itemPath + "\\*").withCString(encodedAs: UTF16.self, {
432439
FindFirstFileW($0, &ffd)
433440
})
434441
guard h != INVALID_HANDLE_VALUE else {

0 commit comments

Comments
 (0)