Udostępnij za pośrednictwem


Quickstart: Getting file properties (HTML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

Get properties for a file represented by a StorageFile object.

Prerequisites

Many of the methods used to interact with folders and files are asynchronous. You can learn how to write asynchronous apps in Asynchronous programming in JavaScript.

Getting a file's top-level properties

Many top-level file properties are accessible as members of the StorageFile class. These properties include datums such as the files attributes, content type, creation date, display name, file type, and so on.

The following code enumerates all the files in the Pictures library, accessing each file's top-level name and type properties.

var library = Windows.Storage.KnownFolders.picturesLibrary;
var outString = "";

library.getFilesAsync().then(function (files) {
    files.forEach(function (file) {
    outString += "File name: " + file.name + "\n";
    outString += "File type: " + file.fileType + "\n";
    outString += "\n"
});

Getting a file's basic properties

Many basic file properties are obtained by first calling the StorageFile.getBasicPropertiesAsync method. This method returns a BasicProperties object, which defines properties for the size of the item (file or folder) as well as when the item was last modified.

The following code enumerates all the files in the Pictures library, accessing both top-level and basic properties for each file. Note that the code makes use of JavaScript promises and the WinJS.Promises.join method in order to synchronize the two asynchronous method calls: StorageFolder.getFilesAsync and StorageFile.getBasicPropertiesAsync.


var library = Windows.Storage.KnownFolders.picturesLibrary;
var outString = "";

library.getFilesAsync().then(function (files) {
    var promises = [];
    files.forEach(function (file) {    
        promises.push(WinJS.Promise.as(file));
        promises.push(file.getBasicPropertiesAsync());
    })
    return WinJS.Promise.join(promises);
})
.done(function (results) {
    var counter = 0

    while (counter < results.length) {
        var file = results[counter];    
        var props = results[counter + 1];
        outString += "File name: " + file.name + "\n";
        outString += "File type: " + file.fileType + "\n";
        outString += "File size: " + props.size + "\n";
        outString += "\n"
        counter = counter + 2;
    }
});

Summary

In this quickstart, you learned how to get top-level and basic properties for a given file represented by a StorageFile object.