Quickstart: Reading and writing files (XAML)
[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]
Read and write a file using a StorageFile object.
Prerequisites
Understand async programming for Windows Runtime apps using C++, C#, or Visual Basic
You can learn how to write asynchronous apps in Quickstart: Calling asynchronous APIs in C# or Visual Basic.
Know how to get the file that you want to read from, write to, or both
You can learn how to get a file by using a file picker in Quickstart: Accessing files with file pickers.
Creating a file
This section's code snippets illustrate how create a file (replacing it if it already exists) in the app's local folder. A StorageFile object named sampleFile
is used in this topic's subsequent code snippets to reference the opened file.
// Create sample file; replace if exists.
StorageFolder folder =
Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile sampleFile =
await folder.CreateFileAsync("sample.txt", CreationCollisionOption.ReplaceExisting);
' Create sample file; replace if exists.
Dim folder As StorageFolder = Windows.Storage.ApplicationData.Current.LocalFolder
Dim sampleFile As StorageFile = Await folder.CreateFileAsync("sample.txt", CreationCollisionOption.ReplaceExisting)
Note Before you can create files in libraries, you must declare the capability in your app manifest. Learn more about file access and capabilities in File access and permissions and App capability declarations.
Note Remember to put the async keyword on the method declaration of any method in which you use the await operator. For more information, see Quickstart: Calling asynchronous APIs in C# or Visual Basic.
Writing to a file
These steps show you how to write to a file if you have a writable file and a StorageFile that represents it.
Writing text to a file
Write text to your file by calling the WriteTextAsync methods of the FileIO class.
The File access sample shows you how to call WriteTextAsync(file, contents) to write some arbitrary text to its sampleFile
like this:
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, "Swift as a shadow");
Await Windows.Storage.FileIO.WriteTextAsync(sampleFile, "Swift as a shadow")
Note Remember to put the async keyword on the method declaration of any method in which you use the await operator. For more information, see Quickstart: Calling asynchronous APIs in C# or Visual Basic.
Writing bytes to a file by using a buffer
Get a buffer of the bytes that you want to write to your file.
For example, the File access sample calls ConvertStringToBinary to get a buffer of bytes based on an arbitrary string, like this:
var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary( "What fools these mortals be", Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
Dim buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary( "What fools these mortals be", Windows.Security.Cryptography.BinaryStringEncoding.Utf8)
Write the bytes from your buffer to your file by calling the WriteBufferAsync method of the FileIO class.
The File access sample shows you how to use WriteBufferAsync to write bytes from a buffer to its
sampleFile
, like this:await Windows.Storage.FileIO.WriteBufferAsync(sampleFile, buffer);
Await Windows.Storage.FileIO.WriteBufferAsync(sampleFile, buffer)
Note Remember to put the async keyword on the method declaration of any method in which you use the await operator. For more information, see Quickstart: Calling asynchronous APIs in C# or Visual Basic.
Writing text to a file by using a stream
Open the file by calling the StorageFile.OpenAsync method. It returns a stream of the file's content when the open operation completes.
The File access sample shows you how to open a stream for a file (
sampleFile
) by calling the StorageFile.OpenAsync method, like this:var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
Dim stream = Await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)
Note Remember to put the async keyword on the method declaration of any method in which you use the await operator. For more information, see Quickstart: Calling asynchronous APIs in C# or Visual Basic.
Get an output stream by calling the GetOutputStreamAt method from the
stream
. Put this in a using statement to manage the output stream's lifetime.using (var outputStream = stream.GetOutputStreamAt(0)) { // Add code to use the stream to write to your file }
Using outputStream = stream.GetOutputStreamAt(0) ' Add code to use the stream to write to your file End Using
Use the following steps to add code within the using statement to write to the output stream.
Write text to the
outputStream
by creating a new DataWriter object and calling the DataWriter.WriteString method.DataWriter dataWriter = new DataWriter(outputStream); dataWriter.WriteString("The DataWriter provides method to write to various types, such as DataTimeOffset.");
Dim dataWriter As New DataWriter(outputStream) dataWriter.WriteString("The DataWriter provides method to write to various types, such as DataTimeOffset.")
Save the text to your file and close the stream by calling the
writer
.StoreAsync andoutputStream
.FlushAsync methods.The File access sample shows you how to save the text to your file and close the stream, like this:
await dataWriter.StoreAsync(); await outputStream.FlushAsync();
Await dataWriter.StoreAsync() Await outputStream.FlushAsync()
Note Remember to put the async keyword on the method declaration of any method in which you use the await operator. For more information, see Quickstart: Calling asynchronous APIs in C# or Visual Basic.
You can download the File access sample to see these code examples in context inside methods.
Reading from a file
These steps show you how to read from a file if you have a readable file and a StorageFile that represents it. You can get a StorageFile that represents readable files by the StorageFolder.GetFileAsync method.
StorageFolder storageFolder =
Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile sampleFile =
await storageFolder.GetFileAsync("sample.txt");
Dim storageFolder As StorageFolder = Windows.Storage.ApplicationData.Current.LocalFolder
Dim sampleFile As StorageFile = Await storageFolder.GetFileAsync("sample.txt")
Note Remember to put the async keyword on the method declaration of any method in which you use the await operator. For more information, see Quickstart: Calling asynchronous APIs in C# or Visual Basic.
Reading text from a file
Read text from your file by calling the ReadTextAsync methods of the FileIO class.
The File access sample shows you how to read text from a file by calling ReadTextAsync(file) to read from its sampleFile
, like this:
string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);
Dim text As String = Await Windows.Storage.FileIO.ReadTextAsync(sampleFile)
Note Remember to put the async keyword on the method declaration of any method in which you use the await operator. For more information, see Quickstart: Calling asynchronous APIs in C# or Visual Basic.
Reading bytes from a file by using a buffer
Read bytes from your buffer to your file by calling the ReadBufferAsync method of the FileIO class.
The File access sample shows you how to read bytes to a buffer from a file by calling ReadBufferAsync, like this:
var buffer = await Windows.Storage.FileIO.ReadBufferAsync(sampleFile);
Dim buffer = Await Windows.Storage.FileIO.ReadBufferAsync(sampleFile)
Note Remember to put the async keyword on the method declaration of any method in which you use the await operator. For more information, see Quickstart: Calling asynchronous APIs in C# or Visual Basic.
Then use a DataReader object to read the length of the buffer
and read the contents of the buffer.
DataReader dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer);
string text = dataReader.ReadString(buffer.Length);
Dim dataReader As DataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer)
Dim text As String = dataReader.ReadString(buffer.Length)
Reading text from a file by using a stream
Open a stream for your file by calling the StorageFile.OpenAsync method. It returns a stream of the file's content when the open operation completes.
The File access sample shows you how to open a stream to a file (
sampleFile
) by calling the StorageFile.OpenAsync method like this:var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
Dim stream = Await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)
Note Remember to put the async keyword on the method declaration of any method in which you use the await operator. For more information, see Quickstart: Calling asynchronous APIs in C# or Visual Basic.
Get the size of the stream to use later.
var size = stream.Size;
Dim size = stream.Size
Get an input stream by calling the GetInputStreamAt method of the
stream
. Put this in a using statement to manage the input stream's lifetime. Specify 0 when you call GetInputStreamAt to set the position of theinputStream
at the beginning of the stream, as shown in the sample.using (var inputStream = stream.GetInputStreamAt(0)) { // Add code to use the stream to read your file }
Using inputStream = stream.GetInputStreamAt(0) ' Add code to use the stream to read your file End Using
Use the following steps to add code within the using statement to read the input stream.
Get a DataReader object by passing the
inputStream
to the constructor.The File access sample shows how to create a DataReader like this:
DataReader dataReader = new DataReader(inputStream);
Dim dataReader As New DataReader(inputStream)
Read the text by calling the DataReader.LoadAsync and DataReader.ReadString methods.
The File access sample shows you how to read text and make sure the
stream
isn't empty, like this:uint numBytesLoaded = await dataReader.LoadAsync((uint)size); string text = dataReader.ReadString(numBytesLoaded);
Dim numBytesLoaded As UInteger = Await dataReader.LoadAsync(CUInt(size)) Dim text As String = dataReader.ReadString(numBytesLoaded)
Note Remember to put the async keyword on the method declaration of any method in which you use the await operator. For more information, see Quickstart: Calling asynchronous APIs in C# or Visual Basic.
You can download the File access sample to see these code examples in context inside methods.
Summary and next steps
You should now understand how to read and write from a file if you have a StorageFile that represents the file.
To learn about working with image files, see Quickstart: Image and ImageBrush, Quickstart: Imaging, and the XAML image sample.
Related topics
Quickstart: Accessing files with file pickers
Guidelines and checklist for file pickers
Reference
Windows.Storage.StorageFile class