本文整理汇总了C#中Windows.Storage.Streams.DataWriter.WriteBuffer方法的典型用法代码示例。如果您正苦于以下问题:C# DataWriter.WriteBuffer方法的具体用法?C# DataWriter.WriteBuffer怎么用?C# DataWriter.WriteBuffer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Storage.Streams.DataWriter
的用法示例。
在下文中一共展示了DataWriter.WriteBuffer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ProccesImage
public async void ProccesImage(StorageFile imageFile)
{
var data = await FileIO.ReadBufferAsync(imageFile);
// create a stream from the file
var ms = new InMemoryRandomAccessStream();
var dw = new DataWriter(ms);
dw.WriteBuffer(data);
await dw.StoreAsync();
ms.Seek(0);
// find out how big the image is, don't need this if you already know
var bm = new BitmapImage();
await bm.SetSourceAsync(ms);
// create a writable bitmap of the right size
var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);
ms.Seek(0);
// load the writable bitpamp from the stream
await wb.SetSourceAsync(ms);
Bitmap bmp = (Bitmap)wb;
//var filter1 = Grayscale.CommonAlgorithms.BT709;
//bmp = filter1.Apply(bmp);
wb = (WriteableBitmap)bmp;
var file = await this.WriteableBitmapToStorageFile(wb, FileFormat.Jpeg);
}
示例2: Quadraliteral
public async void Quadraliteral(StorageFile file, IList<WF.Point> points)
{
var data = await FileIO.ReadBufferAsync(file);
OpencvImageProcess opencv = new OpencvImageProcess();
// create a stream from the file
var ms = new InMemoryRandomAccessStream();
var dw = new DataWriter(ms);
dw.WriteBuffer(data);
await dw.StoreAsync();
ms.Seek(0);
// find out how big the image is, don't need this if you already know
var bm = new BitmapImage();
await bm.SetSourceAsync(ms);
// create a writable bitmap of the right size
var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);
ms.Seek(0);
// load the writable bitpamp from the stream
await wb.SetSourceAsync(ms);
Bitmap bmp = (Bitmap)wb;
var wb1 = opencv.GetImageCorners(wb);
wb1.Invalidate();
//wb.Invalidate();
// define quadrilateral's corners
//List<IntPoint> corners = new List<IntPoint>();
//foreach (var point in points)
//{
// corners.Add(new IntPoint((int)point.X, (int)point.Y));
//}
//// create filter
//var filter =
// new SimpleQuadrilateralTransformation(corners);
//// apply the filter
//Bitmap newImage = filter.Apply(bmp);
//wb = (WriteableBitmap)newImage;
var f = await this.WriteableBitmapToStorageFile(wb1, FileFormat.Jpeg);
}
示例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: GetRandomStream
public async Task<IRandomAccessStream> GetRandomStream()
{
if (Data == null)
{
return null;
}
else
{
var buffer = this.GetBuffer();
InMemoryRandomAccessStream inStream = new InMemoryRandomAccessStream();
DataWriter datawriter = new DataWriter(inStream.GetOutputStreamAt(0));
datawriter.WriteBuffer(buffer, 0, buffer.Length);
await datawriter.StoreAsync();
return inStream;
}
}
示例5: Encrypt
public async Task<IBuffer> Encrypt(string descriptor, string strMsg, BinaryStringEncoding encoding)
{
// Create a DataProtectionProvider object for the specified descriptor.
DataProtectionProvider Provider = new DataProtectionProvider(descriptor);
// Convert the input string to a buffer.
IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);
// Create a random access stream to contain the plaintext message.
InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream();
// Create a random access stream to contain the encrypted message.
InMemoryRandomAccessStream protectedData = new InMemoryRandomAccessStream();
// Retrieve an IOutputStream object and fill it with the input (plaintext) data.
IOutputStream outputStream = inputData.GetOutputStreamAt(0);
DataWriter writer = new DataWriter(outputStream);
writer.WriteBuffer(buffMsg);
await writer.StoreAsync();
await outputStream.FlushAsync();
// Retrieve an IInputStream object from which you can read the input data.
IInputStream source = inputData.GetInputStreamAt(0);
// Retrieve an IOutputStream object and fill it with encrypted data.
IOutputStream dest = protectedData.GetOutputStreamAt(0);
await Provider.ProtectStreamAsync(source, dest);
await dest.FlushAsync();
//Verify that the protected data does not match the original
DataReader reader1 = new DataReader(inputData.GetInputStreamAt(0));
DataReader reader2 = new DataReader(protectedData.GetInputStreamAt(0));
await reader1.LoadAsync((uint)inputData.Size);
await reader2.LoadAsync((uint)protectedData.Size);
IBuffer buffOriginalData = reader1.ReadBuffer((uint)inputData.Size);
IBuffer buffProtectedData = reader2.ReadBuffer((uint)protectedData.Size);
if (CryptographicBuffer.Compare(buffOriginalData, buffProtectedData))
{
throw new Exception("ProtectStreamAsync returned unprotected data");
}
// Return the encrypted data.
return buffProtectedData;
}
示例6: sendMail
public async void sendMail(string strSendTo,string strContent , Boolean hasPicture)
{
HostName hostName = new HostName(hostIP);
StreamSocket socket = new StreamSocket();
List<string[]> storeList = new List<string[]>();
try
{
await socket.ConnectAsync(hostName, port);
}
catch (Exception exception)
{
if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
{
throw;
}
}
StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Temp");
StorageFile pic = await folder.GetFileAsync("MyPainter.png");
IBuffer buffer = await FileIO.ReadBufferAsync(pic);
DataWriter writer = new DataWriter(socket.OutputStream);
writer.WriteUInt32(writer.MeasureString(strSendTo));
writer.WriteString(strSendTo);
writer.WriteUInt32(writer.MeasureString(strContent));
writer.WriteString(strContent);
if (hasPicture)
{
writer.WriteUInt32((uint)buffer.Length);
writer.WriteBuffer(buffer);
}
else
{
writer.WriteUInt32(0);
writer.WriteString("");
}
await writer.StoreAsync();
writer.DetachStream();
writer.Dispose();
socket.Dispose();
}
示例7: SavePhotoAsync
private static async Task<StorageFile> SavePhotoAsync(FilteredPhotoModel photo, StorageFile file)
{
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: receive_file
public override async void receive_file(String devicename, String add, int not)
{
try
{
_httpurl = new Uri(add);
_httpprogress = new Progress<HttpProgress>(ProgressHandler);
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("GET"), _httpurl);
HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
_httpclient = new HttpClient(filter);
_cancel_token_source = new CancellationTokenSource();
_cancel_token = _cancel_token_source.Token;
scan_network_speed();
_stopwatch.Start();
_httpresponse = await _httpclient.SendRequestAsync(request).AsTask(_cancel_token, _httpprogress);
StorageFolder folder = KnownFolders.PicturesLibrary;
StorageFile file = await folder.CreateFileAsync(this.filepath, CreationCollisionOption.ReplaceExisting);
IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.ReadWrite);
IOutputStream filewriter = filestream.GetOutputStreamAt(0);
_datawriter = new DataWriter(filewriter);
_timer.Cancel();
_transferspeed /= 1024;
_message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), " kB/s");
this.callback.on_transfer_speed_change(_message, this.results);
this.main_view.text_to_logs(_message.Replace("\t", " "));
_stopwatch.Stop();
_buffer = await _httpresponse.Content.ReadAsBufferAsync();
_datawriter.WriteBuffer(_buffer);
await _datawriter.StoreAsync();
_datawriter.Dispose();
filewriter.Dispose();
filestream.Dispose();
_httpresponse.Content.Dispose();
_httpresponse.Dispose();
_httpclient.Dispose();
_message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
this.callback.on_file_received(_message, this.results);
this.main_view.text_to_logs(_message.Replace("\t", " "));
}
catch (Exception e)
{
append_error_tolog(e, _stopwatch.Elapsed, "");
}
}
示例9: getsdpRecordBlob
private static IBuffer getsdpRecordBlob(string serviceName, string serviceDescriptor)
{
DataWriter helperWriter = new DataWriter();
DataWriter NameWriter = new DataWriter();
// The length of the UTF-8 encoded string.
NameWriter.WriteByte((byte)serviceName.Length);
// The UTF-8 encoded string.
NameWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
NameWriter.WriteString(serviceName);
// UINT16 (0x09) value = 0x0100 [ServiceName]
helperWriter.WriteByte(0x09);
helperWriter.WriteByte(0x01);
helperWriter.WriteByte(0x00);
IBuffer serviceNameBuf = NameWriter.DetachBuffer();
helperWriter.WriteByte(0x25); //TextString(0x25)
helperWriter.WriteByte((byte)serviceNameBuf.Length);
helperWriter.WriteBuffer(serviceNameBuf);
DataWriter DescriptorWriter = new DataWriter();
// The length of the UTF-8 encoded string.
DescriptorWriter.WriteByte((byte)serviceDescriptor.Length);
// The UTF-8 encoded string.
DescriptorWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
DescriptorWriter.WriteString(serviceDescriptor);
// UINT16 (0x09) value = 0x0101 [ServiceDescription]
helperWriter.WriteByte(0x09);
helperWriter.WriteByte(0x01);
helperWriter.WriteByte(0x01);
IBuffer descriptorBuf = DescriptorWriter.DetachBuffer();
helperWriter.WriteByte(0x25); //TextString(0x25)
helperWriter.WriteByte((byte)descriptorBuf.Length);
helperWriter.WriteBuffer(descriptorBuf);
DataWriter SdpRecordWriter = new DataWriter();
SdpRecordWriter.WriteByte(0x35);
IBuffer dataBuf = helperWriter.DetachBuffer();
SdpRecordWriter.WriteByte((byte)dataBuf.Length);
SdpRecordWriter.WriteBuffer(dataBuf);
return SdpRecordWriter.DetachBuffer();
}
示例10: 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;
}
}
示例11: send_file
public override async void send_file(String devicename, String bluid, int not)
{
try {
_stopwatch.Start();
PeerFinder.AllowBluetooth = true;
PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{" + bluid + "}";
var peers = await PeerFinder.FindAllPeersAsync();
foreach (var p in peers)
{
if (p.DisplayName.Equals(devicename))
{
_peer_info = p;
break;
}
}
_bluetooth_client = new StreamSocket();
if (_peer_info.ServiceName.Equals(""))
{
await _bluetooth_client.ConnectAsync(_peer_info.HostName, "{" + bluid + "}");
}
else
{
await _bluetooth_client.ConnectAsync(_peer_info.HostName, _peer_info.ServiceName);
}
StorageFolder folder = KnownFolders.PicturesLibrary;
StorageFile file = await folder.GetFileAsync(this.filepath);
IRandomAccessStreamWithContentType filestream = await file.OpenReadAsync();
_length = (uint)filestream.Size;
_ibuffer = new Windows.Storage.Streams.Buffer(_length);
_datareader = new DataReader(filestream);
await _datareader.LoadAsync(_length);
_ibuffer = _datareader.ReadBuffer(_length);
_datawriter = new DataWriter(_bluetooth_client.OutputStream);
_datawriter.WriteBuffer(_ibuffer);
await _datawriter.StoreAsync();
filestream.Dispose();
_datareader.Dispose();
_datawriter.Dispose();
_datareader = new DataReader(_bluetooth_client.InputStream);
_datareader.InputStreamOptions = InputStreamOptions.Partial;
scan_received_acks();
while (true)
{
uint count = await _datareader.LoadAsync(4);
byte[] ack = new byte[count];
_datareader.ReadBytes(ack);
_counter_all_acks += BitConverter.ToInt32(ack, 0);
if ((uint)_counter_all_acks == _length) break;
}
_datareader.Dispose();
_bluetooth_client.Dispose();
_message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
this.callback.on_file_received(_message, this.results);
this.main_view.text_to_logs(_message.Replace("\t", " "));
_ack_timer.Cancel();
_stopwatch.Stop();
}
catch (Exception e)
{
append_error_tolog(e, _stopwatch.Elapsed, devicename);
}
}
示例12: ConvertToNfcMessageAsync
/// <summary>
/// Function to format provisioning package into chunk data with a NfcProvHeader prefix.
/// </summary>
/// <param name="content">IBuffer to the provisioning package content.</param>
/// <param name="device">ProximityDevice instance passed in the messageHandler.</param>
/// <param name="messageHandler">Delegate handler to consume the chunk data.</param>
private static async Task ConvertToNfcMessageAsync(IBuffer content, ProximityDevice device, Func<ProximityDevice, IBuffer, CancellationToken, Task> messageHandlerAsync, CancellationToken ct)
{
var maxMessageSize = device.MaxMessageBytes;
var headerSize = GetNfcProvHeaderSize();
uint chunkSize = maxMessageSize - (uint)headerSize;
// Calculate the chunk count needed for this transfer.
uint chunks = content.Length / chunkSize;
if ((content.Length % chunkSize) > 0)
{
++chunks;
}
// Loop and compose the payload per chunk data.
for (uint posToRead = 0; posToRead < content.Length; posToRead += chunkSize)
{
var dataWriter = new DataWriter();
var header = new NfcProvHeader();
header.version = NFC_PROV_MESSAGE_CURRENT_VERSION; // Currently the supported version is 0x00.
header.leading = NFC_PROV_MESSAGE_LEADING_BYTE; // The leading byte should be always 0xFF.
header.index = (byte)(posToRead / chunkSize); // To specify which chunk to this message.
header.total = (byte)chunks; // To specify the total message count for this transfer.
int bufferSizeToAlloc = (int)maxMessageSize;
if (header.total == (header.index + 1))
{
bufferSizeToAlloc = headerSize + (int)(content.Length - posToRead);
}
// Write the prefix first and the chunk data of the provisioning package.
dataWriter.WriteBytes(GetBytes(header));
dataWriter.WriteBuffer(content, posToRead, (uint)(bufferSizeToAlloc - headerSize));
// Invoke the delegate handler to handle the NFC message.
await messageHandlerAsync(device, dataWriter.DetachBuffer(), ct);
}
}
示例13: BtnSaveToFile_Click
/// <summary>
/// this is used when the user selects save to file
/// </summary>
/// <remarks>
/// to implement this, we will need to create and instance of the save file picker
/// then write the output stream into a file
/// </remarks>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void BtnSaveToFile_Click(object sender, RoutedEventArgs e)
{
string text = this.tbData.Text;
// select the file to save this data to
FileSavePicker savePicker = new FileSavePicker();
savePicker.DefaultFileExtension = ".wav";
// this is the only type available
savePicker.FileTypeChoices.Add("Audio file", new List<string>() { ".wav" });
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
this.btnSaveToFile.IsEnabled = false;
// create the data stream
SpeechSynthesisStream synthesisStream;
try
{
synthesisStream = await this.synthesizer.SynthesizeSsmlToStreamAsync(text);
}
catch (Exception)
{
synthesisStream = null;
this.btnSaveToFile.IsEnabled = true;
}
if (synthesisStream == null)
{
MessageDialog dialog = new MessageDialog("unable to synthesize text");
await dialog.ShowAsync();
return;
}
// open the output stream
Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(4096);
IRandomAccessStream writeStream = (IRandomAccessStream)await file.OpenAsync(FileAccessMode.ReadWrite);
IOutputStream outputStream = writeStream.GetOutputStreamAt(0);
DataWriter dataWriter = new DataWriter(outputStream);
// copy the stream data into the file
while (synthesisStream.Position < synthesisStream.Size)
{
await synthesisStream.ReadAsync(buffer, 4096, InputStreamOptions.None);
dataWriter.WriteBuffer(buffer);
}
// close the data file streams
dataWriter.StoreAsync().AsTask().Wait();
outputStream.FlushAsync().AsTask().Wait();
this.btnSaveToFile.IsEnabled = true;
}
}
示例14: DownloadFileAsync
public async Task<bool> DownloadFileAsync(string ftpFile, string localFile, Boolean resume)
{
CheckLoggedIn();
var response = await ExecuteAsync("TYPE I");
response.CheckReturnCode(200);
Debug.WriteLine("Downloading file " + ftpFile + " from " + HostName + "/" + WorkingDirectory, "FtpClient");
if (string.IsNullOrEmpty(localFile))
{
localFile = ftpFile;
}
var tempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(localFile, CreationCollisionOption.OpenIfExists);
var tempStream = await tempFile.OpenStreamForWriteAsync();
StreamSocket dataSocket = await OpenSocketForTransferAsync();
ulong resumeOffset = 0;
if (resume)
{
var prop = await tempFile.GetBasicPropertiesAsync();
resumeOffset = prop.Size;
if (resumeOffset > 0)
{
response = await ExecuteAsync("REST " + resumeOffset);
if (response.ReturnCode != 350)
{
resumeOffset = 0;
Debug.WriteLine("Resuming not supported:" + response.Message, "FtpClient");
}
else
{
Debug.WriteLine("Resuming at offset " + resumeOffset, "FtpClient");
tempStream.Seek(Convert.ToInt64(resumeOffset), SeekOrigin.Begin);
}
}
}
response = await ExecuteAsync("RETR " + ftpFile);
response.CheckReturnCode(150, 125);
var reader = new DataReader(dataSocket.InputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;
var writer = new DataWriter(tempStream.AsOutputStream());
DateTime timeout = DateTime.Now.AddSeconds(TimeOut);
while (timeout > DateTime.Now)
{
var count = await reader.LoadAsync(BUFFER_SIZE);
var bytes = reader.ReadBuffer(count);
writer.WriteBuffer(bytes);
await writer.StoreAsync();
if (count < BUFFER_SIZE)
{
break;
}
}
await tempStream.FlushAsync();
dataSocket.Dispose();
response = await ReadResponseAsync();
response.CheckReturnCode(226, 250);
var props = await tempFile.GetBasicPropertiesAsync();
var tempSize = props.Size;
var size = await GetFileSizeAsync(ftpFile);
if (tempSize != size)
return false;
var destFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(localFile, CreationCollisionOption.ReplaceExisting);
var destStream = await destFile.OpenStreamForWriteAsync();
tempStream.Seek(0, SeekOrigin.Begin);
await tempStream.CopyToAsync(destStream);
await destStream.FlushAsync();
await tempFile.DeleteAsync(StorageDeleteOption.PermanentDelete);
return true;
}
示例15: RotateImage
private async Task<StorageFile> RotateImage(int rotation, IStorageFile file)
{
var data = await FileIO.ReadBufferAsync(file);
var ms = new InMemoryRandomAccessStream();
var dw = new DataWriter(ms);
dw.WriteBuffer(data);
await dw.StoreAsync();
ms.Seek(0);
var bm = new BitmapImage();
await bm.SetSourceAsync(ms);
var wb = new WriteableBitmap(bm.PixelHeight, bm.PixelWidth);
ms.Seek(0);
await wb.SetSourceAsync(ms);
var rotated = wb.Rotate(rotation);
var result = await this.SaveCroppedImage(rotated);
return result;
}