Search code examples
swiftnsfilemanager

Swift: FileManager().fileExists(atPath: (fileURL.path)) without knowing extension


)

today I have a problem and I can't find an easy solution.

With:

FileManager().fileExists(atPath:(fileURL.path))

it's simple to find out if a file exist. Actually I have the file name but don't know the extension. How can I use FileManager() to find a file without the extension. Something like .deletingPathExtension() for FileManger().fileExists? Something like

ls filename.*

Solution

  • You could create a FileManager extension that retrieves the contents of the directory and filters for files as well as the expected filename.

    It might look something like this:

    extension FileManager {
        func urls(of filename: String, in directory: URL)  -> [URL]? {
            guard let urls = try? contentsOfDirectory(at: directory, includingPropertiesForKeys: nil, options: [])
                else { return nil }
            
            return urls.filter { url in
                !url.hasDirectoryPath && url.deletingPathExtension().lastPathComponent == filename
            }
        }
    }
    

    Finally, one would call it something like this:

    let directory = URL(string: "file:///Users/stephan/tmp")!
    if let urls = FileManager.default.urls(of: "test", in: directory) {
        for url in urls {
            print("do something with url: \(url)")
        }
    }