How to get the file size given a path?

后端 未结 10 1165
自闭症患者
自闭症患者 2020-11-30 20:22

I have a path to file contained in an NSString. Is there a method to get its file size?

相关标签:
10条回答
  • 2020-11-30 20:56

    This one liner can help people:

    unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:someFilePath error:nil] fileSize];
    

    This returns the file size in Bytes.

    0 讨论(0)
  • 2020-11-30 20:56

    In Swift 3.x and above you can use:

    do {
        //return [FileAttributeKey : Any]
        let attr = try FileManager.default.attributesOfItem(atPath: filePath)
        fileSize = attr[FileAttributeKey.size] as! UInt64
    
        //or you can convert to NSDictionary, then get file size old way as well.
        let attrDict: NSDictionary = try FileManager.default.attributesOfItem(atPath: filePath) as NSDictionary
        fileSize = dict.fileSize()
    } catch {
        print("Error: \(error)")
    }
    
    0 讨论(0)
  • 2020-11-30 21:00

    Swift4:

            let attributes = try! FileManager.default.attributesOfItem(atPath: path)
            let fileSize = attributes[.size] as! NSNumber
    
    0 讨论(0)
  • 2020-11-30 21:01

    Swift 2.2:

    do {
        let attr: NSDictionary = try NSFileManager.defaultManager().attributesOfItemAtPath(path)
        print(attr.fileSize())
    } catch {
            print(error)
    }
    
    0 讨论(0)
提交回复
热议问题