美文网首页
macOS开发之获取本地磁盘下全部目录

macOS开发之获取本地磁盘下全部目录

作者: 橘子味草莓 | 来源:发表于2023-02-13 17:30 被阅读0次

获取Macintosh HD磁盘下的目录列表:

let fileManager = FileManager.default    
let resourceKeys: [URLResourceKey] = [.volumeNameKey, .volumeLocalizedFormatDescriptionKey,.localizedNameKey,.fileSizeKey,.isDirectoryKey,.isPackageKey,.effectiveIconKey]
let fileEnum = fileManager.enumerator(at: URL(string: "/")!, includingPropertiesForKeys: resourceKeys,options: .skipsHiddenFiles,errorHandler: nil)
let fileURL = fileEnum?.first
if let volumes = fileManager.mountedVolumeURLs(includingResourceValuesForKeys: resourceKeys, options: .skipHiddenVolumes) {
for volume in volumes {
 if let resources = try? volume.resourceValues(forKeys: Set(resourceKeys)),
                   let name = resources.volumeName,
                   let format = resources.volumeLocalizedFormatDescription {
                    print("Disk Info:\(name), format: \(format)")
                    if name == "Macintosh HD" {
                        filesList = contentsOf(folder: URL(string: "/")!)
                        print("File List:\(filesList)")
                        tableView.reloadData()
                    }
                }
            }
}

获取文件列表的函数:

//get files list
    func contentsOf(folder: URL) -> [URL] {
        let fileManager = FileManager.default
        do {
          let contents = try fileManager.contentsOfDirectory(atPath: folder.path)
          let urls = contents
            .filter { return showInvisibles ? true : $0.first != "." }
            .map { return folder.appendingPathComponent($0) }
          return urls
        } catch {
          return []
        }
    }

获取文件信息的函数:

// file info
    func infoAbout(url: URL) -> String {
      let fileManager = FileManager.default
      do {
        let attributes = try fileManager.attributesOfItem(atPath: url.path)
        var report: [String] = ["\(url.path)", ""]
        for (key, value) in attributes {
          // ignore NSFileExtendedAttributes as it is a messy dictionary
          if key.rawValue == "NSFileExtendedAttributes" { continue }
          report.append("\(key.rawValue):\t \(value)")
        }
        return report.joined(separator: "\n")
      } catch {
        return "No information available for \(url.path)"
      }
    }

获取文件图标的代码:

let item = filesList[row]
let fileIcon = NSWorkspace.shared.icon(forFile: item.path)

相关文章

网友评论

      本文标题:macOS开发之获取本地磁盘下全部目录

      本文链接:https://www.haomeiwen.com/subject/uhcskdtx.html