Como: Converter entre fluxos de execução .NET e Windows Runtime (somente windows)How to: Convert between .NET Framework and Windows Runtime streams (Windows only)

O .NET Framework para aplicativos UWP é um subconjunto do .NET Framework completo.The .NET Framework for UWP apps is a subset of the full .NET Framework. Devido a requisitos de segurança e outros requisitos dos aplicativos UWP, não é possível usar o conjunto completo de APIs do .NET Framework para abrir e ler arquivos.Because of security and other requirements for UWP apps, you can't use the full set of .NET Framework APIs to open and read files. Para obter mais informações, confira Visão geral do .NET para aplicativos UWP.For more information, see .NET for UWP apps overview. No entanto, talvez você queira usar APIs do .NET Framework para outras operações de manipulação de fluxos.However, you may want to use .NET Framework APIs for other stream manipulation operations. Para manipular esses fluxos, faça a conversão entre um tipo de fluxo do .NET Framework, como MemoryStream ou FileStream, e um fluxo do Windows Runtime, como IInputStream, IOutputStream ou IRandomAccessStream.To manipulate these streams, you can convert between a .NET Framework stream type such as MemoryStream or FileStream, and a Windows Runtime stream such as IInputStream, IOutputStream, or IRandomAccessStream.

A classe System.IO.WindowsRuntimeStreamExtensions contém métodos que tornam fáceis essas conversões.The System.IO.WindowsRuntimeStreamExtensions class contains methods that make these conversions easy. No entanto, as diferenças subjacentes entre os fluxos do .NET Framework e os fluxos do Windows Runtime afetam os resultados do uso desses métodos, conforme descrito nas seguintes seções:However, underlying differences between .NET Framework and Windows Runtime streams affect the results of using these methods, as described in the following sections:

Converter um fluxo do Windows Runtime em um fluxo do .NET FrameworkConvert from a Windows Runtime to a .NET Framework stream

Para converter de um fluxo do Windows Runtime para um fluxo do .NET Framework, use um dos seguintes métodos System.IO.WindowsRuntimeStreamExtensions:To convert from a Windows Runtime stream to a .NET Framework stream, use one of the following System.IO.WindowsRuntimeStreamExtensions methods:

O Windows Runtime oferece tipos de fluxo que dão suporte ao acesso somente leitura, somente gravação ou de leitura e gravação.The Windows Runtime offers stream types that support reading only, writing only, or reading and writing. Essas funcionalidades são mantidas quando você converte um fluxo do Windows Runtime em um fluxo do .NET Framework.These capabilities are maintained when you convert a Windows Runtime stream to a .NET Framework stream. Além disso, se você converter um fluxo do Windows Runtime para um fluxo do .NET Framework e convertê-lo de volta, você obterá instância original do Windows Runtime outra vez.Furthermore, if you convert a Windows Runtime stream to a .NET Framework stream and back, you get the original Windows Runtime instance back.

É uma melhor prática usar o método de conversão correspondente às funcionalidades do fluxo do Windows Runtime que você deseja converter.It’s best practice to use the conversion method that matches the capabilities of the Windows Runtime stream you want to convert. No entanto, como IRandomAccessStream é legível e gravável (implementa IOutputStream e IInputStream), os métodos de conversão mantêm as funcionalidades do fluxo original.However, since IRandomAccessStream is readable and writeable (it implements both IOutputStream and IInputStream), the conversion methods maintain the capabilities of the original stream. Por exemplo, o uso de WindowsRuntimeStreamExtensions.AsStreamForRead para converter um IRandomAccessStream não limita o fluxo convertido do .NET Framework a ser legível.For example, using WindowsRuntimeStreamExtensions.AsStreamForRead to convert an IRandomAccessStream doesn't limit the converted .NET Framework stream to being readable. Ele também é gravável.It's also writable.

Exemplo: Converter o acesso aleatório do Windows Runtime ao fluxo .NET FrameworkExample: Convert Windows Runtime random-access to .NET Framework stream

Para converter de um fluxo de acesso aleatório do Windows Runtime para um fluxo do .NET Framework, use o método WindowsRuntimeStreamExtensions.AsStream.To convert from a Windows Runtime random-access stream to a .NET Framework stream, use the WindowsRuntimeStreamExtensions.AsStream method.

O exemplo de código a seguir solicita que você selecione um arquivo, abre-o com as APIs do Windows Runtime e, em seguida, converte-o em um fluxo do .NET Framework.The following code example prompts you to select a file, opens it with Windows Runtime APIs, and then converts it to a .NET Framework stream. Ele lê o fluxo e os coloca em um bloco de texto.It reads the stream and outputs it to a text block. Você normalmente manipulará o fluxo com as APIs do .NET Framework antes de produzir os resultados.You would typically manipulate the stream with .NET Framework APIs before outputting the results.

Para executar esse exemplo, crie um aplicativo UWP XAML que contém um bloco de texto chamado TextBlock1 e um botão chamado Button1.To run this example, create a UWP XAML app that contains a text block named TextBlock1 and a button named Button1. Associe o evento de clique no botão ao método button1_Click mostrado no exemplo.Associate the button click event with the button1_Click method shown in the example.

using System;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage;
using System.Net.Http;
using Windows.Storage.Pickers;

private async void button1_Click(object sender, RoutedEventArgs e)
{
    // Create a file picker.
    FileOpenPicker picker = new FileOpenPicker();

    // Set properties on the file picker such as start location and the type
    // of files to display.
    picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
    picker.ViewMode = PickerViewMode.List;
    picker.FileTypeFilter.Add(".txt");

    // Show picker enabling user to pick one file.
    StorageFile result = await picker.PickSingleFileAsync();

    if (result != null)
    {
        try
        {
            // Retrieve the stream. This method returns a IRandomAccessStreamWithContentType.
            var stream = await result.OpenReadAsync();

            // Convert the stream to a .NET stream using AsStream, pass to a 
            // StreamReader and read the stream.
            using (StreamReader sr = new StreamReader(stream.AsStream()))
            {
                TextBlock1.Text = sr.ReadToEnd();
            }
        }
        catch (Exception ex)
        {
            TextBlock1.Text = "Error occurred reading the file. " + ex.Message;
        }
    }
    else
    {
        TextBlock1.Text = "User did not pick a file";
    }
}
Imports System.IO
Imports System.Runtime.InteropServices.WindowsRuntime
Imports Windows.UI.Xaml
Imports Windows.UI.Xaml.Controls
Imports Windows.UI.Xaml.Media.Imaging
Imports Windows.Storage
Imports System.Net.Http
Imports Windows.Storage.Pickers

Private Async Sub button1_Click(sender As Object, e As RoutedEventArgs)
    ' Create a file picker.
    Dim picker As New FileOpenPicker()

    ' Set properties on the file picker such as start location and the type of files to display.
    picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary
    picker.ViewMode = PickerViewMode.List
    picker.FileTypeFilter.Add(".txt")

    ' Show picker that enable user to pick one file.
    Dim result As StorageFile = Await picker.PickSingleFileAsync()

    If result IsNot Nothing Then
        Try
            ' Retrieve the stream. This method returns a IRandomAccessStreamWithContentType.
            Dim stream = Await result.OpenReadAsync()

            ' Convert the stream to a .NET stream using AsStreamForRead, pass to a 
            ' StreamReader and read the stream.
            Using sr As New StreamReader(stream.AsStream())
                TextBlock1.Text = sr.ReadToEnd()
            End Using
        Catch ex As Exception
            TextBlock1.Text = "Error occurred reading the file. " + ex.Message
        End Try
    Else
        TextBlock1.Text = "User did not pick a file"
    End If
End Sub

Converter um fluxo do .NET Framework em um fluxo do Windows RuntimeConvert from a .NET Framework to a Windows Runtime stream

Para converter de um fluxo do .NET Framework para um fluxo do Windows Runtime, use um dos seguintes métodos System.IO.WindowsRuntimeStreamExtensions:To convert from a .NET Framework stream to a Windows Runtime stream, use one of the following System.IO.WindowsRuntimeStreamExtensions methods:

Quando você converte um fluxo do .NET Framework em um fluxo do Windows Runtime, as funcionalidades do fluxo convertido dependem do fluxo original.When you convert a .NET Framework stream to a Windows Runtime stream, the capabilities of the converted stream depend on the original stream. Por exemplo, se o fluxo original tiver suporte à leitura e à gravação e você chamar WindowsRuntimeStreamExtensions.AsInputStream para converter o fluxo, o tipo retornado será um IRandomAccessStream.For example, if the original stream supports both reading and writing, and you call WindowsRuntimeStreamExtensions.AsInputStream to convert the stream, the returned type is an IRandomAccessStream. IRandomAccessStream implementa IInputStream e IOutputStream e dá suporte à leitura e à gravação.IRandomAccessStream implements IInputStream and IOutputStream, and supports reading and writing.

Os fluxos do .NET Framework não dão suporte à clonagem, mesmo após a conversão..NET Framework streams don't support cloning, even after conversion. Se você converte um fluxo do .NET Framework em um fluxo do Windows Runtime e chama GetInputStreamAt ou GetOutputStreamAt, que chama CloneStream, ou se você chama CloneStream diretamente, ocorre uma exceção.If you convert a .NET Framework stream to a Windows Runtime stream and call GetInputStreamAt or GetOutputStreamAt, which call CloneStream, or if you call CloneStream directly, an exception occurs.

Exemplo: Converter o .NET Framework para o fluxo de acesso aleatório do Windows RuntimeExample: Convert .NET Framework to Windows Runtime random-access stream

Para converter um fluxo do .NET Framework em um fluxo de acesso aleatório do Windows Runtime, use o método AsRandomAccessStream, conforme mostrado no seguinte exemplo:To convert from a .NET Framework stream to a Windows Runtime random-access stream, use the AsRandomAccessStream method, as shown in the following example:

Importante

Verifique se o fluxo do .NET Framework que você está usando dá suporte à busca ou copie-o para um fluxo que dê esse suporte.Make sure that the .NET Framework stream you are using supports seeking, or copy it to a stream that does. Você pode usar a propriedade Stream.CanSeek para determinar isso.You can use the Stream.CanSeek property to determine this.

Para executar esse exemplo, crie um aplicativo UWP XAML direcionado ao .NET Framework 4.5.1 e que contém um bloco de texto chamado TextBlock2 e um botão chamado Button2.To run this example, create a UWP XAML app that targets the .NET Framework 4.5.1 and contains a text block named TextBlock2 and a button named Button2. Associe o evento de clique no botão ao método button2_Click mostrado no exemplo.Associate the button click event with the button2_Click method shown in the example.

using System;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage;
using System.Net.Http;
using Windows.Storage.Pickers;

private async void button2_Click(object sender, RoutedEventArgs e)
{
    // Create an HttpClient and access an image as a stream.
    var client = new HttpClient();
    Stream stream = await client.GetStreamAsync("https://docs.microsoft.com/en-us/dotnet/images/hub/featured-1.png");
    // Create a .NET memory stream.
    var memStream = new MemoryStream();
    // Convert the stream to the memory stream, because a memory stream supports seeking.
    await stream.CopyToAsync(memStream);
    // Set the start position.
    memStream.Position = 0;
    // Create a new bitmap image.
    var bitmap = new BitmapImage();
    // Set the bitmap source to the stream, which is converted to a IRandomAccessStream.
    bitmap.SetSource(memStream.AsRandomAccessStream());
    // Set the image control source to the bitmap.
    image1.Source = bitmap;
}
Imports System.IO
Imports System.Runtime.InteropServices.WindowsRuntime
Imports Windows.UI.Xaml
Imports Windows.UI.Xaml.Controls
Imports Windows.UI.Xaml.Media.Imaging
Imports Windows.Storage
Imports System.Net.Http
Imports Windows.Storage.Pickers

Private Async Sub button2_Click(sender As Object, e As RoutedEventArgs)


    ' Create an HttpClient and access an image as a stream.
    Dim client = New HttpClient()
    Dim stream As Stream = Await client.GetStreamAsync("https://docs.microsoft.com/en-us/dotnet/images/hub/featured-1.png")
    ' Create a .NET memory stream.
    Dim memStream = New MemoryStream()

    ' Convert the stream to the memory stream, because a memory stream supports seeking.
    Await stream.CopyToAsync(memStream)

    ' Set the start position.
    memStream.Position = 0

    ' Create a new bitmap image.
    Dim bitmap = New BitmapImage()

    ' Set the bitmap source to the stream, which is converted to a IRandomAccessStream.
    bitmap.SetSource(memStream.AsRandomAccessStream())

    ' Set the image control source to the bitmap.
    image1.Source = bitmap
End Sub

Confira tambémSee also