Getting List of Files in Documents Folder

Getting list of files in documents folder

This solution works with Swift 4 (Xcode 9.2) and also with Swift 5 (Xcode 10.2.1+):

let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
// process files
} catch {
print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
}

Here's a reusable FileManager extension that also lets you skip or include hidden files in the results:

import Foundation

extension FileManager {
func urls(for directory: FileManager.SearchPathDirectory, skipsHiddenFiles: Bool = true ) -> [URL]? {
let documentsURL = urls(for: directory, in: .userDomainMask)[0]
let fileURLs = try? contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: skipsHiddenFiles ? .skipsHiddenFiles : [] )
return fileURLs
}
}

// Usage
print(FileManager.default.urls(for: .documentDirectory) ?? "none")

Listing files in a specific folder

do {
let files = try NSFileManager.defaultManager().contentsOfDirectoryAtPath("/Users/username/Documents/Photos")
print(files)
} catch {
print(error)
}

Get File List from sub folder of Documents Directory swift ios

This is the working code..

func listFilesFromDocumentsFolder() -> [String]
{
var theError = NSErrorPointer()
let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]

if dirs != nil {
let dir = dirs![0]//this path upto document directory

//this will give you the path to MyFiles
let MyFilesPath = dir.stringByAppendingPathComponent("/BioData")
if !NSFileManager.defaultManager().fileExistsAtPath(MyFilesPath) {
NSFileManager.defaultManager().createDirectoryAtPath(MyFilesPath, withIntermediateDirectories: false, attributes: nil, error: theError)
} else {
println("not creted or exist")
}

let fileList = NSFileManager.defaultManager().contentsOfDirectoryAtPath(MyFilesPath, error: theError) as! [String]

var count = fileList.count
for var i = 0; i < count; i++
{
var filePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
filePath = filePath.stringByAppendingPathComponent(fileList[i])
let properties = [NSURLLocalizedNameKey, NSURLCreationDateKey, NSURLContentModificationDateKey, NSURLLocalizedTypeDescriptionKey]
var attr = NSFileManager.defaultManager().attributesOfItemAtPath(filePath, error: NSErrorPointer())
}
println("fileList: \(fileList)")
return fileList.filter{ $0.pathExtension == "pdf" }.map{ $0.lastPathComponent } as [String]
}else{
let fileList = [""]
return fileList
}
}

Command to list all files in a folder as well as sub-folders in windows

The below post gives the solution for your scenario.

dir /s /b /o:gn

/S Displays files in specified directory and all subdirectories.

/B Uses bare format (no heading information or summary).

/O List by files in sorted order.

Then in :gn, g sorts by folders and then files, and n puts those files in alphabetical order.

how to get a list of files from the directory and pass it to the ListView?

Don't call _getFilesCount() in build(). build() can be called very frequently. Call it in initState() and store the result instead of re-reading over and over again.

UWP : How to get a list of all the text file names from a sub folder of Documents folder

If you want to access Documents folder, you can use FolderPicker or KnownFolders.DocumentsLibrary method.

About FolderPicker, you need to access folders by interacting with a picker, but you can directly choose the folder you want to. About KnownFolders.DocumentsLibrary method, you need to add extra broadFileSystemAccess capability and allow your app to access file system in settings.

//FolderPicker
var folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
folderPicker.FileTypeFilter.Add("*");
Windows.Storage.StorageFolder subFolder = await folderPicker.PickSingleFolderAsync();

//KnownFolders.DocumentsLibrary
//StorageFolder Myfolder = KnownFolders.DocumentsLibrary;
//StorageFolder subFolder = await Myfolder.GetFolderAsync("YouSubFolder");

List fileTypeFilter = new List();
fileTypeFilter.Add(".txt");
QueryOptions queryOptions = new QueryOptions(Windows.Storage.Search.CommonFileQuery.OrderByName, fileTypeFilter);
StorageFileQueryResult queryResult = subFolder.CreateFileQueryWithOptions(queryOptions);
var files = await queryResult.GetFilesAsync();
foreach (var file in files)
{
string name = file.Name;
}


Related Topics



Leave a reply



Submit