How To Get Directory Size With Swift On OS X

I am trying to get the size of a directory, as well as it's content on OS X using Swift. So far, I have only been able to get the size of the directory itself, with none of it's content. For most of my directories it generally shows a value of 6,148 bytes but it does varie.

I have tried the directorySize() function from the file below but it returned 6,148 bytes as well.

https://github.com/amosavian/ExtDownloader/blob/2f7dba2ec1edd07282725ff47080e5e7af7dabea/Utility.swift

I tried the top 2 answers from this question, but was unsure what argument it needed passed Swift to the Objective-C function. I believe it wants a pointer (I am a beginning programmer in learning).

Calculate the size of a folder

And I could not get the Swift answer from here to work for my purpose either.

How to get the file size given a path?

I am using Xcode 7.0 and running OS X 10.10.5.

update: Xcode 11.4.1 • Swift 5.2


extension URL {
    /// check if the URL is a directory and if it is reachable 
    func isDirectoryAndReachable() throws -> Bool {
        guard try resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true else {
            return false
        }
        return try checkResourceIsReachable()
    }

    /// returns total allocated size of a the directory including its subFolders or not
    func directoryTotalAllocatedSize(includingSubfolders: Bool = false) throws -> Int? {
        guard try isDirectoryAndReachable() else { return nil }
        if includingSubfolders {
            guard
                let urls = FileManager.default.enumerator(at: self, includingPropertiesForKeys: nil)?.allObjects as? [URL] else { return nil }
            return try urls.lazy.reduce(0) {
                    (try $1.resourceValues(forKeys: [.totalFileAllocatedSizeKey]).totalFileAllocatedSize ?? 0) + $0
            }
        }
        return try FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: nil).lazy.reduce(0) {
                 (try $1.resourceValues(forKeys: [.totalFileAllocatedSizeKey])
                    .totalFileAllocatedSize ?? 0) + $0
        }
    }

    /// returns the directory total size on disk
    func sizeOnDisk() throws -> String? {
        guard let size = try directoryTotalAllocatedSize(includingSubfolders: true) else { return nil }
        URL.byteCountFormatter.countStyle = .file
        guard let byteCount = URL.byteCountFormatter.string(for: size) else { return nil}
        return byteCount + " on disk"
    }
    private static let byteCountFormatter = ByteCountFormatter()
}

usage:

do {
    let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    if let sizeOnDisk = try documentDirectory.sizeOnDisk() {
        print("Size:", sizeOnDisk) // Size: 3.15 GB on disk
    }
} catch {
    print(error)
}

osx How To Get Directory Size With Swift On OS X?, update: Xcode 8.2.1 • Swift 3.0.2 // get your directory url let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: . How to View the Size of All Directory Contents by Command Line If you want to see the size of the current directory contents from the command line, including any containing folders and files, the du -sh command with a star wildcard, like so:

Swift 3 version here:

 func findSize(path: String) throws -> UInt64 {

    let fullPath = (path as NSString).expandingTildeInPath
    let fileAttributes: NSDictionary = try FileManager.default.attributesOfItem(atPath: fullPath) as NSDictionary

    if fileAttributes.fileType() == "NSFileTypeRegular" {
        return fileAttributes.fileSize()
    }

    let url = NSURL(fileURLWithPath: fullPath)
    guard let directoryEnumerator = FileManager.default.enumerator(at: url as URL, includingPropertiesForKeys: [URLResourceKey.fileSizeKey], options: [.skipsHiddenFiles], errorHandler: nil) else { throw FileErrors.BadEnumeration }

    var total: UInt64 = 0

    for (index, object) in directoryEnumerator.enumerated() {
        guard let fileURL = object as? NSURL else { throw FileErrors.BadResource }
        var fileSizeResource: AnyObject?
        try fileURL.getResourceValue(&fileSizeResource, forKey: URLResourceKey.fileSizeKey)
        guard let fileSize = fileSizeResource as? NSNumber else { continue }
        total += fileSize.uint64Value
        if index % 1000 == 0 {
            print(".", terminator: "")
        }
    }

    if total < 1048576 {
        total = 1
    }
    else
    {
        total = UInt64(total / 1048576)
    }

    return total
}

enum FileErrors : ErrorType {
    case BadEnumeration
    case BadResource
}

Output value is megabyte. Converted from source: https://gist.github.com/rayfix/66b0a822648c87326645

How to Get the Size of a Directory from Command Line, get your directory url let documentsDirectoryURL = FileManager.default.urls(for: . documentDirectory, in: .userDomainMask).first! // check if the url is a directory if� To do so, open the folder in question, select View -> Show View Options from the menu bar or press the keys Command-J, and check Calculate All Sizes. Finder will now remember your viewing

To anyone who is looking for a solution for Swift 5+ and Xcode 11+ look at this gist

func directorySize(url: URL) -> Int64 {
    let contents: [URL]
    do {
        contents = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: [.fileSizeKey, .isDirectoryKey])
    } catch {
        return 0
    }

    var size: Int64 = 0

    for url in contents {
        let isDirectoryResourceValue: URLResourceValues
        do {
            isDirectoryResourceValue = try url.resourceValues(forKeys: [.isDirectoryKey])
        } catch {
            continue
        }

        if isDirectoryResourceValue.isDirectory == true {
            size += directorySize(url: url)
        } else {
            let fileSizeResourceValue: URLResourceValues
            do {
                fileSizeResourceValue = try url.resourceValues(forKeys: [.fileSizeKey])
            } catch {
                continue
            }

            size += Int64(fileSizeResourceValue.fileSize ?? 0)
        }
    }
    return size

}

How to Get the Size of a File or Folder in Mac OS, Terminal in macOS. Want to for retrieving the size of a directory will work the same on Mac OS, mac OS X, linux, and most other unix varieties. head -20: Output the first 20 lines result. Use the below du command format to get the total size of a given directory. $ du -hs /home/daygeek/Documents or $ du -h --max-depth=0 /home/daygeek/Documents/ 20G /home/daygeek/Documents.

Swift 3 version

private func sizeToPrettyString(size: UInt64) -> String {

    let byteCountFormatter = ByteCountFormatter()
    byteCountFormatter.allowedUnits = .useMB
    byteCountFormatter.countStyle = .file
    let folderSizeToDisplay = byteCountFormatter.string(fromByteCount: Int64(size))

    return folderSizeToDisplay

}

contentsOfDirectory(at:includingPropertiesForKeys:options:), The tricks work the same on all versions of Mac OS and Mac OS X, as the Get Info capability See file and folder size in Finder of Mac OS with Get Info next post iOS 11.3 Beta 4, macOS 10.13.4 Beta 4 Released for Testing� Mac OS X doesn’t have an obvious way to view the exact text based path to a folder (otherwise known as a directory) in the finder window. You can have it show a graphical path, but getting just the text based path to a directory (for use in the Terminal for example) requires a couple of extra steps.

For anyone looking for the barebones implementation (works the same on macOS and iOS):

Swift 5

extension URL {
    var fileSize: Int? { // in bytes
        do {
            let val = try self.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey])
            return val.totalFileAllocatedSize ?? val.fileAllocatedSize
        } catch {
            print(error)
            return nil
        }
    }
}

extension FileManager {
    func directorySize(_ dir: URL) -> Int? { // in bytes
        if let enumerator = self.enumerator(at: dir, includingPropertiesForKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey], options: [], errorHandler: { (_, error) -> Bool in
            print(error)
            return false
        }) {
            var bytes = 0
            for case let url as URL in enumerator {
                bytes += url.fileSize ?? 0
            }
            return bytes
        } else {
            return nil
        }
    }
}

Usage

let fm = FileManager.default
let tmp = fm.temporaryDirectory

if let size = fm.directorySize(tmp) {
    print(size)
}

What makes this barebones: doesn't precheck if a directory is a directory or a file is a file (returns nil either way), and the results are returned in their native format (bytes as integers).

fileSize, iOS 4.0+; macOS 10.6+; Mac Catalyst 13.0+; tvOS 9.0+; watchOS 2.0+ If you want directory contents to have no pre-fetched file properties, pass an empty array� To print only the file name and size we can run the below command from a batch file. @echo off for /F "tokens=4,5" %%a in ('dir c:\windows\fonts') do echo %%a %%b. Save the above commands to a text file, say filesize.bat, and run it from command prompt. Get directory size. There’s no Windows built in command to find directory size.

FileManager Class Tutorial for macOS: Getting Started with the File , iOS 7.0+; macOS 10.9+; Mac Catalyst 13.0+; tvOS 9.0+; watchOS 2.0+; Xcode 8.0 var fileSize: Int? { get } be either a file or directory) and is used to identify the document regardless of where it gets moved on a volume. var fileAllocatedSize: Int? Total size allocated on disk for the file in bytes (number of blocks times block � Run the app, and click the Select Directory button. Pick a folder or a drive to scan for folders. The app will show you each folder and its size. You can sort the results by folder size. Expand each folder and you can see the size of the folders nested under it.

macOS: How to Check Folder Sizes in Bulk, In this tutorial, learn to use the FileManager class in a macOS app. Now that you have a URL pointing to your home folder, you can derive the NSString has a lot of file path manipulation methods, but Swift's String struct doesn't. more important as Apple transitions to the new Apple File System (APFS). Detect Combined Size of a Folder (Including Subfolders) in Finder OS X: If you get annoyed as I do that sometimes you can't see the complete size of a folder in… Read more

How-To: Show the size of folders in the Finder on Mac [Video , Andrew actually learned of this tip a couple of minutes ago. If you've ever wondered how to check folder sizes in bulk, here's how to do it. Show Available Disk Space in Mac OS X by Showing the Folder Status Bar Aug 5, 2011 - 27 Comments In Apple’s quest to simplify the Mac user experience, they hid the windows status bar in Mac OS X starting with Lion and continuing through with Mountain Lion, Mavericks, OS X Yosemite, El Capitan, and Sierra.

Comments
  • There are 2 screen shots below. I cannot get the sizes to match. My documents directory is ~1.50 GBs drive.google.com/file/d/0B8F7IPsTUK7gUEVzeU5JRTF0Qms/… But the console is only reporting 272 bytes drive.google.com/file/d/0B8F7IPsTUK7gaDBiZkdfREZhWkE/…
  • Is it a local folder ?
  • It is. The only change to your code I put in was a print of the document url just to make sure it was correct.
  • @JackVaughn you have to manually sum all file sizes. See my Edit
  • Even with the updated code, I am still getting the size 6,148 bytes for the directory, rather than the ~1,500,000,000 the directory is.
  • Note that you also need (from source cited): enum FileErrors : Error { case BadEnumeration case BadResource }
  • I add the the ErrorType enum also. Thx Dan