Comment: Convertir entre .NET Framework et Windows Runtime streams (Windows uniquement)How to: Convert between .NET Framework and Windows Runtime streams (Windows only)

Le .NET Framework pour les applications UWP est un sous-ensemble du .NET Framework complet.The .NET Framework for UWP apps is a subset of the full .NET Framework. En raison de la sécurité et d’autres spécifications des applications UWP, vous ne pouvez pas utiliser l’ensemble d’API .NET Framework pour ouvrir et lire des fichiers.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. Pour plus d’informations, consultez Vue d’ensemble de .NET pour les applications UWP.For more information, see .NET for UWP apps overview. Toutefois, vous pouvez utiliser des API .NET Framework pour les autres opérations de manipulation des flux.However, you may want to use .NET Framework APIs for other stream manipulation operations. Pour manipuler ces flux, vous pouvez convertir un flux .NET Framework, tel que MemoryStream ou FileStream, en flux Windows Runtime tel que 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.

La classe System.IO.WindowsRuntimeStreamExtensions contient des méthodes qui rendent ces conversions plus faciles.The System.IO.WindowsRuntimeStreamExtensions class contains methods that make these conversions easy. Toutefois, il existe des différences sous-jacentes entre les flux .NET Framework et Windows Runtime qui affecteront les résultats obtenus lors de l’utilisation de ces méthodes, comme l’expliquent les sections suivantes :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 flux Windows Runtime en flux .NET FrameworkConvert from a Windows Runtime to a .NET Framework stream

Pour convertir un flux Windows Runtime en un flux .NET Framework, utilisez l’une des méthodes System.IO.WindowsRuntimeStreamExtensions suivantes :To convert from a Windows Runtime stream to a .NET Framework stream, use one of the following System.IO.WindowsRuntimeStreamExtensions methods:

Windows Runtime propose des types de flux qui prennent en charge la lecture seule, l’écriture seule et la lecture-écriture.The Windows Runtime offers stream types that support reading only, writing only, or reading and writing. Ces fonctionnalités sont conservées lorsque vous convertissez un flux Windows Runtime en flux .NET Framework.These capabilities are maintained when you convert a Windows Runtime stream to a .NET Framework stream. En outre, si vous convertissez un flux Windows Runtime en un flux .NET Framework et inversement, vous obtenez l'instance du Windows Runtime en retour.Furthermore, if you convert a Windows Runtime stream to a .NET Framework stream and back, you get the original Windows Runtime instance back.

Il est recommandé d’utiliser la méthode de conversion qui correspond aux fonctionnalités du flux Windows Runtime que vous souhaitez convertir.It’s best practice to use the conversion method that matches the capabilities of the Windows Runtime stream you want to convert. Toutefois, comme IRandomAccessStream est accessible en lecture et en écriture (il implémente IOutputStream et IInputStream), les méthodes de conversion conservent les fonctionnalités du flux d’origine.However, since IRandomAccessStream is readable and writeable (it implements both IOutputStream and IInputStream), the conversion methods maintain the capabilities of the original stream. Par exemple, l’utilisation de WindowsRuntimeStreamExtensions.AsStreamForRead pour convertir IRandomAccessStream n’empêche pas le flux .NET Framework converti d’être accessible en lecture.For example, using WindowsRuntimeStreamExtensions.AsStreamForRead to convert an IRandomAccessStream doesn't limit the converted .NET Framework stream to being readable. Il est également accessible en écriture.It's also writable.

Exemple : Convertir Windows Runtime accès aléatoire au flux cadre .NETExample: Convert Windows Runtime random-access to .NET Framework stream

Pour convertir un flux d’accès aléatoire Windows Runtime en un flux .NET Framework, utilisez la méthode WindowsRuntimeStreamExtensions.AsStream.To convert from a Windows Runtime random-access stream to a .NET Framework stream, use the WindowsRuntimeStreamExtensions.AsStream method.

L’exemple de code suivant vous invite à sélectionner un fichier, l’ouvre à l’aide des API Windows Runtime, puis le convertit en flux .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. Il lit le flux et l’exporte vers un bloc de texte.It reads the stream and outputs it to a text block. En général, vous devez manipuler le flux à l’aide des API .NET Framework avant de sortir les résultats.You would typically manipulate the stream with .NET Framework APIs before outputting the results.

Pour exécuter cet exemple, créez une application XAML UWP, contenant un bloc de texte nommé TextBlock1 et un bouton nommé Button1.To run this example, create a UWP XAML app that contains a text block named TextBlock1 and a button named Button1. Associez l’événement de clic de bouton à la méthode button1_Click qui est illustrée dans l’exemple.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 flux .NET Framework en flux Windows RuntimeConvert from a .NET Framework to a Windows Runtime stream

Pour convertir un flux .NET Framework en un flux Windows Runtime, utilisez l’une des méthodes System.IO.WindowsRuntimeStreamExtensions suivantes :To convert from a .NET Framework stream to a Windows Runtime stream, use one of the following System.IO.WindowsRuntimeStreamExtensions methods:

Lorsque vous convertissez un flux .NET Framework en flux Windows Runtime, les fonctionnalités du flux converti dépendent de celles du flux d’origine.When you convert a .NET Framework stream to a Windows Runtime stream, the capabilities of the converted stream depend on the original stream. Par exemple, si le flux d’origine prend en charge la lecture et l’écriture, et que vous appelez WindowsRuntimeStreamExtensions.AsInputStream pour convertir le flux, le type retourné est un 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 implémente IInputStream et IOutputStream, et prend en charge la lecture et l’écriture.IRandomAccessStream implements IInputStream and IOutputStream, and supports reading and writing.

Les flux .NET Framework ne prennent pas en charge le clonage, même après la conversion..NET Framework streams don't support cloning, even after conversion. Si vous convertissez un flux .NET Framework en flux Windows Runtime, et appelez GetInputStreamAt ou GetOutputStreamAt, qui appelle CloneStream, ou si vous appelez CloneStream directement, une exception est levée.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.

Exemple : Convertir le cadre .NET en flux d’accès aléatoire Windows RuntimeExample: Convert .NET Framework to Windows Runtime random-access stream

Pour convertir un flux .NET Framework en flux d’accès aléatoire Windows Runtime, utilisez une méthode AsRandomAccessStream, comme indiqué dans l’exemple suivant :To convert from a .NET Framework stream to a Windows Runtime random-access stream, use the AsRandomAccessStream method, as shown in the following example:

Important

Vérifiez que le flux du .NET Framework que vous utilisez prend en charge la recherche, ou copiez-le dans un flux qui la prend en charge.Make sure that the .NET Framework stream you are using supports seeking, or copy it to a stream that does. Vous pouvez utiliser la propriété Stream.CanSeek pour le déterminer.You can use the Stream.CanSeek property to determine this.

Pour exécuter cet exemple, créez une application XAML UWP qui cible .NET Framework 4.5.1 et contient un bloc de texte nommé TextBlock2 et un bouton nommé 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. Associez l’événement de clic de bouton à la méthode button2_Click qui est illustrée dans l’exemple.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

Voir aussiSee also