本文整理汇总了C#中Windows.Storage.Streams.DataReader.ReadInt32方法的典型用法代码示例。如果您正苦于以下问题:C# DataReader.ReadInt32方法的具体用法?C# DataReader.ReadInt32怎么用?C# DataReader.ReadInt32使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Storage.Streams.DataReader
的用法示例。
在下文中一共展示了DataReader.ReadInt32方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LoadFrom
public static async Task<bool> LoadFrom ( ObservableCollection<RecentData> datas )
{
try
{
StorageFile sf = await ApplicationData.Current.LocalFolder.GetFileAsync ( "data.dat" );
FileRandomAccessStream stream = await sf.OpenAsync ( FileAccessMode.Read ) as FileRandomAccessStream;
DataReader dr = new DataReader ( stream );
dr.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
dr.ByteOrder = ByteOrder.LittleEndian;
await dr.LoadAsync ( ( uint ) stream.Size );
int len = dr.ReadInt32 ();
for ( int i = 0; i < len; i++ )
{
RecentData data = new RecentData ();
uint srclen = dr.ReadUInt32 ();
data.Source = dr.ReadString ( srclen );
data.SourceIndex = dr.ReadInt32 ();
data.TargetIndex = dr.ReadInt32 ();
datas.Add ( data );
}
stream.Dispose ();
}
catch { return false; }
return true;
}
示例2: ReceiveImage
private async void ReceiveImage(StreamSocket socket)
{
UpdateStatus("Empfange Daten...");
// DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen
var reader = new DataReader(socket.InputStream);
// Anzahl der Bytes abrufen, aus denen das Bild besteht
// Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden
await reader.LoadAsync(4);
int imageSize = reader.ReadInt32();
// Bytearray des Bildes laden
await reader.LoadAsync((uint)imageSize);
byte[] imageBytes = new byte[imageSize];
reader.ReadBytes(imageBytes);
// Bytearray in Stream laden und anzeigen
Dispatcher.BeginInvoke(() =>
{
using (var ms = new MemoryStream(imageBytes))
{
var image = new BitmapImage();
image.SetSource(ms);
ReceivedImage.Source = image;
}
});
UpdateStatus("Bild empfangen.");
// Ressourcen freigeben
reader.Dispose();
}
示例3: WaitForData
public async Task WaitForData()
{
var mainPageViewModel = MainPageViewModel.GetInstance();
using (var dr = new DataReader(ServerProxy.TcpSocket.InputStream))
{
while (mainPageViewModel.ConnectionStatus)
{
var stringHeader = await dr.LoadAsync(4);
if (stringHeader == 0)
{
mainPageViewModel.ConnectionStatus = false;
return;
}
int messageLength = dr.ReadInt32();
uint numBytes = await dr.LoadAsync((uint)messageLength);
var packetBaseBuffer = new byte[numBytes];
dr.ReadBytes(packetBaseBuffer);
var packetBase = new PacketBase();
using (var stream = new MemoryStream(packetBaseBuffer))
{
try
{
var reader = new BinaryReader(stream);
packetBase.Read(reader);
}
catch (Exception e)
{
#if DEBUG
throw;
#endif
}
}
var incomingMessage = IncomingMessageFactory.GetMessage(
packetBase.Data as PacketV1);
incomingMessage.HandleMessage();
}
}
}
示例4: Read
public void Read(DataReader reader)
{
t = (HeartBeatType)reader.ReadInt32();
time = reader.ReadDateTime().UtcDateTime;
cc = reader.ReadInt64();
asdf = reader.ReadInt64();
peak = reader.ReadInt64();
max0 = reader.ReadUInt64();
max1 = reader.ReadUInt64();
ave0 = reader.ReadUInt64();
ave1 = reader.ReadUInt64();
ave = reader.ReadUInt64();
beat = reader.ReadUInt64();
audio = reader.ReadUInt64();
noAudio = reader.ReadUInt64();
}
示例5: ReceiveImage
private async void ReceiveImage(PeerInformation peer)
{
try
{
Status.Text = "Verbinde mit Peer...";
StreamSocket peerSocket = await PeerFinder.ConnectAsync(peer);
Status.Text = "Verbunden. Empfange Daten...";
// DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen
var reader = new DataReader(peerSocket.InputStream);
// Anzahl der Bytes abrufen, aus denen das Bild besteht
// Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden
await reader.LoadAsync(4);
int imageSize = reader.ReadInt32();
// Bytearray des Bildes laden
await reader.LoadAsync((uint)imageSize);
byte[] imageBytes = new byte[imageSize];
reader.ReadBytes(imageBytes);
// Bytearray in Stream laden und anzeigen
using (var ms = new MemoryStream(imageBytes))
{
var image = new BitmapImage();
image.SetSource(ms);
ReceivedImage.Source = image;
}
Status.Text = "Bild empfangen.";
// Ressourcen freigeben
reader.Dispose();
peerSocket.Dispose();
// Wieder Verbindungen akzeptieren
PeerFinder.Start();
}
catch (Exception ex)
{
MessageBox.Show("Fehler: " + ex.Message);
Status.Text = "Bereit.";
}
}
示例6: WriteString
public async void WriteString(string HostName, string Message)
{
HostName remoteHostName = new HostName(HostName);
using (StreamSocket socket = new StreamSocket())
{
socket.Control.KeepAlive = false;
await socket.ConnectAsync(remoteHostName, "6");
using (DataWriter writer = new DataWriter(socket.OutputStream))
{
// set payload length
writer.ByteOrder = ByteOrder.LittleEndian;
writer.WriteUInt32(writer.MeasureString(Message));
// set payload type
writer.WriteByte((byte)PayloadType.String);
// set payload
writer.WriteString(Message);
// transmit
await writer.StoreAsync();
writer.DetachStream();
}
using (DataReader reader = new DataReader(socket.InputStream))
{
int length;
string response;
// receive payload length
reader.ByteOrder = ByteOrder.LittleEndian;
await reader.LoadAsync(4);
length = reader.ReadInt32();
// receive payload
await reader.LoadAsync((uint)length);
response = reader.ReadString((uint)length);
Debug.WriteLine(string.Format("response: {0}", response));
reader.DetachStream();
}
}
}
示例7: WaitForData
/// <summary>
/// Wait for data on a given socket.
/// </summary>
/// <param name="socket">Socket which will be monitored for incoming data</param>
private async void WaitForData(StreamSocket socket)
{
//System.Diagnostics.Debug.WriteLine("Waiting for header on socket from " + socket.Information.RemoteAddress.CanonicalName);
DataReader reader = new DataReader(socket.InputStream);
reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
// Load the first four bytes (32-bit int header)
var stringHeader = await reader.LoadAsync(4);
if (stringHeader == 0)
{
//System.Diagnostics.Debug.WriteLine("Disconnected from " + socket.Information.RemoteAddress.CanonicalName);
socket.Dispose();
return;
}
// Read the header of the stream (the first 4 bytes) which indicate how much bytes are expected after the header
Int32 strLength = reader.ReadInt32();
//System.Diagnostics.Debug.WriteLine("Waiting for data of length " + strLength + " on socket from " + socket.Information.RemoteAddress.CanonicalName);
// Asynchronously load the next "strLenght" bytes
uint byteCount = await reader.LoadAsync((uint)strLength);
// Prepare an array to read the bytes in
byte[] bytes = new byte[byteCount];
reader.ReadBytes(bytes);
// Convert the array of bytes to an UTF8 encoded string
string data = System.Text.Encoding.UTF8.GetString(bytes, 0, (int) byteCount);
System.Diagnostics.Debug.WriteLine(String.Format("Received data from {0}: {1}", socket.Information.RemoteAddress.CanonicalName, data));
// Trigger the registered callback
requestHandlerCallback(data, socket.Information.RemoteHostName.CanonicalName);
// Wait for more data on the same socket
WaitForData(socket);
}
示例8: Read
/// <summary>
/// Reads the specified hashed block stream into a memory stream.
/// </summary>
/// <param name="input">The hashed block stream.</param>
/// <returns>The de-hashed stream.</returns>
public static async Task<Stream> Read(IInputStream input)
{
if (input == null)
throw new ArgumentNullException("input");
var blockIndex = 0;
var result = new MemoryStream();
var hash = WindowsRuntimeBuffer.Create(32);
var reader = new DataReader(input)
{
ByteOrder = ByteOrder.LittleEndian,
};
var sha = HashAlgorithmProvider
.OpenAlgorithm(HashAlgorithmNames.Sha256);
try
{
while (true)
{
// Detect end of file
var read = await reader.LoadAsync(4);
if (read == 0)
break;
// Verify block index
var index = reader.ReadInt32();
if (index != blockIndex)
{
throw new InvalidDataException(string.Format(
"Wrong block ID detected, expected: {0}, actual: {1}",
blockIndex, index));
}
blockIndex++;
// Block hash
hash = await input.ReadAsync(hash, 32);
if (hash.Length != 32)
{
throw new InvalidDataException(
"Data corruption detected (truncated data)");
}
read = await reader.LoadAsync(4);
if (read != 4)
{
throw new InvalidDataException(
"Data corruption detected (truncated data)");
}
// Validate block size (< 10MB)
var blockSize = reader.ReadInt32();
if (blockSize == 0)
{
// Terminator block
var isTerminator = hash
.ToArray()
.All(x => x == 0);
if (!isTerminator)
{
throw new InvalidDataException(
"Data corruption detected (invalid hash for terminator block)");
}
break;
}
if (0 > blockSize || blockSize > 10485760)
{
throw new InvalidDataException(
"Data corruption detected (truncated data)");
}
// Check data truncate
var loaded = await reader.LoadAsync((uint)blockSize);
if (loaded < blockSize)
{
throw new InvalidDataException(
"Data corruption detected (truncated data)");
}
var buffer = reader.ReadBuffer((uint)blockSize);
// Verify block integrity
var actual = sha.HashData(buffer);
if (!CryptographicBuffer.Compare(hash, actual))
{
throw new InvalidDataException(
"Data corruption detected (content corrupted)");
}
await result.WriteAsync(buffer.ToArray(),
0, (int)buffer.Length);
}
//.........这里部分代码省略.........
示例9: ReadFileAsync
public async Task<IStorageFile> ReadFileAsync(StreamSocket socket, StorageFolder folder, string outputFilename = null)
{
StorageFile file;
using (var rw = new DataReader(socket.InputStream))
{
// 1. Read the filename length
await rw.LoadAsync(sizeof(Int32));
var filenameLength = (uint)rw.ReadInt32();
// 2. Read the filename
await rw.LoadAsync(filenameLength);
var originalFilename = rw.ReadString(filenameLength);
if (outputFilename == null)
{
outputFilename = originalFilename;
}
//3. Read the file length
await rw.LoadAsync(sizeof(UInt64));
var fileLength = rw.ReadUInt64();
// 4. Reading file
var buffer = rw.ReadBuffer((uint)fileLength);
file = await ApplicationData.Current.LocalFolder.CreateFileAsync(outputFilename, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBufferAsync(file, buffer);
//using (var memStream = await DownloadFile(rw, fileLength))
//{
// file = await folder.CreateFileAsync(outputFilename, CreationCollisionOption.ReplaceExisting);
// using (var fileStream1 = await file.OpenAsync(FileAccessMode.ReadWrite))
// {
// await RandomAccessStream.CopyAndCloseAsync(memStream.GetInputStreamAt(0), fileStream1.GetOutputStreamAt(0));
// }
// rw.DetachStream();
//}
}
return file;
}
示例10: LoadData
private ActivityDataDoc LoadData(DataReader reader)
{
//read signature
int signature = reader.ReadInt32();
//read head
ActivityDataDoc ret = new ActivityDataDoc();
ret.version = (int)reader.ReadByte();
ret.year = (int)reader.ReadByte();
ret.month = (int)reader.ReadByte();
ret.day = (int)reader.ReadByte();
//read data
while (reader.UnconsumedBufferLength > 0)
{
var row = new ActivityDataRow();
//row head
row.mode = reader.ReadByte();
row.hour = reader.ReadByte();
row.minute = reader.ReadByte();
//row meta
int size = (int)reader.ReadByte();
byte[] meta = new byte[4];
reader.ReadBytes(meta);
//row data
for (int i = 0, j = 0; meta[i] != 0 && i < 4 && j < size; ++i)
{
int lvalue = meta[i] >> 4;
int rvalue = meta[i] & 0x0f;
if (j < size)
{
int rawValue = reader.ReadInt32();
ActivityDataRow.DataType dtype = dataTypeMap[lvalue];
double value = GetValue(rawValue, dtype);
row.data.Add(dtype, value);
j++;
}
if (j < size)
{
int rawValue = reader.ReadInt32();
ActivityDataRow.DataType dtype = dataTypeMap[rvalue];
double value = GetValue(rawValue, dtype);
row.data.Add(dtype, value);
j++;
}
}
ret.data.Add(row);
}
return ret;
}
示例11: Listener_ConnectionReceived
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
OnCaptureStarted();
DataReader reader = new DataReader(args.Socket.InputStream);
reader.ByteOrder = ByteOrder.LittleEndian; //WTF Microsoft ?
try
{
while (true)
{
uwpCapture.GetFrame();
// Read first 4 bytes (length of the subsequent data).
uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
if (sizeFieldCount != sizeof(uint))
{
throw new ArgumentException("bad data from capture socket");
}
int actualLength = reader.ReadInt32();
byte[] data = new byte[actualLength];
sizeFieldCount = await reader.LoadAsync((uint)actualLength);
reader.ReadBytes(data);
OnSample(data);
}
}
finally
{
uwpCapture.Stop();
OnCaptureStopped();
}
}
示例12: OperateResponse
public async void OperateResponse()
{
SQLiteAsyncConnection con;
switch(this.operateContent)
{
case "LoginOperate":
int code= await Login();
if (code == 0) LoginOK();
else LoginErr(code.ToString());
break;
case "GetNewInfoOperator":
string pattern;
StorageFolder localFolderStorage = ApplicationData.Current.LocalFolder;
StorageFile infoStorageIcon;
try
{
infoStorageIcon = await localFolderStorage.GetFileAsync(LoginInfo.UserName + "\\" + "PersonIcon.jpg");
IRandomAccessStream iconStream = await infoStorageIcon.OpenAsync(FileAccessMode.Read);
await PageInit.homePage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
BitmapImage newImage = new BitmapImage();
newImage.SetSource(iconStream);
PageInit.homePage.SetIcon(ref newImage);
});
}
catch(Exception err)
{
infoStorageIcon = null;
}
if (infoStorageIcon == null)
{
pattern = "fakeid=(\\d*)";
var m = Regex.Match(responseInfo, pattern);
LoginInfo.FakeId = m.Groups[1].Value.ToString();
//无法检测到fakeid
if (string.IsNullOrEmpty(LoginInfo.FakeId))
{
// home.toast.Message = "无法查找到到您的Fakeid,可能是登陆超时"; home.toast.Show();
//此处添加通知
}
else
{
string responseInfoUri = "https://mp.weixin.qq.com/misc/getheadimg?fakeid=" + LoginInfo.FakeId + "&token=" + LoginInfo.Token + "&lang=zh_CN";
string responseInfoRefer = "https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token=" + LoginInfo.Token;
HttpImageGet getIcon = new HttpImageGet();
getIcon.Operate = "GetPersonalIcon";
getIcon.GetImageOperate(responseInfoUri, responseInfoRefer);
}
}
StorageFile infoStorageText;
try
{
infoStorageText = await localFolderStorage.GetFileAsync(LoginInfo.UserName + "\\" + "PersonalInfo.txt");
using (IRandomAccessStream readStream = await infoStorageText.OpenAsync(FileAccessMode.Read))
{
using (DataReader dataReader = new DataReader(readStream))
{
UInt64 size = readStream.Size;
if (size <= UInt32.MaxValue)
{
await dataReader.LoadAsync(sizeof(Int32));
Int32 stringSize = dataReader.ReadInt32();
await dataReader.LoadAsync((UInt32)stringSize);
string fileContent = dataReader.ReadString((uint)stringSize);
string[] splitString = fileContent.Split('\n');
LoginInfo.Type = splitString[0].Split(':')[0] == "type" ? splitString[0].Split(':')[1] : splitString[1].Split(':')[1];
LoginInfo.NickName = splitString[1].Split(':')[0] == "nickname" ? splitString[1].Split(':')[1] : splitString[0].Split(':')[1];
await PageInit.homePage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
PageInit.homePage.SetInfo(LoginInfo.Type, LoginInfo.NickName);
});
}
else
{
// OutputTextBlock.Text = "文件 " + file.Name + " 太大,不能再单个数据块中读取";
}
}
}
}
catch (Exception err)
{
infoStorageText = null;
}
if (infoStorageText == null)
{
//.........这里部分代码省略.........
示例13: Listener_ConnectionReceived
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
DataReader reader = new DataReader(args.Socket.InputStream);
reader.ByteOrder = ByteOrder.LittleEndian; //WTF Microsoft ?
try
{
while (true)
{
capture.GetFrame();
// Read first 4 bytes (length of the subsequent string).
uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
if (sizeFieldCount != sizeof(uint))
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
int actualStringLength = reader.ReadInt32();
//System.Diagnostics.Debug.WriteLine("Expecting " + actualStringLength + " bytes from socket");
byte[] data = new byte[actualStringLength];
sizeFieldCount = await reader.LoadAsync((uint)actualStringLength);
reader.ReadBytes(data);
//System.Diagnostics.Debug.WriteLine("read " + sizeFieldCount + " bytes from socket");
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,() =>
{
WriteableBitmap bm = new WriteableBitmap((int)Preview.Width, (int)Preview.Height);
data.AsBuffer().CopyTo(bm.PixelBuffer);
Preview.Source = bm;
});
// Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal
// the text back to the UI thread.
//NotifyUserFromAsyncThread(
// String.Format("Received data: bytes {0} frame {1}", actualStringLength, ++frameCounter));
}
}
catch (Exception exception)
{
// If this is an unknown status it means that the error is fatal and retry will likely fail.
if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
{
throw;
}
NotifyUserFromAsyncThread(exception.ToString());
}
}
示例14: ReadMediaFileAsync
private async Task ReadMediaFileAsync(DataReader reader)
{
//a media file will always start with an int32 containing the file length
await reader.LoadAsync(sizeof(int));
int messageLength = reader.ReadInt32();
Debug.WriteLine("Message Length " + messageLength);
_totalBytesRead = 0;
uint bytesRead = 0;
IBuffer readBuffer = new Windows.Storage.Streams.Buffer(MAX_PACKET_SIZE);
// read as many blocks as are in the incoming stream - this prevents blocks getting dropped
do
{
await reader.LoadAsync(sizeof(int));
int partNumber = reader.ReadInt32();
Debug.WriteLine("Part " + partNumber);
readBuffer = await _socket.InputStream.ReadAsync(readBuffer, MAX_PACKET_SIZE,
InputStreamOptions.Partial);
bytesRead = readBuffer.Length;
Debug.WriteLine("Bytes read " + bytesRead);
if (bytesRead > 0)
{
_incomingStream.WriteAsync(readBuffer).GetResults();
_totalBytesRead += bytesRead;
}
Debug.WriteLine("Total bytes read: " + _totalBytesRead);
}
while (_totalBytesRead < messageLength);
Debug.WriteLine("Incoming stream length " + _incomingStream.Size);
if (_totalBytesRead >= messageLength)
{
if (_writer == null)
{
_writer = new DataWriter(_socket.OutputStream);
}
_writer.WriteUInt16((UInt16)MessageType.Ready);
await _writer.StoreAsync();
messageLength = 0;
}
}
示例15: LoadQueueInternalAsync
private static async Task LoadQueueInternalAsync(IotHubClient client)
{
System.Collections.Generic.Queue<DataPoint> tmp = new System.Collections.Generic.Queue<DataPoint>();
try
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile file = await storageFolder.GetFileAsync(FILE_NAME);
var stream = await file.OpenAsync(FileAccessMode.ReadWrite);
ulong size = stream.Size;
using (var inputStream = stream.GetInputStreamAt(0))
{
using (var dataReader = new DataReader(inputStream))
{
uint numBytesLoaded = await dataReader.LoadAsync((uint)size);
int count = dataReader.ReadInt32();
for (int i = 0; i < count; i++)
{
DataPoint p = new DataPoint();
p.Read(dataReader);
tmp.Enqueue(p);
}
}
}
stream.Dispose();
lock (client.thisLock)
{
client.queue.Clear();
client.queue = null;
client.queue = new System.Collections.Generic.Queue<DataPoint>(tmp);
}
}
catch (Exception) { }
}