DataReader Classe

Définition

Lit les données d’un flux d’entrée.

C#
[Windows.Foundation.Metadata.Activatable(typeof(Windows.Storage.Streams.IDataReaderFactory), 65536, typeof(Windows.Foundation.UniversalApiContract))]
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public sealed class DataReader : System.IDisposable, IDataReader
C#
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
[Windows.Foundation.Metadata.Activatable(typeof(Windows.Storage.Streams.IDataReaderFactory), 65536, "Windows.Foundation.UniversalApiContract")]
public sealed class DataReader : System.IDisposable, IDataReader
Héritage
Object DataReader
Attributs
Implémente

Configuration requise pour Windows

Famille d’appareils
Windows 10 (introduit dans 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduit dans v1.0)

Exemples

L’exemple de code suivant montre comment écrire et lire des chaînes dans un flux en mémoire. Pour obtenir l’exemple d’application complet en C# et en C++/CX, consultez Exemple de sérialisation et désérialisation des données.

C#
using System;
using System.Diagnostics;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

// This is the click handler for the 'Copy Strings' button.  Here we will parse the
// strings contained in the ElementsToWrite text block, write them to a stream using
// DataWriter, retrieve them using DataReader, and output the results in the
// ElementsRead text block.
private async void TransferData(object sender, RoutedEventArgs e)
{
    // Initialize the in-memory stream where data will be stored.
    using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
    {
        // Create the data writer object backed by the in-memory stream.
        using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream))
        {
            dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

            // Parse the input stream and write each element separately.
            string[] inputElements = ElementsToWrite.Text.Split(';');
            foreach (string inputElement in inputElements)
            {
                uint inputElementSize = dataWriter.MeasureString(inputElement);
                dataWriter.WriteUInt32(inputElementSize);
                dataWriter.WriteString(inputElement);
            }

            // Send the contents of the writer to the backing stream.
            await dataWriter.StoreAsync();

            // For the in-memory stream implementation we are using, the flushAsync call 
            // is superfluous,but other types of streams may require it.
            await dataWriter.FlushAsync();

            // In order to prolong the lifetime of the stream, detach it from the 
            // DataWriter so that it will not be closed when Dispose() is called on 
            // dataWriter. Were we to fail to detach the stream, the call to 
            // dataWriter.Dispose() would close the underlying stream, preventing 
            // its subsequent use by the DataReader below.
            dataWriter.DetachStream();
        }

        // Create the input stream at position 0 so that the stream can be read 
        // from the beginning.
        using (var inputStream = stream.GetInputStreamAt(0))
        {
            using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream))
            {
                // The encoding and byte order need to match the settings of the writer 
                // we previously used.
                dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                dataReader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

                // Once we have written the contents successfully we load the stream.
                await dataReader.LoadAsync((uint)stream.Size);

                var receivedStrings = "";

                // Keep reading until we consume the complete stream.
                while (dataReader.UnconsumedBufferLength > 0)
                {
                    // Note that the call to readString requires a length of "code units" 
                    // to read. This is the reason each string is preceded by its length 
                    // when "on the wire".
                    uint bytesToRead = dataReader.ReadUInt32();
                    receivedStrings += dataReader.ReadString(bytesToRead) + "\n";
                }

                // Populate the ElementsRead text block with the items we read 
                // from the stream.
                ElementsRead.Text = receivedStrings;
            }
        }
    }
}

Remarques

Les instances d’objets DataReader ne prennent pas en charge les opérations de lecture simultanées. Si une application lit ou détache simultanément un flux d’un instance DataReader en cours de lecture, l’appel à l’objet échoue avec l’erreur HRESULT_FROM_WIN32(ERROR_INVALID_OPERATION).

Constructeurs

DataReader(IInputStream)

Crée et initialise une nouvelle instance du lecteur de données.

Propriétés

ByteOrder

Obtient ou définit l’ordre d’octet des données dans le flux d’entrée.

InputStreamOptions

Obtient ou définit les options de lecture pour le flux d’entrée.

UnconsumedBufferLength

Obtient la taille de la mémoire tampon qui n’a pas été lue.

UnicodeEncoding

Obtient ou définit l’encodage de caractères Unicode pour le flux d’entrée.

Méthodes

Close()

Ferme le flux actuel et libère les ressources système.

DetachBuffer()

Détache la mémoire tampon associée au lecteur de données. Cela est utile si vous souhaitez conserver la mémoire tampon après avoir éliminé le lecteur de données.

DetachStream()

Détache le flux associé au lecteur de données.

Dispose()

Exécute les tâches définies par l'application associées à la libération ou à la redéfinition des ressources non managées.

FromBuffer(IBuffer)

Crée une instance du lecteur de données avec les données de la mémoire tampon spécifiée.

LoadAsync(UInt32)

Charge des données à partir du flux d’entrée.

ReadBoolean()

Lit une valeur booléenne à partir du flux d’entrée.

ReadBuffer(UInt32)

Lit une mémoire tampon à partir du flux d’entrée.

ReadByte()

Lit une valeur d’octet à partir du flux d’entrée.

ReadBytes(Byte[])

Lit un tableau de valeurs d’octets à partir du flux d’entrée.

ReadDateTime()

Lit une valeur de date et d’heure à partir du flux d’entrée.

ReadDouble()

Lit une valeur à virgule flottante à partir du flux d’entrée.

ReadGuid()

Lit une valeur GUID à partir du flux d’entrée.

ReadInt16()

Lit une valeur entière 16 bits à partir du flux d’entrée.

ReadInt32()

Lit une valeur entière 32 bits à partir du flux d’entrée.

ReadInt64()

Lit une valeur entière 64 bits à partir du flux d’entrée.

ReadSingle()

Lit une valeur à virgule flottante à partir du flux d’entrée.

ReadString(UInt32)

Lit une valeur de chaîne à partir du flux d’entrée.

ReadTimeSpan()

Lit une valeur d’intervalle de temps à partir du flux d’entrée.

ReadUInt16()

Lit un entier non signé 16 bits à partir du flux d’entrée.

ReadUInt32()

Lit un entier non signé 32 bits à partir du flux d’entrée.

ReadUInt64()

Lit un entier non signé 64 bits à partir du flux d’entrée.

S’applique à

Produit Versions
WinRT Build 10240, Build 10586, Build 14383, Build 15063, Build 16299, Build 17134, Build 17763, Build 18362, Build 19041, Build 20348, Build 22000, Build 22621, Build 26100

Voir aussi