本文整理汇总了C#中Windows.Storage.Streams.DataReader.ReadBuffer方法的典型用法代码示例。如果您正苦于以下问题:C# DataReader.ReadBuffer方法的具体用法?C# DataReader.ReadBuffer怎么用?C# DataReader.ReadBuffer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Storage.Streams.DataReader
的用法示例。
在下文中一共展示了DataReader.ReadBuffer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ConvertToRandomAccessStream
public static async Task<IRandomAccessStream> ConvertToRandomAccessStream(Stream source)
{
Stream streamToConvert = null;
if (!source.CanRead)
throw new Exception("The source cannot be read.");
if (!source.CanSeek)
{
var memStream = new MemoryStream();
await source.CopyToAsync(memStream);
streamToConvert = memStream;
}
else
{
streamToConvert = source;
}
var reader = new DataReader(streamToConvert.AsInputStream());
streamToConvert.Position = 0;
await reader.LoadAsync((uint) streamToConvert.Length);
var buffer = reader.ReadBuffer((uint) streamToConvert.Length);
var randomAccessStream = new InMemoryRandomAccessStream();
var outputStream = randomAccessStream.GetOutputStreamAt(0);
await outputStream.WriteAsync(buffer);
await outputStream.FlushAsync();
return randomAccessStream;
}
示例2: AsRandomAccessStreamAsync
public async static Task<IRandomAccessStream> AsRandomAccessStreamAsync(this Stream stream)
{
Stream streamToConvert = null;
if (!stream.CanRead)
{
throw new Exception("Cannot read the source stream-");
}
if (!stream.CanSeek)
{
MemoryStream memoryStream = new MemoryStream();
await stream.CopyToAsync(memoryStream);
streamToConvert = memoryStream;
}
else
{
streamToConvert = stream;
}
DataReader dataReader = new DataReader(streamToConvert.AsInputStream());
streamToConvert.Position = 0;
await dataReader.LoadAsync((uint)streamToConvert.Length);
IBuffer buffer = dataReader.ReadBuffer((uint)streamToConvert.Length);
InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
IOutputStream outputstream = randomAccessStream.GetOutputStreamAt(0);
await outputstream.WriteAsync(buffer);
await outputstream.FlushAsync();
return randomAccessStream;
}
示例3: Decrypt
public async Task<string> Decrypt(IBuffer buffProtected, BinaryStringEncoding encoding)
{
try
{
// Create a DataProtectionProvider object.
DataProtectionProvider Provider = new DataProtectionProvider();
// Create a random access stream to contain the encrypted message.
InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream();
// Create a random access stream to contain the decrypted data.
InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream();
// Retrieve an IOutputStream object and fill it with the input (encrypted) data.
IOutputStream outputStream = inputData.GetOutputStreamAt(0);
DataWriter writer = new DataWriter(outputStream);
writer.WriteBuffer(buffProtected);
await writer.StoreAsync();
await outputStream.FlushAsync();
// Retrieve an IInputStream object from which you can read the input (encrypted) data.
IInputStream source = inputData.GetInputStreamAt(0);
// Retrieve an IOutputStream object and fill it with decrypted data.
IOutputStream dest = unprotectedData.GetOutputStreamAt(0);
await Provider.UnprotectStreamAsync(source, dest);
await dest.FlushAsync();
// Write the decrypted data to an IBuffer object.
DataReader reader2 = new DataReader(unprotectedData.GetInputStreamAt(0));
await reader2.LoadAsync((uint)unprotectedData.Size);
IBuffer buffUnprotectedData = reader2.ReadBuffer((uint)unprotectedData.Size);
// Convert the IBuffer object to a string using the same encoding that was
// used previously to conver the plaintext string (before encryption) to an
// IBuffer object.
String strUnprotected = CryptographicBuffer.ConvertBinaryToString(encoding, buffUnprotectedData);
// Return the decrypted data.
return strUnprotected;
}
catch (Exception ex)
{
App.Telemetry.TrackException(ex);
return "";
}
}
示例4: SaveBitmapAsync
public async Task SaveBitmapAsync(string albumFolder, uint size, string songPath)
{
var songFile = await StorageFile.GetFileFromPathAsync(songPath);
using (var thumbnail = await songFile.GetThumbnailAsync(ThumbnailMode.MusicView, size) ??
await songFile.GetThumbnailAsync(ThumbnailMode.VideosView, size))
{
if (thumbnail == null)
return;
var reader = new DataReader(thumbnail);
var fileLength = (uint)thumbnail.Size;
await reader.LoadAsync(fileLength);
var buffer = reader.ReadBuffer(fileLength);
var memStream = new InMemoryRandomAccessStream();
await memStream.WriteAsync(buffer);
await memStream.FlushAsync();
memStream.Seek(0);
await ApplicationData.Current.LocalFolder.CreateFolderAsync(AlbumArtFolderName(albumFolder), CreationCollisionOption.OpenIfExists);
var albumArtFileName = AlbumArtFileName(albumFolder, size);
var outputFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(albumArtFileName, CreationCollisionOption.ReplaceExisting);
// http://social.msdn.microsoft.com/Forums/windowsapps/en-US/1dda3a15-d299-40e0-b668-ec690a683f6e/how-to-resize-an-image-as-storagefile?forum=winappswithcsharp
var decoder = await BitmapDecoder.CreateAsync(memStream);
var transform = new BitmapTransform { ScaledHeight = size, ScaledWidth = size };
var pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Rgba8,
BitmapAlphaMode.Straight,
transform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.DoNotColorManage);
using (var destinationStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
{
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, size, size, 96, 96, pixelData.DetachPixelData());
await encoder.FlushAsync();
}
}
}
示例5: WriteFileAsync
/// <summary>
/// Write the contents of stream to filename in the cache location. If a null stream is provided, the file is created with no contents.
/// </summary>
/// <param name="stream">Content to be written to file</param>
/// <param name="filename">Name of the file to be written in cache location</param>
private static async Task WriteFileAsync(Stream stream, string filename)
{
// Prepare output file stream
StorageFolder parent = GetCacheFolder();
StorageFile file = null;
try
{
file = await parent.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
}
catch (Exception)
{
}
if (file != null && stream != null)
{
// Prepare input image stream
IInputStream inStream = stream.AsInputStream();
DataReader reader = new DataReader(inStream);
IRandomAccessStream fileStream = null;
try
{
fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);
// Buffered write to file
await reader.LoadAsync(1024);
while (reader.UnconsumedBufferLength > 0)
{
await fileStream.WriteAsync(reader.ReadBuffer(reader.UnconsumedBufferLength));
await reader.LoadAsync(1024);
}
}
catch (Exception)
{
}
finally
{
if (fileStream != null)
{
fileStream.FlushAsync();
}
}
inStream.Dispose();
}
}
示例6: UnprotectAsyncBuffer_Click
private async void UnprotectAsyncBuffer_Click(object sender, RoutedEventArgs e)
{
string outputStr = "";
if (m_protectedStream != null)
{
IInputStream source = m_protectedStream.GetInputStreamAt(0);
m_unprotectedStream = new InMemoryRandomAccessStream();
await DataProtectionManager.UnprotectStreamAsync(source,
m_unprotectedStream
);
var unprotectedReader = new DataReader(m_unprotectedStream.GetInputStreamAt(0));
await unprotectedReader.LoadAsync((uint)m_unprotectedStream.Size);
IBuffer unprotectedStreamBuffer = unprotectedReader.ReadBuffer((uint)m_unprotectedStream.Size);
outputStr += "\n UnProtected Stream buffer:" +
CryptographicBuffer.EncodeToHexString(unprotectedStreamBuffer);
rootPage.NotifyUser(outputStr, NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Please protect a stream to unprotect", NotifyType.ErrorMessage);
}
}
示例7: SaveTemporaryPhotoAsync
private async Task<StorageFile> SaveTemporaryPhotoAsync(FilteredPhotoModel photo)
{
var filename = Application.Current.Resources["PhotoSaveTemporaryFilename"] as string;
var folder = ApplicationData.Current.TemporaryFolder;
var task = folder.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting).AsTask();
task.Wait();
var file = task.Result;
CachedFileManager.DeferUpdates(file);
using (var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
using (var photoStream = await photo.GetFilteredPhotoAsync())
using (var reader = new DataReader(photoStream))
using (var writer = new DataWriter(fileStream))
{
await reader.LoadAsync((uint)photoStream.Size);
var buffer = reader.ReadBuffer((uint)photoStream.Size);
writer.WriteBuffer(buffer);
await writer.StoreAsync();
await writer.FlushAsync();
}
var status = await CachedFileManager.CompleteUpdatesAsync(file);
if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
{
return file;
}
else
{
return null;
}
}
示例8: GetUrlsFromPDF
private async Task GetUrlsFromPDF(IRandomAccessStream stream)
{
using (var dataReader = new DataReader(stream.GetInputStreamAt(0)))
{
uint u = await dataReader.LoadAsync((uint)stream.Size);
IBuffer buffer = dataReader.ReadBuffer(u);
GetPDFLinks(buffer);
TimeSpan t = new TimeSpan(0, 0, 1);
await Task.Delay(t);
}
}
示例9: 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);
}
//.........这里部分代码省略.........
示例10: GetThumbnailStreamAsync
private async Task<IRandomAccessStream> GetThumbnailStreamAsync()
{
#if DEBUG
System.Diagnostics.Debug.WriteLine("GetThumbnailStreamAsync invoked " + this.GetHashCode());
#endif
var maximumSide = (int)Windows.UI.Xaml.Application.Current.Resources["ThumbnailSide"];
var orientation = await GetPhotoOrientationAsync();
var orientationValue = orientation.HasValue ? orientation.Value : PhotoOrientation.Unspecified;
#if WINDOWS_PHONE_APP
// TODO Getting platform thumbnails is currently broken in the WP8.1 preview SDK,
// thus generating thumbnails from the large original photos. Change to platform
// thumbnails again when platform is live & fine.
var size = await GetPhotoResolutionAsync();
using (var stream = await GetPhotoAsync())
{
return await ResizeStreamAsync(stream, new Size(maximumSide, maximumSide), orientationValue);
}
#else
using (var stream = await _file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView))
{
if (stream.ContentType == "image/jpeg")
{
if (stream.OriginalWidth <= maximumSide || stream.OriginalHeight <= maximumSide)
{
using (var memoryStream = new InMemoryRandomAccessStream())
{
using (var reader = new DataReader(stream))
using (var writer = new DataWriter(memoryStream))
{
await reader.LoadAsync((uint)stream.Size);
var buffer = reader.ReadBuffer((uint)stream.Size);
writer.WriteBuffer(buffer);
await writer.StoreAsync();
await writer.FlushAsync();
return memoryStream.CloneStream();
}
}
}
else
{
return await ResizeStreamAsync(stream, new Size(maximumSide, maximumSide), orientationValue);
}
}
else
{
using (var preview = await GetPreviewAsync())
{
return await ResizeStreamAsync(preview, new Size(maximumSide, maximumSide), orientationValue);
}
}
}
#endif
}
示例11: GetReceiptAsync
private static async Task<string> GetReceiptAsync(string productId)
{
var encryptedFilename = CipherEncryption(productId);
var encodedFileName = Convert.ToBase64String(encryptedFilename.ToArray());
var encodedAndEscapedFilename = encodedFileName.Replace('/', '-');
//var folder = ApplicationData.Current.RoamingFolder;
var folder = ApplicationData.Current.RoamingFolder;
if (folder == null) return "NoReceipt";
folder = await folder.CreateFolderAsync("Receipts", CreationCollisionOption.OpenIfExists);
try
{
var file = await folder.GetFileAsync(encodedAndEscapedFilename + ".pmd");
var stream = await file.OpenAsync(FileAccessMode.Read);
var dataReader = new DataReader(stream.GetInputStreamAt(0));
uint u = await dataReader.LoadAsync((uint)stream.Size);
IBuffer buffEncrypted = dataReader.ReadBuffer(u);
dataReader.DetachStream();
stream.Dispose();
stream = null;
var receipt = CipherDecryption(buffEncrypted);
if (productId.Contains("subscritpion") && DownloadManager.ReceiptExpired(receipt))
{
await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
return "NoReceipt";
}
return receipt;
}
catch (Exception)
{
return "NoReceipt";
}
}
示例12: Recive
public static async Task<string> Recive(StreamSocket streamSocket, List<string> orstarts, List<string> orends, List<string> andstarts, List<string> andends)
{
string returnString = string.Empty;
try
{
using (var dataReader = new DataReader(streamSocket.InputStream))
{
dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
dataReader.InputStreamOptions = InputStreamOptions.Partial;
var end = false;
while (!end && await dataReader.LoadAsync(64000) != 0)
{
string readString;
var buffer = dataReader.ReadBuffer(dataReader.UnconsumedBufferLength);
using (var dr = DataReader.FromBuffer(buffer))
{
var bytes1251 = new Byte[buffer.Length];
dr.ReadBytes(bytes1251);
readString = Encoding.GetEncoding("UTF-8").GetString(bytes1251, 0, bytes1251.Length);
}
if (!string.IsNullOrEmpty(readString))
returnString += readString;
if (readString == null)
{
end = true;
}
else if (orstarts.FirstOrDefault(o => returnString.StartsWith(o)) != null)
{
end = true;
}
else if (orends.FirstOrDefault(o => returnString.EndsWith(o)) != null)
{
end = true;
}
else if (andstarts.FirstOrDefault(o => returnString.StartsWith(o)) != null
&& andends.FirstOrDefault(o => returnString.EndsWith(o)) != null)
{
end = true;
}
}
dataReader.DetachStream();
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
returnString = string.Empty;
}
return returnString;
}
示例13: SaveStreamTo3MF
private async static Task<bool> SaveStreamTo3MF(Windows.Storage.Streams.IRandomAccessStream stream)
{
// set back
stream.Seek(0);
using (var dataReader = new Windows.Storage.Streams.DataReader(stream))
{
var dataLoad = await dataReader.LoadAsync((uint)stream.Size);
if (dataLoad > 0)
{
var buffer = dataReader.ReadBuffer((uint)stream.Size);
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
var outputfile = await localFolder.CreateFileAsync("output.3mf", CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteBufferAsync(outputfile, buffer);
var options = new Windows.System.LauncherOptions();
options.TargetApplicationPackageFamilyName = "Microsoft.3DBuilder_8wekyb3d8bbwe";
}
}
return true;
}
示例14: mediaalbumart
public async void mediaalbumart()
{
try
{
StorageFile media =
await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(futurelocation);
string filename = "thumbnail" + ".png";
//var ThumbUri = new Uri("ms-appdata:///local/" + filename);
// Store the file thumbnail in local applicatin storage
using (
StorageItemThumbnail storageItemThumbnail =
await media.GetThumbnailAsync(ThumbnailMode.SingleItem, 200, ThumbnailOptions.ResizeThumbnail))
using (IInputStream inputStreamAt = storageItemThumbnail.GetInputStreamAt(0))
using (var dataReader = new DataReader(inputStreamAt))
{
uint u = await dataReader.LoadAsync((uint)storageItemThumbnail.Size);
IBuffer readBuffer = dataReader.ReadBuffer(u);
var tempFolder = ApplicationData.Current.LocalFolder;
var imageFile = await tempFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream randomAccessStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite))
using (IOutputStream outputStreamAt = randomAccessStream.GetOutputStreamAt(0))
{
await outputStreamAt.WriteAsync(readBuffer);
await outputStreamAt.FlushAsync();
}
}
MediaControl.AlbumArt = new Uri("ms-appdata:///local/" + filename);
}
catch
{
// ErrorCorrecting("015");
}
}
示例15: albumart
public async void albumart(StorageFile fil)
{
using (StorageItemThumbnail storageItemThumbnail = await fil.GetThumbnailAsync(ThumbnailMode.SingleItem, 200, ThumbnailOptions.ResizeThumbnail))
using (IInputStream inputStreamAt = storageItemThumbnail.GetInputStreamAt(0))
using (var dataReader = new DataReader(inputStreamAt))
{
uint u = await dataReader.LoadAsync((uint)storageItemThumbnail.Size);
IBuffer readBuffer = dataReader.ReadBuffer(u);
var tempFolder = ApplicationData.Current.RoamingFolder;
try
{
var imageFile = await tempFolder.CreateFileAsync(fil.DisplayName + ".png", CreationCollisionOption.OpenIfExists);
using (IRandomAccessStream randomAccessStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite))
using (IOutputStream outputStreamAt = randomAccessStream.GetOutputStreamAt(0))
{
await outputStreamAt.WriteAsync(readBuffer);
await outputStreamAt.FlushAsync();
}
}
catch
{
// ErrorCorrecting("013");
}
}
}