Partilhar via


File handling, start to finish

[ 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 ]

Learn how to add file-handling capabilities to your Windows Store app using C++, C#, or Visual Basic and running on Windows 8.1.

Each section of this topic describes a key file-handling feature, links to a topic that provides more detail on that feature, and offers info about how to quickly find the relevant code in this topic's companion File handling, start to finish companion sample.

Note  Many of the methods used to interact with folders and files are asynchronous. You can learn how to write asynchronous Microsoft Visual C# apps in Quickstart: Using the await operator for asynchronous programming.

 

File access basics - enumerating, getting properties, and reading and writing data

Quickstart: Accessing files programmatically

You can access files in a location such as a folder, library, device, or network location, with just two lines of code—a call to the StorageFolder.GetFilesAsync function. See Quickstart: Accessing files programmatically for step-by-step instructions that show how to perform tasks like enumerating the top-level files and folders of a specified location and querying files in a location.

These steps show you how to enumerate files in a particular location:

  1. Acquire a StorageFolder object for the location you want. For example, you can do this by referencing one of the static KnownFolders properties - such as KnowFolders.PicturesLibrary.
  2. Call the returned StorageFolder object's StorageFolder.CreateFileQuery method with no parameters, indicating that you want all folders and files returned.
  3. When the StorageFolder.CreateFileQuery call returns, you'll have a StorageFileQueryResult object. Call its GetFilesAsync method.
  4. The StorageFileQueryResult.GetFilesAsync method returns an IReadOnlyList collection of StorageFile objects that can be iterated with a foreach loop.

This code example enumerates all files in Pictures. A Visual C# extension method is used so that you can easily query the files from any supported location.

// Generic extension method that returns all files for the specified
// KnownFolders location.
public static async
Task<System.Collections.Generic.IReadOnlyList<StorageFile>>
GetLibraryFilesAsync(this StorageFolder folder)
{
var query = folder.CreateFileQuery();
return await query.GetFilesAsync();
}
...
// Enumerate all files in Pictures.
var files = await KnownFolders.PicturesLibrary.GetLibraryFilesAsync();
// For each file found ...
foreach (StorageFile file in files)
{
// ... perform your processing.
}

This screen shot shows an example of enumerating the files in Pictures.

Find it in the sample: The sample includes a page titled File Access Basics, which includes the examples presented in this section. The relevant Visual C# and XAML code is centralized to the FileAccessBasicsPage.xaml.cs (OnEnumPicturesClick method) and FileAccessBasicsPage.xaml files, respectively, along with the extension method in the FileHelper.cs file.

Quickstart: Getting a file's properties

File properties describe or quantify an attribute of a file or its contents. For example, file properties include data such as file name, path, file size, file attributes, and date last accessed. Quickstart: Getting a file's propertiesshows how to retrieve and display a file's top-level and basic properties.

These steps show you how to get either top-level, basic, and extended file properties.

This code example enumerates all files in Pictures and displays various top-level, basic file, and extended properties.

// Generic extension method that returns all files for the
// specified KnownFolders location.
public static async Task<IReadOnlyList<StorageFile>>
GetLibraryFilesAsync(this StorageFolder folder)
{
var query = folder.CreateFileQuery();
return await query.GetFilesAsync();
}
...
// Enumerate all files in the Pictures library.
var files = await KnownFolders.PicturesLibrary.GetLibraryFilesAsync();
// For each file found ...
foreach (StorageFile file in files)
{
// Get top-level file properties.
StringBuilder fileProperties = new StringBuilder();
fileProperties.AppendLine("File name: " + file.Name);
fileProperties.AppendLine("File type: " + file.FileType);
// Get basic properties.
BasicProperties basicProperties = await file.GetBasicPropertiesAsync();
string fileSize = string.Format("{0:n0}", basicProperties.Size);
fileProperties.AppendLine("File size: " + fileSize + " bytes");
fileProperties.AppendLine("Date modified: " + basicProperties.DateModified);
// Specify extended properties to be retrieved.
List<string> propertiesName = new List<string>();
propertiesName.Add(dateAccessedProperty);
propertiesName.Add(fileOwnerProperty);
// Get extended properties.
IDictionary<string, object> extraProperties =
await file.Properties.RetrievePropertiesAsync(propertiesName);
// Get LastDateAccessed property.
var propValue = extraProperties[dateAccessedProperty];
if (propValue != null)
{
fileProperties.AppendLine("Date accessed: " + propValue);
}
// Get FileOwner property.
propValue = extraProperties[fileOwnerProperty];
if (propValue != null)
{
fileProperties.AppendLine("File owner: " + propValue);
}
}

This screen shot shows the results of querying for various file properties.

Find it in the sample: The sample includes a page titled File Access Basics, which includes the examples presented in this section. All of the relevant Visual C# and XAML code is centralized to the FileAccessBasicsPage.xaml.cs (OnGetFilePropertiesClick method) and FileAccessBasicsPage.xaml files, respectively, along with the extension method in the FileHelper.cs file.

Quickstart: Reading and writing a file

A Windows Store app reads and writes files via the FileIO class. See Quickstart: Reading and writing a file for code examples that show how to read and write various types of data using the FileIO and StorageFile classes.

Writing text to a file

  1. To write to a file, you must first acquire a StorageFile object to pass to one of the FileIO functions for writing data. In the companion sample, this is done by creating a file via the StorageFolder.CreateFileAsync function.
  2. Once you have a StorageFile object, you can write text to its underlying file via one of the overloaded FileIO.WriteTextAsync functions.
This code example writes the current data/time to a sample file.
// Create the sample file; replacing it if it already exists.
StorageFile sampleFile =
await KnownFolders.PicturesLibrary.CreateFileAsync(sampleFileName,
CreationCollisionOption.ReplaceExisting);
// Write the current timestamp to the sample file.
string sampleFileContents = DateTime.Now.ToString();
await FileIO.WriteTextAsync(sampleFile, sampleFileContents);

Reading text from a file

  1. To read the contents of a file, you must first acquire a StorageFile object to pass to one of the FileIO functions for reading data. In the companion sample, this is done by calling the StorageFolder.GetFileAsync function.
  2. Once you have a StorageFile object, you can read text from its underlying file via one of the overloaded FileIO.ReadTextAsync functions.
This code example reads the contents from a sample file.
// Get StorageFile object for sample file.
StorageFile sampleFile =
await KnownFolders.PicturesLibrary.GetFileAsync(sampleFileName);
if (sampleFile != null)
{
// Read and display sample file's contents.
string fileContent = await FileIO.ReadTextAsync(sampleFile);
}

This screen shot shows an example of running the sample and writing to the sample file.

Find it in the sample: The sample includes a page titled File Access Basics, which includes the samples presented in this section. All of the relevant Visual C# and XAML code is centralized to the FileAccessBasicsPage.xaml.cs (OnWriteTextToFileClick and OnReadTextFromFileClick methods) and FileAccessBasicsPage.xaml files, respectively.

 

Working with file and folder pickers

Quickstart: Accessing files with file pickers

Pickers—both file pickers and folder pickers—are used to display a list of files or folders from which users can select one or more items for further processing. Pickers can be configured programmatically to search for files and folders that match a specified filter (such as files with specific extensions), start at a particular folder, display a specific view mode (list or thumbnail), and much more.

The following procedures illustrate how to configure a file or folder picker for various tasks:

Configuring a single-file selection file picker

  1. Instantiate a FileOpenPicker object.
  2. Set the FileOpenPicker object's ViewMode, SuggestedStartLocation, and FileTypeFilter properties as needed.
  3. Call the FileOpenPicker.PickSingleFileAsync method. When the FileOpenPicker.PickSingleFileAsync method is complete, the app has read/write access to the selected file.
This code example instantiates and displays a file picker for single-file selection.
public static FileOpenPicker
CreateFileOpenPicker(this PickerLocationId location,
string[] filters)
{
FileOpenPicker picker = new FileOpenPicker()
{
SuggestedStartLocation = location,
ViewMode = PickerViewMode.Thumbnail
};
foreach (string filter in filters)
{
picker.FileTypeFilter.Add(filter);
}
return picker;
}
...
// Instantiate/configure picker object.
FileOpenPicker openPicker =
PickerLocationId.PicturesLibrary.CreateFileOpenPicker(new string[]
{ ".jpg", ".jpeg", ".png" });
// Display picker and allow user to select a single file.
StorageFile file = await openPicker.PickSingleFileAsync();
// If the user selected a file ...
if (file != null)
{
// ... process file as needed.
}
else
{
// User canceled the operation.
}

Configuring a multi-file select file picker

  1. Instantiate a FileOpenPicker object.
  2. Set the FileOpenPicker object's ViewMode, SuggestedStartLocation, and FileTypeFilter properties as needed.
  3. Call the FileOpenPicker.PickMultipleFilesAsync method. When the FileOpenPicker.PickMultipleFilesAsync method is complete, the app has read/write access to the selected files. The files selected are represented by an IReadOnlyList collection. This collection can be iterated using a foreach loop.
This code example instantiates and displays a file picker for multiple-file selection.
public static FileOpenPicker
CreateFileOpenPicker(this PickerLocationId location,
string[] filters)
{
FileOpenPicker picker = new FileOpenPicker()
{
SuggestedStartLocation = location,
ViewMode = PickerViewMode.Thumbnail
};
foreach (string filter in filters)
{
picker.FileTypeFilter.Add(filter);
}
return picker;
}
...
// Instantiate/configure picker object.
FileOpenPicker openPicker =
PickerLocationId.PicturesLibrary.CreateFileOpenPicker(new string[]
{ ".jpg", ".jpeg", ".png" });
// Display picker and allow user to select multiple files.
IReadOnlyList<StorageFile> files = await openPicker.PickMultipleFilesAsync();
// For each selected file ...
foreach (StorageFile file in files)
{
// ... process file as needed.
}

Configuring a folder picker

  1. Instantiate a FolderPicker object.
  2. Set the FolderPicker object's ViewMode, SuggestedStartLocation, and FolderPicker.FileTypeFilter properties as needed.
  3. Call theFolderPicker.PickSingleFolderAsync method, which returns a StorageFolder object representing the selected folder. When the FolderPicker.PickSingleFolderAsync method is complete, the app has read/write access to all contents in the selected folder, including subfolders.
This code example instantiates and displays a folder picker.
public static FolderPicker
CreateFolderOpenPicker(this PickerLocationId location,
string[] filters)
{
FolderPicker picker = new FolderPicker()
{
SuggestedStartLocation = location,
ViewMode = PickerViewMode.Thumbnail
};
foreach (string filter in filters)
{
picker.FileTypeFilter.Add(filter);
}
return picker;
}
...
// Instantiate/configure picker object.
FolderPicker folderPicker =
PickerLocationId.Desktop.CreateFolderOpenPicker(new string[]
{ ".jpg", ".jpeg", ".png" });
// Display picker and allow user to select a folder.
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
// If the user selected a folder ...
if (folder != null)
{
// ... process file as needed.
}
else
{
// User canceled operation.
}

This screen shot shows the results of running the sample and selecting two files (sample1.png and sample2.png).

Find it in the sample: The sample includes a page titled File Picker, which demonstrates the tasks outlined in this section (for both file and folder pickers). The Visual C# code and XAML for this sample is located in the FilePickerPage.xaml.cs and FilePickerPage.xaml files, respectively, along with helper methods in the FileHelper.cs file.

 

Working with OneDrive files

Quickstart: Determining availability of OneDrive files

Windows 8.1 enables users to mark OneDrive files as online only. When the user is disconnected from OneDrive, these files are not available. To help you programmatically determine the availability of a file, there's a new property called StorageFile.IsAvailable.

These steps show you how to determine the availability of files using the StorageFile.IsAvailable property.

  1. Acquire a StorageFolder object for the location you want. For example, you can do this by referencing one of the static KnownFolders properties - such as KnowFolders.PicturesLibrary.
  2. Call the returned StorageFolder object's StorageFolder.CreateFileQuery method with no parameters, indicating that you want all folders and files returned.
  3. When the StorageFolder.CreateFileQuery call returns, you'll have a StorageFileQueryResult object. Call its GetFilesAsync method.
  4. The StorageFileQueryResult.GetFilesAsync method returns an IReadOnlyList collection of StorageFile objects that can be iterated with a foreach loop.
  5. Reference the StorageFile.IsAvailable boolean property.
This code example enumerates all files in Pictures, displaying each file's name, provider name, and availability.
// Generic extension method that returns all files for the
// specified KnownFolders location.
public static async Task<IReadOnlyList<StorageFile>>
GetLibraryFilesAsync(this StorageFolder folder)
{
var query = folder.CreateFileQuery();
return await query.GetFilesAsync();
}
...
// Display file list with storage provider and availability.
var files = await KnownFolders.PicturesLibrary.GetLibraryFilesAsync();
foreach (StorageFile file in files)
{
// Reference the file.IsAvailable property as needed.
}

Find it in the sample: The sample includes a page titled OneDrive Files, which has a button that enumerates all of the files in the local machine's Pictures library. Each file name is displayed, along with its provider (This PC or OneDrive) and whether it is available. The Visual C# code and XAML for this sample are in the OneDriveFilesPage.xaml.cs and OneDriveFilesPage.xaml files, respectively, along with helper methods in the FileHelper.cs file.

 

Finish up

Using the Windows App Certification Kit

Recommended. Running the Windows App Certification Kit helps you make sure that your app fulfills Windows Store requirements. We recommend you run it whenever you add major functionality to your app.

You’re finished! Now that you’ve explored different file-handling capabilities for your app, you're ready to create an app like the File handling, start to finish companion sample.

 

Want to know more?

Quickstart: Using the await operator for asynchronous programming

Learn more about asynchronous programming in C#.

Quickstart: Accessing files programmatically

Learn more about enumerating files.

Quickstart: Getting a file's properties

Learn more about retrieving a file's top-level, basic, and extended properties.

Quickstart: Reading and writing a file

Learn more about reading and writing files.

Quickstart: Determining availability of OneDrive files

Learn more about determining whether a file is available.