DataReader 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
입력 스트림에서 데이터를 읽습니다.
public ref class DataReader sealed : IClosable, IDataReader
/// [Windows.Foundation.Metadata.Activatable(Windows.Storage.Streams.IDataReaderFactory, 65536, Windows.Foundation.UniversalApiContract)]
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class DataReader final : IClosable, IDataReader
/// [Windows.Foundation.Metadata.ContractVersion(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(Windows.Storage.Streams.IDataReaderFactory, 65536, "Windows.Foundation.UniversalApiContract")]
class DataReader final : IClosable, IDataReader
[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
[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
function DataReader(inputStream)
Public NotInheritable Class DataReader
Implements IDataReader, IDisposable
- 상속
- 특성
- 구현
Windows 요구 사항
디바이스 패밀리 |
Windows 10 (10.0.10240.0에서 도입되었습니다.)
|
API contract |
Windows.Foundation.UniversalApiContract (v1.0에서 도입되었습니다.)
|
예제
다음 코드 예제에서는 메모리 내 스트림에 문자열을 쓰고 읽는 방법을 보여 줍니다. C# 및 C++/CX의 전체 샘플 애플리케이션은 데이터 직렬화 및 역직렬화 샘플을 참조하세요.
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;
}
}
}
}
#include "pch.h"
#include "WriteReadStream.h" // header file for WriteReadStream.xaml.
#include <sstream>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Storage.Streams.h>
using namespace winrt;
std::array<winrt::hstring, 5> m_inputElements{ L"Hello", L"World", L"1 2 3 4 5", L"Très bien!", L"Goodbye" };
WriteReadStream::WriteReadStream()
{
InitializeComponent();
// Populate the text block with the input elements.
std::wstringstream stringstream;
for (winrt::hstring const& element : m_inputElements)
{
stringstream << element.c_str() << L";";
}
ElementsToWrite().Text(stringstream.str().c_str());
}
// 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.
winrt::Windows::Foundation::IAsyncAction WriteReadStream::TransferData(
Windows::Foundation::IInspectable const& /* sender */,
Windows::UI::Xaml::RoutedEventArgs const& /* args */)
{
// Initialize the in-memory stream where data will be stored.
Windows::Storage::Streams::InMemoryRandomAccessStream stream;
// Create the DataWriter object backed by the in-memory stream. When
// dataWriter goes out of scope, it closes the underlying stream.
Windows::Storage::Streams::DataWriter dataWriter{ stream };
dataWriter.UnicodeEncoding(Windows::Storage::Streams::UnicodeEncoding::Utf16LE);
dataWriter.ByteOrder(Windows::Storage::Streams::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 the position that
// the original stream ends up in after the store.
Windows::Storage::Streams::IInputStream inputStream{ stream.GetInputStreamAt(0) };
Windows::Storage::Streams::DataReader dataReader{ inputStream };
// The encoding and byte order need to match the settings of the writer that
// we previously used.
dataReader.UnicodeEncoding(Windows::Storage::Streams::UnicodeEncoding::Utf16LE);
dataReader.ByteOrder(Windows::Storage::Streams::ByteOrder::LittleEndian);
// Write the input data to the output stream. Serialize the elements by writing
// each string separately, preceded by its length in bytes.
for (winrt::hstring const& element : m_inputElements)
{
dataWriter.WriteUInt32(element.size());
dataWriter.WriteString(element);
}
// Send the contents of the writer to the backing stream.
unsigned int bytesStored{ co_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.
if (co_await dataWriter.FlushAsync())
{
try
{
// Once we've written the contents successfully, we load the stream.
unsigned int bytesLoaded{ co_await dataReader.LoadAsync((unsigned int)stream.Size()) };
std::wstringstream 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).c_str() << std::endl;
}
// Populate the ElementsRead text block with the items we read from the stream
ElementsRead().Text(readFromStream.str().c_str());
}
catch (winrt::hresult_error const& ex)
{
ElementsRead().Text(L"Error: " + ex.message());
}
}
}
#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;
}
});
}
설명
DataReader 개체의 인스턴스는 동시 읽기 작업을 지원하지 않습니다. 애플리케이션이 읽고 있는 DataReader instance 스트림을 동시에 읽거나 분리하는 경우 개체 호출이 실패하고 오류 HRESULT_FROM_WIN32(ERROR_INVALID_OPERATION)가 발생합니다.
생성자
DataReader(IInputStream) |
데이터 판독기의 새 instance 만들고 초기화합니다. |
속성
ByteOrder |
입력 스트림에 있는 데이터의 바이트 순서를 가져오거나 설정합니다. |
InputStreamOptions |
입력 스트림에 대한 읽기 옵션을 가져오거나 설정합니다. |
UnconsumedBufferLength |
읽지 않은 버퍼의 크기를 가져옵니다. |
UnicodeEncoding |
입력 스트림에 대한 유니코드 문자 인코딩을 가져오거나 설정합니다. |
메서드
Close() |
현재 스트림을 닫고 시스템 리소스를 해제합니다. |
DetachBuffer() |
데이터 판독기와 연결된 버퍼를 분리합니다. 데이터 판독기를 삭제한 후 버퍼를 유지하려는 경우에 유용합니다. |
DetachStream() |
데이터 판독기와 연결된 스트림을 분리합니다. |
Dispose() |
관리되지 않는 리소스의 확보, 해제 또는 다시 설정과 관련된 애플리케이션 정의 작업을 수행합니다. |
FromBuffer(IBuffer) |
지정된 버퍼의 데이터를 사용하여 데이터 판독기의 새 instance 만듭니다. |
LoadAsync(UInt32) |
입력 스트림에서 데이터를 로드합니다. |
ReadBoolean() |
입력 스트림에서 부울 값을 읽습니다. |
ReadBuffer(UInt32) |
입력 스트림에서 버퍼를 읽습니다. |
ReadByte() |
입력 스트림에서 바이트 값을 읽습니다. |
ReadBytes(Byte[]) |
입력 스트림에서 바이트 값 배열을 읽습니다. |
ReadDateTime() |
입력 스트림에서 날짜 및 시간 값을 읽습니다. |
ReadDouble() |
입력 스트림에서 부동 소수점 값을 읽습니다. |
ReadGuid() |
입력 스트림에서 GUID 값을 읽습니다. |
ReadInt16() |
입력 스트림에서 16비트 정수 값을 읽습니다. |
ReadInt32() |
입력 스트림에서 32비트 정수 값을 읽습니다. |
ReadInt64() |
입력 스트림에서 64비트 정수 값을 읽습니다. |
ReadSingle() |
입력 스트림에서 부동 소수점 값을 읽습니다. |
ReadString(UInt32) |
입력 스트림에서 문자열 값을 읽습니다. |
ReadTimeSpan() |
입력 스트림에서 시간 간격 값을 읽습니다. |
ReadUInt16() |
입력 스트림에서 부호 없는 16비트 정수 를 읽습니다. |
ReadUInt32() |
입력 스트림에서 부호 없는 32비트 정수 를 읽습니다. |
ReadUInt64() |
입력 스트림에서 부호 없는 64비트 정수 를 읽습니다. |