Procedimiento Convertir flujos de .NET Framework en flujos de Windows Runtime y viceversa (solo Windows)How to: Convert between .NET Framework and Windows Runtime streams (Windows only)

.NET Framework para aplicaciones para UWP es un subconjunto de la plataforma .NET Framework completa.The .NET Framework for UWP apps is a subset of the full .NET Framework. Debido a los requisitos de seguridad y de otro tipo de las aplicaciones para UWP, no se puede usar el conjunto completo de API de .NET Framework para abrir y leer archivos.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 obtener más información, consulte Información general de .NET para aplicaciones para UWP.For more information, see .NET for UWP apps overview. Sin embargo, puede que desee usar las API de .NET Framework para otras operaciones de manipulación de secuencias.However, you may want to use .NET Framework APIs for other stream manipulation operations. Para manipular estos flujos, puede convertir entre un tipo de flujo de .NET Framework como MemoryStream o FileStream, y un flujo de Windows Runtime como IInputStream, IOutputStream o 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.

La clase System.IO.WindowsRuntimeStreamExtensions contiene métodos que facilitan estas conversiones.The System.IO.WindowsRuntimeStreamExtensions class contains methods that make these conversions easy. Sin embargo, las diferencias subyacentes entre los flujos de .NET Framework y de Windows Runtime afectan a los resultados del uso de estos métodos, tal como se describe en las secciones siguientes:However, underlying differences between .NET Framework and Windows Runtime streams affect the results of using these methods, as described in the following sections:

Convertir un flujo de Windows Runtime en un flujo de .NET FrameworkConvert from a Windows Runtime to a .NET Framework stream

Para convertir un flujo de Windows Runtime en un flujo de .NET Framework, utilice uno de métodos de System.IO.WindowsRuntimeStreamExtensions siguientes:To convert from a Windows Runtime stream to a .NET Framework stream, use one of the following System.IO.WindowsRuntimeStreamExtensions methods:

Windows Runtime ofrece tipos de flujo que admiten solo lectura, solo escritura o lectura y escritura.The Windows Runtime offers stream types that support reading only, writing only, or reading and writing. Estas funcionalidades se mantienen al convertir un flujo de Windows Runtime en un flujo de .NET Framework.These capabilities are maintained when you convert a Windows Runtime stream to a .NET Framework stream. Además, en caso de convertir una secuencia de Windows en tiempo de ejecución en secuencia de .NET Framework y de nuevo al revés, obtendrá de nuevo la instancia original de Windows en tiempo de ejecución.Furthermore, if you convert a Windows Runtime stream to a .NET Framework stream and back, you get the original Windows Runtime instance back.

Se recomienda usar el método de conversión correspondiente a las funcionalidades del flujo de Windows Runtime que desea convertir.It’s best practice to use the conversion method that matches the capabilities of the Windows Runtime stream you want to convert. Pero como IRandomAccessStream es de lectura y escritura (implementa tanto IOutputStream como IInputStream), los métodos de conversión mantienen las funcionalidades del flujo 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 ejemplo, el uso de WindowsRuntimeStreamExtensions.AsStreamForRead para convertir un objeto IRandomAccessStream, no limita el flujo de .NET Framework convertido a que sea legible.For example, using WindowsRuntimeStreamExtensions.AsStreamForRead to convert an IRandomAccessStream doesn't limit the converted .NET Framework stream to being readable. También es de escritura.It's also writable.

Ejemplo: Convertir un flujo de acceso aleatorio de Windows Runtime en un flujo de .NET FrameworkExample: Convert Windows Runtime random-access to .NET Framework stream

Para convertir un flujo de acceso aleatorio de Windows Runtime en un flujo de .NET Framework, use el método WindowsRuntimeStreamExtensions.AsStream.To convert from a Windows Runtime random-access stream to a .NET Framework stream, use the WindowsRuntimeStreamExtensions.AsStream method.

En el ejemplo de código siguiente, se le pide que seleccione un archivo, lo abra con las API de Windows Runtime y, a continuación, lo convierta en un flujo de .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. Lee el flujo y lo genera en un bloque de texto.It reads the stream and outputs it to a text block. Normalmente se manipularía el flujo con las API de .NET Framework antes de generar los resultados.You would typically manipulate the stream with .NET Framework APIs before outputting the results.

Para ejecutar este ejemplo, cree una aplicación XAML para UWP que contenga un bloque de texto denominado TextBlock1 y un botón denominado Button1.To run this example, create a UWP XAML app that contains a text block named TextBlock1 and a button named Button1. Asocie el evento Click del botón al método button1_Click mostrado en el ejemplo.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

Convertir un flujo de .NET Framework en un flujo de Windows RuntimeConvert from a .NET Framework to a Windows Runtime stream

Para convertir un flujo de .NET Framework en un flujo de Windows Runtime, utilice uno de métodos de System.IO.WindowsRuntimeStreamExtensions siguientes:To convert from a .NET Framework stream to a Windows Runtime stream, use one of the following System.IO.WindowsRuntimeStreamExtensions methods:

Al convertir un flujo de .NET Framework en un flujo de Windows Runtime, las funcionalidades del flujo convertido dependen del flujo 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 ejemplo, si el flujo original admite lectura y escritura y se llama a WindowsRuntimeStreamExtensions.AsInputStream para convertir el flujo, el tipo devuelto es 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 y IOutputStream, y admite la lectura y la escritura.IRandomAccessStream implements IInputStream and IOutputStream, and supports reading and writing.

Los flujos de .NET Framework no admiten la clonación, incluso después de la conversión..NET Framework streams don't support cloning, even after conversion. Si se convierte un flujo de .NET Framework en un flujo de Windows Runtime y se llama a GetInputStreamAt o GetOutputStreamAt, que a su vez llaman a CloneStream, o si llama a CloneStream directamente, se producirá una excepción.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.

Ejemplo: Convertir un flujo de .NET Framework en un flujo de acceso aleatorio de Windows RuntimeExample: Convert .NET Framework to Windows Runtime random-access stream

Para convertir una secuencia de .NET Framework en una secuencia de acceso aleatorio de Windows Runtime, use el método AsRandomAccessStream, como se muestra en el ejemplo siguiente: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

Asegúrese de que el flujo de .NET Framework que está usando admite las búsquedas, o cópielo en un flujo que las admita.Make sure that the .NET Framework stream you are using supports seeking, or copy it to a stream that does. Puede usar la propiedad Stream.CanSeek para averiguarlo.You can use the Stream.CanSeek property to determine this.

Para ejecutar este ejemplo, cree una aplicación XAML para UWP destinada a .NET Framework 4.5.1 y que contenga un bloque de texto denominado TextBlock2 y un botón denominado 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. Asocie el evento Click del botón al método button2_Click mostrado en el ejemplo.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

Vea tambiénSee also