pisker
pisker

Reputation: 866

Renaming a file in Swift only by changing case gives an error: No such file or directory

I want to rename a file with Swift to the same filename, just with different casing (you can try it in an ios playground):

filename = "NameWithCase"
newFilename = "Namewithcase"
var url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(filename)
let myText = "Some text to write to file"
try myText.write(to: url, atomically: true, encoding: .utf8)
url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(newFilename)
try myText.write(to: url, atomically: true, encoding: .utf8)

The above code gives an exception and I don't really know, how to avoid it:

Error Domain=NSCocoaErrorDomain Code=4 "The file “Namewithcase” doesn’t exist." UserInfo={NSFilePath=..abreviated../tmp/Namewithcase, NSUnderlyingError=0x60000047f8d0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

If I change the filename for the new file completely to e.g., Namewithcase2, everything works as expected.
What do I miss here?

Upvotes: 1

Views: 414

Answers (1)

pisker
pisker

Reputation: 866

This is an inherent problem of MacOS (namely the HFS+ file system), as the file system does not differentiate between capitalized and non-capitalized letters. The file name is NOT case sensitive, only case preserving (meaning that file names are stored with correct casing). So the only solution is to delete the file before another save operation with the same name but different casing:

try FileManager.default.removeItem(at: url)

Upvotes: 1

Related Questions