Skip to main content
June 25, 2013
Windows Phone Developer Blog

File handling with Windows.Storage APIs



This blog post was authored by Douglas Laudenschlager, a Senior Content Developer on the Windows Phone Developer Content team.

– Adam


Windows Phone 8 introduces new APIs for file handling that are convergent with the APIs in Windows Store apps. These APIs are in the Windows.Storage and Windows.Storage.Streams namespaces. You can use them in place of the APIs from the System.IO.IsolatedStorage namespace that might be familiar to a Windows Phone 7 developer. When you switch to the Windows.Storage APIs, it’ll be easier to port your Windows Phone app to the Windows Store, and easier to upgrade your app to future versions of the Windows Phone operating system.

You can see all the methods and properties of these new namespaces here:

Many of the methods in these namespaces are asynchronous methods that require you to use the async and await keywords. For more info, see Asynchronous Programming with Async and Await (C# and Visual Basic).

Learn from the sample

The Windows Phone SDK documentation team recently published the Basic Storage Recipes sample. Download the sample to see working examples of the programming tasks described in this blog post.

Here’s the list of tasks demonstrated in the Basic Storage Recipes sample:

clip_image001

In addition to showing you how to work with files, the Basic Storage Recipes sample also demonstrates the following tasks:

  • How to retrieve a directory tree recursively
  • How to pass data from one page to the next without using the query string in the page URI
  • How to persist application state when the app is deactivated
  • How to call async methods successfully in the Application_Deactivated event handler
  • How to use the PhotoChooserTask and the CameraCaptureTask.

The local folder is still “isolated storage”

In Windows Phone 8, the isolated area of storage reserved for each app is called the local folder. Only the app itself (and the operating system) can access the files you store in this folder. Here’s how you retrieve the local folder using the Windows.Storage APIs:

C#
  1. StorageFolder localFolder = ApplicationData.Current.LocalFolder;

Here’s how you previously retrieved the local folder using the IsolatedStorage APIs:

C#
  1. IsolatedStorageFile store =
  2.     IsolatedStorageFile.GetUserStoreForApplication();

Creating new folders and files

To create a new subfolder in the local folder, call the StorageFolder.CreateFolderAsync method.

C#
  1. StorageFolder newFolder =
  2.     await localFolder.CreateFolderAsync(folderName,
  3.         CreationCollisionOption.ReplaceExisting);

To create a new file in the local folder, call the StorageFolder.CreateFileAsync method.

C#
  1. StorageFile newFile =
  2.     await localFolder.CreateFileAsync(newFileName,
  3.         CreationCollisionOption.ReplaceExisting);

Writing a text file

Use these methods to write a new text file in the local folder:

  1. Create the new file using the StorageFolder.CreateFileAsync method.
  2. Open the file using the StorageFile.OpenAsync method, which returns a stream.
  3. Open a DataWriter over the stream returned by OpenAsync.
  4. Write the text to the stream with the DataWriter.WriteString method.
  5. Flush and close the DataWriter using the StoreAsync method.

The sample method returns the path of the new text file. The sample app uses this return value to maintain a list of all the files it creates so it can delete them later.

C#
  1. // Write a text file to the app’s local folder.
  2. public static async Task<string> WriteTextFile(string filename, string contents)
  3. {
  4.     StorageFolder localFolder = ApplicationData.Current.LocalFolder;
  5.     StorageFile textFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
  6.  
  7.     using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite))
  8.     {
  9.         using (DataWriter textWriter = new DataWriter(textStream))
  10.         {
  11.             textWriter.WriteString(contents);
  12.             await textWriter.StoreAsync();
  13.         }
  14.     }
  15.  
  16.     return textFile.Path;
  17. }

Reading a text file

Use these methods to read the contents of a text file in the local folder:

  1. Get the file using StorageFolder.GetFileAsync.
  2. Open the file for reading using StorageFile.OpenReadAsync, which returns a stream.
  3. Open a DataReader over the stream returned by OpenReadAsync.
  4. Load the contents of the stream using DataReader.LoadAsync.
  5. Retrieve the contents as a string using DataReader.ReadString.

The sample method returns the contents of the text file as a string. The sample app uses this return value to display the output on a new page.

C#
  1. // Read the contents of a text file from the app’s local folder.
  2. public static async Task<string> ReadTextFile(string filename)
  3. {
  4.     string contents;
  5.  
  6.     StorageFolder localFolder = ApplicationData.Current.LocalFolder;
  7.     StorageFile textFile = await localFolder.GetFileAsync(filename);
  8.  
  9.     using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
  10.     {
  11.         using (DataReader textReader = new DataReader(textStream))
  12.         {
  13.             uint textLength = (uint)textStream.Size;
  14.             await textReader.LoadAsync(textLength);
  15.             contents = textReader.ReadString(textLength);
  16.         }
  17.     }
  18.     return contents;
  19. }

Copying a photo

Use these methods to create a new binary file from the stream returned by the PhotoChooserTask or the CameraCaptureTask.

  1. Create the new file using the StorageFolder.CreateFileAsync method.
  2. Open an output stream for writing using the StorageFile.OpenStreamForWriteAsync extension method.
  3. Copy the binary data from the input stream to the output stream using the System.IO.Stream.CopyToAsync method.

The sample method returns the path of the new binary file. The sample app uses this return value to maintain a list of all the files it creates so it can delete them later.

C#
  1. // Save a photo to the app’s local folder.
  2. public static async Task<string> SavePhoto(Stream photoToSave, string fileName)
  3. {
  4.     StorageFolder localFolder = ApplicationData.Current.LocalFolder;
  5.     StorageFile photoFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
  6.     using (var photoOutputStream = await photoFile.OpenStreamForWriteAsync())
  7.     {
  8.         await photoToSave.CopyToAsync(photoOutputStream);
  9.     }
  10.  
  11.     return photoFile.Path;
  12. }

Reading a directory tree recursively

The Basic Storage Recipes sample displays the contents of the app’s local folder after you run each task.

clip_image002

To build the directory tree recursively, the sample app uses the following two methods, which are contained in a static helper class. These methods store the directory tree in a StringBuilder named folderContents.

C#
  1. private static StringBuilder folderContents;
  2.  
  3. private const string FOLDER_PREFIX = “”;
  4. private const int PADDING_FACTOR = 3;
  5. private const char SPACE = ‘ ‘;
  6.  
  7. // Begin recursive enumeration of files and folders.
  8. public static async Task<string> EnumerateFilesAndFolders(StorageFolder rootFolder)
  9. {
  10.     // Initialize StringBuilder to contain output.
  11.     folderContents = new StringBuilder();
  12.     folderContents.AppendLine(FOLDER_PREFIX + rootFolder.Name);
  13.  
  14.     await ListFilesInFolder(rootFolder, 1);
  15.  
  16.     return folderContents.ToString();
  17. }
  18.  
  19. // Continue recursive enumeration of files and folders.
  20. private static async Task ListFilesInFolder(StorageFolder folder, int indentationLevel)
  21. {
  22.     string indentationPadding = String.Empty.PadRight(indentationLevel * PADDING_FACTOR, SPACE);
  23.  
  24.     // Get the subfolders in the current folder.
  25.     var foldersInFolder = await folder.GetFoldersAsync();
  26.     // Increase the indentation level of the output.
  27.     int childIndentationLevel = indentationLevel + 1;
  28.     // For each subfolder, call this method again recursively.
  29.     foreach (StorageFolder currentChildFolder in foldersInFolder)
  30.     {
  31.         folderContents.AppendLine(indentationPadding + FOLDER_PREFIX + currentChildFolder.Name);
  32.         await ListFilesInFolder(currentChildFolder, childIndentationLevel);
  33.     }
  34.  
  35.     // Get the files in the current folder.
  36.     var filesInFolder = await folder.GetFilesAsync();
  37.     foreach (StorageFile currentFile in filesInFolder)
  38.     {
  39.         folderContents.AppendLine(indentationPadding + currentFile.Name);
  40.     }
  41. }

Persisting application state in the Application_Deactivated event handler

If you call an async method directly to persist state in the Application_Deactivated event handler, the method never finishes its work. The trick is to run the task on a separate thread and wait for its completion. The following routine calls two helper methods that save the lists of folders and files created by the sample app when it’s deactivated. When the user activates the app again, the list of temporary files is still available for the Cleanup method.

C#
  1. // Code to execute when the application is deactivated (sent to background)
  2. // This code will not execute when the application is closing
  3. private void Application_Deactivated(object sender, DeactivatedEventArgs e)
  4. {
  5.     Task.Run(async () =>
  6.     {
  7.         await StateHelper.SaveList(foldersToDelete, FOLDER_LIST_NAME);
  8.     }).Wait();
  9.  
  10.     Task.Run(async () =>
  11.     {
  12.         await StateHelper.SaveList(filesToDelete, FILE_LIST_NAME);
  13.     }).Wait();
  14.  
  15. }

System.IO is still useful

The Basic Storage Recipes sample app we refer to in this blog post contains several methods and properties from the System.IO namespace that are still useful:

  • Extension methods such as OpenStreamForWriteAsync and OpenStreamForReadAsync
  • The Directory.Exists and File.Exists methods and the FileNotFoundException
  • The Path.Combine, Path.GetFilename, and Path.GetTempFileName methods

We hope you’ll find the Basic Storage Recipes sample useful as you adopt the Windows.Storage APIs in your apps for Windows Phone 8.