Condividi tramite


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

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

  1. 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)
    
  2. 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

  1. 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.

     

  2. 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.

    1. 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.")
      
    2. Save the text to your file and close the stream by calling the writer.StoreAsync and outputStream.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

  1. 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.

     

  2. Get the size of the stream to use later.

    var size = stream.Size;
    
    Dim size = stream.Size
    
  3. 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 the inputStream 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.

    1. 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)
      
    2. 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.

Accessing data and files

Quickstart: Accessing files with file pickers

Guidelines and checklist for file pickers

File access and permissions

File access sample

XAML image sample

Reference

Windows.Storage.StorageFile class

Windows.Storage.Streams.DataReader class

Windows.Storage.Streams.DataWriter class