DataReader
DataReader
DataReader
DataReader
Class
Definition
Reads data from an input stream.
public : sealed class DataReader : IClosable, IDataReaderpublic sealed class DataReader : IDisposable, IDataReaderPublic NotInheritable Class DataReader Implements IDisposable, IDataReader// You can use this class in JavaScript.
- Attributes
| Device family |
Windows 10 (introduced v10.0.10240.0)
|
| API contract |
Windows.Foundation.UniversalApiContract (introduced v1)
|
Examples
The following example shows how to write and read strings to an in-memory stream. For the full code sample, see Serializing and deserializing data sample.
#include "pch.h"
#include "WriteReadStream.xaml.h"
using namespace Concurrency;
using namespace DataReaderWriter;
using namespace Platform;
using namespace Windows::Storage::Streams;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
Array<String^>^ _inputElements = ref new Array<String^>
{
"Hello", "World", "1 2 3 4 5", "Très bien!", "Goodbye"
};
WriteReadStream::WriteReadStream()
{
InitializeComponent();
// Populate the text block with the input elements.
ElementsToWrite->Text = "";
for (unsigned int i = 0; i < _inputElements->Length; i++)
{
ElementsToWrite->Text += _inputElements[i] + ";";
}
}
// Invoked when this page is about to be displayed in a Frame.
void WriteReadStream::OnNavigatedTo(NavigationEventArgs^ e)
{
// Get a pointer to our main page.
rootPage = MainPage::Current;
}
// 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.
void DataReaderWriter::WriteReadStream::TransferData(
Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
// Initialize the in-memory stream where data will be stored.
InMemoryRandomAccessStream^ stream = ref new InMemoryRandomAccessStream();
// Create the DataWriter object backed by the in-memory stream. When
// dataWriter is deleted, it will also close the underlying stream.
DataWriter^ dataWriter = ref new DataWriter(stream);
dataWriter->UnicodeEncoding = UnicodeEncoding::Utf8;
dataWriter->ByteOrder = ByteOrder::LittleEndian;
// Create the data reader by using the input stream set at position 0 so that
// the stream will be read from the beginning regardless of where the position
// the original stream ends up in after the store.
IInputStream^ inputStream = stream->GetInputStreamAt(0);
DataReader^ dataReader = ref new DataReader(inputStream);
// The encoding and byte order need to match the settings of the writer
/ we previously used.
dataReader->UnicodeEncoding = UnicodeEncoding::Utf8;
dataReader->ByteOrder = ByteOrder::LittleEndian;
// Write the input data to the output stream. Serialize the elements by writing
// each string separately, preceded by its length.
for (unsigned int i = 0; i < _inputElements->Length; i++)
{
unsigned int inputElementSize = dataWriter->MeasureString(_inputElements[i]);
dataWriter->WriteUInt32(inputElementSize);
dataWriter->WriteString(_inputElements[i]);
}
// Send the contents of the writer to the backing stream.
create_task(dataWriter->StoreAsync()).then([this, dataWriter] (unsigned int bytesStored)
{
// For the in-memory stream implementation we are using, the FlushAsync() call
// is superfluous, but other types of streams may require it.
return dataWriter->FlushAsync();
}).then([this, dataReader, stream] (bool flushOp)
{
// Once we have written the contents successfully we load the stream.
return dataReader->LoadAsync((unsigned int) stream->Size);
}).then([this, dataReader] (task<unsigned int> bytesLoaded)
{
try
{
// Check for possible exceptions that could have been thrown
// in the async call chain.
bytesLoaded.get();
String^ readFromStream = "";
// 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".
unsigned int bytesToRead = dataReader->ReadUInt32();
readFromStream += dataReader->ReadString(bytesToRead) + "\n";
}
// Populate the ElementsRead text block with the items we read from the stream
ElementsRead->Text = readFromStream;
}
catch (Exception^ e)
{
ElementsRead->Text = "Error: " + e->Message;
}
});
}
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;
}
}
}
}
(function () {
"use strict";
var page = WinJS.UI.Pages.define("/html/write-read-stream.html", {
ready: function (element, options) {
var sourceElement = document.getElementById("ElementsToSend");
sourceElement.innerHTML = "Hello;World;1 2 3 4 5;Très bien!;Goodbye";
var sendButton = document.getElementById("SendButton");
sendButton.addEventListener("click", transferData);
}
});
function transferData() {
var sourceElement = document.getElementById("ElementsToSend");
var destinationElement = document.getElementById("scenario1Output");
// First a DataWriter object is created, backed by an in-memory stream where
// the data will be stored.
var writer = Windows.Storage.Streams.DataWriter(
new Windows.Storage.Streams.InMemoryRandomAccessStream());
writer.unicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.utf8;
writer.byteOrder = Windows.Storage.Streams.ByteOrder.littleEndian;
// We separate the contents of the sourceElement div in multiple strings
// using ';' as the separator. Each string will be written separately.
var elements = sourceElement.innerHTML.split(";");
elements.forEach(function (element) {
var codeUnits = writer.measureString(element);
writer.writeInt32(codeUnits);
writer.writeString(element);
});
var reader;
var stream;
// The call to store async sends the actual contents of the writer
// to the backing stream.
writer.storeAsync().then(function () {
// For the in-memory stream implementation we are using, the flushAsync call
// is superfluous, but other types of streams may require it.
return writer.flushAsync();
}).then(function () {
// We detach the stream to prolong its useful lifetime. Were we to fail
// to detach the stream, the call to writer.close() would close the underlying
// stream, preventing its subsequent use by the DataReader below. Most clients
// of DataWriter will have no reason to use the underlying stream after
// writer.close() is called, and will therefore have no reason to call
// writer.detachStream(). Note that once we detach the stream, we assume
// responsibility for closing the stream subsequently; after the stream
// has been detached, a call to writer.close() will have no effect on the stream.
stream = writer.detachStream();
// Make sure the stream is read from the beginning in the reader
// we are creating below.
stream.seek(0);
// Most DataWriter clients will not call writer.detachStream(),
// and furthermore will be working with a file-backed or network-backed stream,
// rather than an in-memory-stream. In such cases, it would be particularly
// important to call writer.close(). Doing so is always a best practice.
writer.close();
reader = new Windows.Storage.Streams.DataReader(stream);
// The encoding and byte order need to match the settings of the writer
// we previously used.
reader.unicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.utf8;
reader.byteOrder = Windows.Storage.Streams.ByteOrder.littleEndian;
// Once we have written the contents successfully we load the stream,
// this is also an asynchronous operation
return reader.loadAsync(stream.size);
}).done(function () {
var receivedStrings = "";
// Keep reading until we consume the complete stream
while (reader.unconsumedBufferLength > 0) {
// Note that the call to readString requires a length of "code units"
// to read. This is the reason each string is preceeded by its length
// when "on the wire".
var codeUnitsToRead = reader.readInt32();
receivedStrings += reader.readString(codeUnitsToRead) + "<br/>";
}
// Calling reader.close() closes the underlying stream. It would be particularly important
// to call reader.close() if the underlying stream were file-backed or
// network-backed. Note that this call to reader.close() satisfies
// our obligation to close the stream previously detached from DataReader.
reader.close();
destinationElement.innerHTML = receivedStrings;
});
};
})();
Constructors
DataReader(IInputStream) DataReader(IInputStream) DataReader(IInputStream) DataReader(IInputStream)
Creates and initializes a new instance of the data reader.
public : DataReader(IInputStream inputStream)public DataReader(IInputStream inputStream)Public Sub New(inputStream As IInputStream)// You can use this method in JavaScript.
- inputStream
- IInputStream IInputStream IInputStream IInputStream
The input stream.
Properties
ByteOrder ByteOrder ByteOrder ByteOrder
Gets or sets the byte order of the data in the input stream.
public : ByteOrder ByteOrder { get; set; }public ByteOrder ByteOrder { get; set; }Public ReadWrite Property ByteOrder As ByteOrder// You can use this property in JavaScript.
InputStreamOptions InputStreamOptions InputStreamOptions InputStreamOptions
Gets or sets the read options for the input stream.
public : InputStreamOptions InputStreamOptions { get; set; }public InputStreamOptions InputStreamOptions { get; set; }Public ReadWrite Property InputStreamOptions As InputStreamOptions// You can use this property in JavaScript.
One of the enumeration values.
UnconsumedBufferLength UnconsumedBufferLength UnconsumedBufferLength UnconsumedBufferLength
Gets the size of the buffer that has not been read.
public : unsigned int UnconsumedBufferLength { get; }public uint UnconsumedBufferLength { get; }Public ReadOnly Property UnconsumedBufferLength As uint// You can use this property in JavaScript.
- Value
- unsigned int uint uint uint
The size of the buffer that has not been read, in bytes.
UnicodeEncoding UnicodeEncoding UnicodeEncoding UnicodeEncoding
Gets or sets the Unicode character encoding for the input stream.
public : UnicodeEncoding UnicodeEncoding { get; set; }public UnicodeEncoding UnicodeEncoding { get; set; }Public ReadWrite Property UnicodeEncoding As UnicodeEncoding// You can use this property in JavaScript.
One of the enumeration values.
Methods
Close() Close() Close() Close()
Closes the current stream and releases system resources.
public : void Close()This member is not implemented in C#This member is not implemented in VB.Net// You can use this method in JavaScript.
Remarks
DataReader takes ownership of the stream that is passed to its constructor. Calling this method also calls on the associated stream. After calling this method, calls to most other DataReader methods will fail.
If you do not want the associated stream to be closed when the reader closes, call DataReader.DetachStream before calling this method.
DetachStream() DetachStream() DetachStream() DetachStream()
Detaches the stream that is associated with the data reader.
public : IInputStream DetachStream()public IInputStream DetachStream()Public Function DetachStream() As IInputStream// You can use this method in JavaScript.
The detached stream.
Dispose() Dispose() Dispose() Dispose()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
This member is not implemented in C++void Dispose()Sub Disposevoid Dispose()
FromBuffer(IBuffer) FromBuffer(IBuffer) FromBuffer(IBuffer) FromBuffer(IBuffer)
Creates a new instance of the data reader with data from the specified buffer.
public : static DataReader FromBuffer(IBuffer buffer)public static DataReader FromBuffer(IBuffer buffer)Public Static Function FromBuffer(buffer As IBuffer) As DataReader// You can use this method in JavaScript.
The data reader.
LoadAsync(UInt32) LoadAsync(UInt32) LoadAsync(UInt32) LoadAsync(UInt32)
Loads data from the input stream.
public : DataReaderLoadOperation LoadAsync(unsigned int count)public DataReaderLoadOperation LoadAsync(UInt32 count)Public Function LoadAsync(count As UInt32) As DataReaderLoadOperation// You can use this method in JavaScript.
- count
- unsigned int UInt32 UInt32 UInt32
The count of bytes to load into the intermediate buffer.
The asynchronous load data request.
Remarks
The read operation can get more or fewer bytes depending on how the InputStreamOptions property is set.
You will need to call this method to load the data before the data can be read from DataReader.
- See Also
ReadBoolean() ReadBoolean() ReadBoolean() ReadBoolean()
Reads a Boolean value from the input stream.
public : PlatForm::Boolean ReadBoolean()public bool ReadBoolean()Public Function ReadBoolean() As bool// You can use this method in JavaScript.
The value.
ReadBuffer(UInt32) ReadBuffer(UInt32) ReadBuffer(UInt32) ReadBuffer(UInt32)
Reads a buffer from the input stream.
public : IBuffer ReadBuffer(unsigned int length)public IBuffer ReadBuffer(UInt32 length)Public Function ReadBuffer(length As UInt32) As IBuffer// You can use this method in JavaScript.
- length
- unsigned int UInt32 UInt32 UInt32
The length of the buffer, in bytes.
ReadByte() ReadByte() ReadByte() ReadByte()
Reads a byte value from the input stream.
public : byte ReadByte()public byte ReadByte()Public Function ReadByte() As byte// You can use this method in JavaScript.
The value.
ReadBytes(Byte[]) ReadBytes(Byte[]) ReadBytes(Byte[]) ReadBytes(Byte[])
Reads an array of byte values from the input stream.
public : void ReadBytes(Byte[] value)public void ReadBytes(Byte[] value)Public Function ReadBytes(value As Byte[]) As void// You can use this method in JavaScript.
- value
- Byte[] Byte[] Byte[] Byte[]
The array that receives the byte values.
- See Also
ReadDateTime() ReadDateTime() ReadDateTime() ReadDateTime()
Reads a date and time value from the input stream.
public : DateTime ReadDateTime()public DateTimeOffset ReadDateTime()Public Function ReadDateTime() As DateTimeOffset// You can use this method in JavaScript.
The value.
ReadDouble() ReadDouble() ReadDouble() ReadDouble()
Reads a floating-point value from the input stream.
public : double ReadDouble()public double ReadDouble()Public Function ReadDouble() As double// You can use this method in JavaScript.
The value.
ReadGuid() ReadGuid() ReadGuid() ReadGuid()
Reads a GUID value from the input stream.
public : PlatForm::Guid ReadGuid()public Guid ReadGuid()Public Function ReadGuid() As Guid// You can use this method in JavaScript.
The value.
ReadInt16() ReadInt16() ReadInt16() ReadInt16()
Reads a 16-bit integer value from the input stream.
public : short ReadInt16()public short ReadInt16()Public Function ReadInt16() As short// You can use this method in JavaScript.
The value.
ReadInt32() ReadInt32() ReadInt32() ReadInt32()
Reads a 32-bit integer value from the input stream.
public : int ReadInt32()public int ReadInt32()Public Function ReadInt32() As int// You can use this method in JavaScript.
The value.
ReadInt64() ReadInt64() ReadInt64() ReadInt64()
Reads a 64-bit integer value from the input stream.
public : long ReadInt64()public long ReadInt64()Public Function ReadInt64() As long// You can use this method in JavaScript.
The value.
ReadSingle() ReadSingle() ReadSingle() ReadSingle()
Reads a floating-point value from the input stream.
public : float ReadSingle()public float ReadSingle()Public Function ReadSingle() As float// You can use this method in JavaScript.
The value.
ReadString(UInt32) ReadString(UInt32) ReadString(UInt32) ReadString(UInt32)
Reads a string value from the input stream.
public : PlatForm::String ReadString(unsigned int codeUnitCount)public string ReadString(UInt32 codeUnitCount)Public Function ReadString(codeUnitCount As UInt32) As string// You can use this method in JavaScript.
- codeUnitCount
- unsigned int UInt32 UInt32 UInt32
The length of the string.
The value.
ReadTimeSpan() ReadTimeSpan() ReadTimeSpan() ReadTimeSpan()
Reads a time-interval value from the input stream.
public : TimeSpan ReadTimeSpan()public TimeSpan ReadTimeSpan()Public Function ReadTimeSpan() As TimeSpan// You can use this method in JavaScript.
The value.
ReadUInt16() ReadUInt16() ReadUInt16() ReadUInt16()
Reads a 16-bit unsigned integer from the input stream.
public : ushort ReadUInt16()public ushort ReadUInt16()Public Function ReadUInt16() As ushort// You can use this method in JavaScript.
The value.
ReadUInt32() ReadUInt32() ReadUInt32() ReadUInt32()
Reads a 32-bit unsigned integer from the input stream.
public : unsigned int ReadUInt32()public uint ReadUInt32()Public Function ReadUInt32() As uint// You can use this method in JavaScript.
The value.
See Also
- Reading and writing data sample
- StreamSocket sample
- DataReaderLoadOperation DataReaderLoadOperation DataReaderLoadOperation DataReaderLoadOperation
- Serializing and deserializing data sample (Windows 10)
- File access sample (Windows 10)
- StreamSocket sample (Windows 10)
- Custom USB device sample (Windows 10)
- DatagramSocket sample (Windows 10)