Loading and saving files

Applies to Windows and Windows Phone

How to use file pickers to load and save data.

The age-old technique of loading and saving files is alive and well in Windows 8.1, and has been updated to embrace the Cloud with Microsoft OneDrive. For example, you may be writing an app which combines data from different sources, and saves the results for later use. Or your users might want to create the file on a PC, and load it into the same app running on a portable tablet.

Note  Keep in mind that this type of file handing is not the best way to deal with small pieces of data such as app settings: see the topic Loading and saving settings for better ways to do that in Windows 8. Also, if your app wants to share data with other apps, your might be better using Charms instead.

File pickers

The UI control for loading or saving files is a File picker and is available to C++, C#, Visual Basic and JavaScript apps.

Quickstart: Accessing files with file pickers (Windows Runtime apps using C#/VB/C++ and XAML), How to continue your Windows Phone app after calling a file picker (Windows Phone Store apps using C#/VB/C++ and XAML)

File pickers are easy to use, and require minimal set-up. They look like this:

Activity and Progress controls

Here's a short piece of C# which opens up a File picker for saving a file, using the Photo directory as a default location.

Important  Windows 8.1 has changed the use of the DocumentsLibrary, and you are strongly discouraged from using this location for general files. See this posting from the Windows Store Developer Solutions blog for more information.

Note  Apps written for Windows Phone 8.1 should use PickSingleFileAndContinue rather than PickSingleFileAsync. Using this API requires some extra steps, see How to continue your Windows Phone app after calling a file picker (Windows Phone Store apps using C#/VB/C++ and XAML).


 private async void SaveFileButton_Click(object sender, RoutedEventArgs e)
        {
            
            FileSavePicker savePicker = new FileSavePicker();
            savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; 
            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = "New Document";
            StorageFile file = await savePicker.PickSaveFileAsync();
            if (file != null)
            {
                // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
                CachedFileManager.DeferUpdates(file);
                // write to file
                await FileIO.WriteTextAsync(file, file.Name);
                // Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
                // Completing updates may require Windows to ask for user input.
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
                if (status == FileUpdateStatus.Complete)
                {
                   // File was saved
                }
                else
                {
                   // File was not saved
                }
            }
            else
            {
                // File Operation cancelled
            }
        }

For the complete code sample, see File picker sample.

Loading and saving data

Using a File picker to open a file, or a location to save one, is only half the story. Now you need to read or write some actual data! Saving and loading files is achieved through the FileIO class, using methods such as WriteTextAsync and ReadTextAsync, like this:


try
{
    if (file != null)
    {
        await FileIO.WriteTextAsync(file, "Swift as a shadow");
    }
}
// Handle errors with catch blocks
catch (FileNotFoundException)
{
    // For example, handle file not found
}


It's important to use exception handling when using file handing code. To save and load data that is already in a collection or other data structure, you can use serialization to convert data into a format which can be saved and loaded. For a demonstration of this in action, see Save a collection to Application Storage.

Loading and saving without a file picker

The ApplicationsData class provides you with a location to save and load settings (see Loading and saving settings), but it's also where you can save and load the data that is unique to your app. Here is an example which will save and load some text: ideal for when your app needs to restore information between app launches. Using serialization, you could store a database as XML data in the same way.


        public static async void SaveData()
        {
            string myString = "This is the data I want to save";

            // Add:  using Windows.Storage;
            Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            // Optionally overwrite any existing file with CreationCollisionOption
            StorageFile file = await localFolder.CreateFileAsync("myData.txt", CreationCollisionOption.ReplaceExisting);

            try
            {
                if (file != null)
                {
                    await FileIO.WriteTextAsync(file, myString);
                }
            }
            catch (FileNotFoundException)
            {
                // Error saving data
            }
        }


        public async void LoadData()
        {
            string myString;    
            Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            try
            {
                StorageFile sampleFile = await localFolder.GetFileAsync("myData.txt");
                myString = await FileIO.ReadTextAsync(sampleFile);
            }

            catch (Exception)
            {
                // No file to load or error loading it
            }

            // Data is now in myString
        }
    }

These methods are declared with the async keyword, so use await when calling them. See Asynchronous programming (Windows Store apps) for more information.

Related topics

Topics for iOS devs
Resources for iOS devs
Windows 8 controls for iOS devs
Windows 8 cookbook for iOS devs
File handling topics
File picker sample
File access sample
Quickstart: Reading and writing a file (JavaScript)
Quickstart: Accessing files with file pickers (Windows Store apps using C#/VB/C++ and XAML)
Accessing data and files (Windows Store apps using C#/VB/C++ and XAML)

 

 

Show:
© 2014 Microsoft