#Win8Dev Tutorial: Handling Files and Folders in your WinRT apps



Many time we need to access files and folders from our applications. The Windows Store apps SDK provides us Asynchronous APIs to use for this service to query files and folders. You have to be familiar with async await calls in order to get started with this.

 

This post is part of the Windows Store Application Development Tutorial series. Today we will learn how to handle files and folders in your Windows 8 metro applications.

 

Understand the API

StorageFolder” is a class of Windows Store SDK present in the Windows.Store namespace and provides us easy access APIs to handle all file and folder operations. The class implements few interfaces named IStorageFolder, IStorageItem, IStorageFolderQueryOperations, IStorageItemProperties to manipulate folders and their contents to provides information about them.

 

To get the installed location of the current application package, you need to call the Package.Current.InstalledLocation property get the folder handle and store it as StorageFolder reference. This is how you can call it:

 
StorageFolder installedStorageFolder = Package.Current.InstalledLocation;

 

 

Let’s quickly see the API methods present in the Windows.Store.StorageFolder class. Read out the method comments to understand the API calls:

 
// Creates a new file in the folder or file group.
// When this method completes, it returns the new file as a StorageFile.
public IAsyncOperation<StorageFile> CreateFileAsync(string desiredName);
 
// Creates a new file in the current folder, and specifies what to do if a file 
// with the same name already exists in the current folder.
// When this method completes, it returns the new file as a StorageFile.
public IAsyncOperation<StorageFile> CreateFileAsync(string desiredName, 
                                                    CreationCollisionOption options);
 
// Creates a new subfolder inside the current folder.
// When this method completes, it returns the new subfolder as a StorageFolder.
public IAsyncOperation<StorageFolder> CreateFolderAsync(string desiredName);
 
// Creates a new sub-folder inside the current folder, and specifies what to do 
// if a folder with the same name already exists in the current folder.
// When this method completes, it returns the new subfolder as a StorageFolder.
public IAsyncOperation<StorageFolder> CreateFolderAsync(string desiredName, 
                                                        CreationCollisionOption options);
 
// Gets a single file from the current folder using the specified file name.
// When this method completes successfully, it returns a StorageFile that 
// represents the file.
public IAsyncOperation<StorageFile> GetFileAsync(string name);
 
// Gets a single sub-folder from the current folder using the specified folder name.
// When this method completes successfully, it returns a StorageFolder that 
// represents the sub-folder.
public IAsyncOperation<StorageFolder> GetFolderAsync(string name);
 
// Gets a single file or sub-folder from the current folder using the name 
// of the item. When this method completes successfully, it returns the file or folder.
public IAsyncOperation<IStorageItem> GetItemAsync(string name);
 
// Gets the top-level files in the current folder.
// When this method completes successfully, it returns a list of the files 
// in the folder. Each file in the list is represented by a StorageFile object.
public IAsyncOperation<IReadOnlyList<StorageFile>> GetFilesAsync();
 
// Gets a list of the top-level sub-folders of the current folder.
// When this method completes successfully, it returns a list of the files.
// Each folder in the list is represented by a StorageFolder.
public IAsyncOperation<IReadOnlyList<StorageFolder>> GetFoldersAsync();
 
// Gets a list of top-level files and sub-folders inside the current folder.
// When this method completes successfully, it returns a list of the files 
// and folders inside the current folder. The items in the 
// list are represented by objects of type IStorageItem.
public IAsyncOperation<IReadOnlyList<IStorageItem>> GetItemsAsync();
 
// Renames the current folder.
// No object or value is returned by this method when it completes.
public IAsyncAction RenameAsync(string desiredName);
 
// Renames the current folder and specifies what to do if a folder with the 
// same name already exists. No object or value is returned by this method 
// when it completes.
public IAsyncAction RenameAsync(string desiredName, NameCollisionOption option);
 
// Deletes the current folder or file group.
// No object or value is returned by this method when it completes.
public IAsyncAction DeleteAsync();
 
// Deletes the current folder or file group, optionally deleting it permanently.
// No object or value is returned by this method when it completes.
public IAsyncAction DeleteAsync(StorageDeleteOption option);
 
// When this method completes successfully, it returns a list of the files 
// in the folder. Each file in the list is represented by a StorageFile object.
public IAsyncOperation<IReadOnlyList<StorageFile>> GetFilesAsync(CommonFileQuery query, 
                                                                 uint startIndex,
                                                                 uint maxItemsToRetrieve);
 
// Gets a list of all files in the current folder and its sub-folders. 
// Files are filtered and sorted based on the specified CommonFileQuery.
// When this method completes successfully, it returns a list of the files 
// in the folder. Each file in the list is represented by a StorageFile object.
public IAsyncOperation<IReadOnlyList<StorageFile>> GetFilesAsync(CommonFileQuery query);
 
// Gets an index-based range of StorageFolder objects that represent groups of files 
// in the current folder. Files are filtered and grouped based on the specified 
// CommonFolderQuery and are included in the range based on the resulting indexes.
// When this method completes successfully, it returns a list of the files. 
// Each folder in the list is represented by a StorageFolder.
public IAsyncOperation<IReadOnlyList<StorageFolder>> GetFoldersAsync(CommonFolderQuery query, 
                                                                     uint startIndex, 
                                                                     uint maxItemsToRetrieve);
 
// Gets a list of StorageFolder objects that represent groups of files in the 
// current folder. Files are filtered and grouped based on the specified CommonFolderQuery.
// When this method completes successfully, it returns a list of the files (type IVectorView). 
// Each folder in the list is represented by a StorageFolder.
public IAsyncOperation<IReadOnlyList<StorageFolder>> GetFoldersAsync(CommonFolderQuery query);
 
// Gets a StorageFolder that represents the folder at the specified file-system path.

// When this method completes successfully, it returns a StorageFolder that represents the

// folder.

public static IAsyncOperation<StorageFolder> GetFolderFromPathAsync(string path);

 

 

The above API methods will provide you instance towards the StorageFolder asynchronously. When you are calling it from a method, you must have to mark the method as async and the call must be marked as await.

 

The StorageFolder instance also provides you few information about the file and folder by exposing few properties. You can directly call those properties to grab the information.

 

Here are the properties that the StorageFolder exposes to the developers:

 
// Gets the attributes of the current folder.
public FileAttributes Attributes { [MethodImpl] get; }
 
// Gets the date and time that the current folder was created.
public DateTimeOffset DateCreated { [MethodImpl] get; }
 
// Gets the name of the current folder.
public string Name { [MethodImpl] get; }
 
// Gets the full file-system path of the current folder, if the folder has a path.
public string Path { [MethodImpl] get; }
 
// Gets the user-friendly name of the current folder.
public string DisplayName { [MethodImpl] get; }
 
// Gets the user-friendly type of the folder or file group.
public string DisplayType { [MethodImpl] get; }
 
// Gets an identifier for the current folder. This ID is unique for the query result 
// or StorageFolder that contains the current folder or file group, and can be used 
// to distinguish between items that have the same name.
public string FolderRelativeId { [MethodImpl] get; }
 
// Gets an object that provides access to the content-related properties 
// of the current folder.
public StorageItemContentProperties Properties { [MethodImpl] get; }

 

 

You can easily understand the need of each property from the above property level comments mentioned above.

 

How to use the APIs?

In case you need to create or get an instance of file or folder inside your application’s root folder, you first need an instance of the installed directory which you can grab by calling Package.Current.InstalledLocation as mentioned above. Once you have the instance of the same, you can easily call the above APIs and pass required parameters to do so.

 

Let me show you how to create and get folders and files easily with the APIs present in Windows.Store.StorageFolder class:

 
// ways to create new folder
folder.CreateFolderAsync("Demo Folder", CreationCollisionOption.FailIfExists);
folder.CreateFolderAsync("Demo Folder", CreationCollisionOption.GenerateUniqueName);
folder.CreateFolderAsync("Demo Folder", CreationCollisionOption.OpenIfExists);
folder.CreateFolderAsync("Demo Folder", CreationCollisionOption.ReplaceExisting);
 
// ways to get folder
folder.GetFolderAsync("Demo Folder");
 
// ways to create new file
folder.CreateFileAsync("Demo File.txt", CreationCollisionOption.OpenIfExists);
folder.CreateFileAsync("Demo File.txt", CreationCollisionOption.GenerateUniqueName);
folder.CreateFileAsync("Demo File.txt", CreationCollisionOption.OpenIfExists);
folder.CreateFileAsync("Demo File.txt", CreationCollisionOption.ReplaceExisting);
 
// ways to get file
folder.GetFileAsync("Demo File.txt");
 
// ways to get all files by search queries
folder.GetFilesAsync(CommonFileQuery.DefaultQuery);
folder.GetFilesAsync(CommonFileQuery.OrderByDate);
folder.GetFilesAsync(CommonFileQuery.OrderByMusicProperties);
folder.GetFilesAsync(CommonFileQuery.OrderByName);
folder.GetFilesAsync(CommonFileQuery.OrderBySearchRank);
folder.GetFilesAsync(CommonFileQuery.OrderByTitle);

 

 

In case you want to rename current folder handle, just call the API folder.RenameAsync(desiredName) with proper desired name and this will fire the rename operation on it.

 

The delete operation is also easy on a storage folder instance. You can do so by calling the DeleteAsync() method by passing proper parameters to it. There is an option to chose whether you want to use the default system delete operation or a permanent delete. In case of permanent delete operation, your folder will be deleted permanently without sending it to the recycle bin.

 

Here is how you can achieve this:

 
// ways to delete a folder instance
folder.DeleteAsync(StorageDeleteOption.Default);
folder.DeleteAsync(StorageDeleteOption.PermanentDelete);

 

 

End Note

I hope that, this chapter of the tutorial series will help you to understand the basic operations on file and folders. Explore the other APIs of this class to know more about it.

 

Stay tuned with me on Twitter, Facebook and Google+. Subscribe to my blog’s RSS feed and email newsletter to get updates directly delivered to your inbox. Don’t forget to share these tutorial series to your network and if you have any queries, let me know by dropping a line below in the comments section.

0 comments


 
© 2008-2014 Kunal-Chowdhury.com | Designed by Kunal Chowdhury
Back to top