当前位置: 首页>>代码示例>>C#>>正文


C# MemoryStream.ReadAsync方法代码示例

本文整理汇总了C#中System.IO.MemoryStream.ReadAsync方法的典型用法代码示例。如果您正苦于以下问题:C# MemoryStream.ReadAsync方法的具体用法?C# MemoryStream.ReadAsync怎么用?C# MemoryStream.ReadAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.MemoryStream的用法示例。


在下文中一共展示了MemoryStream.ReadAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: WritesMessage

        public async Task WritesMessage()
        {
            MemoryStream outputStream = new MemoryStream();

            MessageWriter messageWriter = 
                new MessageWriter(
                    outputStream,
                    this.messageSerializer);

            // Write the message and then roll back the stream to be read
            // TODO: This will need to be redone!
            await messageWriter.WriteMessage(Message.Event("testEvent", null));
            outputStream.Seek(0, SeekOrigin.Begin);

            string expectedHeaderString =
                string.Format(
                    Constants.ContentLengthFormatString,
                    ExpectedMessageByteCount);

            byte[] buffer = new byte[128];
            await outputStream.ReadAsync(buffer, 0, expectedHeaderString.Length);

            Assert.Equal(
                expectedHeaderString,
                Encoding.ASCII.GetString(buffer, 0, expectedHeaderString.Length));

            // Read the message
            await outputStream.ReadAsync(buffer, 0, ExpectedMessageByteCount);

            Assert.Equal(
                TestEventString,
                Encoding.UTF8.GetString(buffer, 0, ExpectedMessageByteCount));

            outputStream.Dispose();
        }
开发者ID:juvchan,项目名称:PowerShellEditorServices,代码行数:35,代码来源:MessageReaderWriterTests.cs

示例2: Get

        public async Task<HttpResponseMessage> Get(int width, int height, string bgColor, string fgColor)
        {
            var bg = GetColor(bgColor, Color.LightGray);
            var fg = GetColor(fgColor, Color.DarkGray);

            var result = new HttpResponseMessage(HttpStatusCode.OK);

            using (var ms = new MemoryStream())
            using (var img = await GetImageAsync($"{width} x {height}", width, height, bg, fg))
            {
                if (img == null)
                {
                    result.StatusCode = HttpStatusCode.BadRequest;
                    return result;
                }

                img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                var bytes = new byte[ms.Length];
                ms.Seek(0, SeekOrigin.Begin);
                await ms.ReadAsync(bytes, 0, bytes.Length);

                result.Content = new ByteArrayContent(bytes);
            }

            result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");

            return result;
        }
开发者ID:aghasilorsabyanmic,项目名称:MVCTeam1,代码行数:29,代码来源:ImageController.cs

示例3: WriteBufferToFile

        // todo refactor
        public async Task WriteBufferToFile(byte[] buffer, string path)
        {
            using (var fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            using (var memoryStream = new MemoryStream(buffer))
            {
                byte[] bytes = new byte[memoryStream.Length];
                await memoryStream.ReadAsync(bytes, 0, (int)memoryStream.Length);
                await fileStream.WriteAsync(bytes, 0, bytes.Length);
            };

        }
开发者ID:mathiasnohall,项目名称:Servanda,代码行数:12,代码来源:StreamHandler.cs

示例4: TestDownloadFileFromDriveAsync

 public async Task TestDownloadFileFromDriveAsync()
 {
     var env = await TestEnvironment.CreateSimpleAsync();
     var file = await env.GetFileByFullPathAsync("photos2015/info.txt");
     var stream = new MemoryStream();
     await env.Account.DownloadFileFromDriveAsync(file, stream, CancellationToken.None);
     stream.Seek(0, SeekOrigin.Begin);
     var buffer = new byte[stream.Length];
     await stream.ReadAsync(buffer, 0, buffer.Length);
     var content = Encoding.ASCII.GetString(buffer);
     Assert.AreEqual("Hello, World!", content);
 }
开发者ID:fiftin,项目名称:oblqo,代码行数:12,代码来源:AccountTest.cs

示例5: SaveAsync

		public async Task SaveAsync(Stream output, CancellationToken cancellationToken)
		{
			if (output == null) throw new ArgumentNullException(nameof(output));

			var buffer = new byte[64 * 1024];

			foreach (var file in Files)
			{
				using (var input = new MemoryStream(file))
				{
					int readBytes;
					while ((readBytes = await input.ReadAsync(buffer, 0, buffer.Length, cancellationToken)) != 0)
					{
						await output.WriteAsync(buffer, 0, readBytes, cancellationToken);
					}
				}
			}
		}
开发者ID:ppetrov,项目名称:Cchbc,代码行数:18,代码来源:ZipData.cs

示例6: ProcessRequestAsync

 public override async Task ProcessRequestAsync(HttpContext context)
 {
     System.Drawing.Bitmap myBitmap = null;
     MemoryStream objMemoryStream = null;
     try
     {
         var strImageFileName = context.Request.QueryString["ImageUrl"].ToString();
         var height = context.Request.QueryString["height"];
         var width = context.Request.QueryString["width"];
         //create callback handler
         var myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
         //creat BitMap object from image path passed in querystring
         myBitmap =
            new System.Drawing.Bitmap(
                context.Server.MapPath("~/Images/Users/" + strImageFileName));
         //create unit object for height and width. This is to convert parameter passed in differen unit like pixel, inch into generic unit.
         var widthUnit = System.Web.UI.WebControls.Unit.Parse(width);
         var heightUnit = System.Web.UI.WebControls.Unit.Parse(height);
         //Resize actual image using width and height paramters passed in querystring
         var myThumbnail = myBitmap.GetThumbnailImage(Convert.ToInt16(widthUnit.Value),
             Convert.ToInt16(heightUnit.Value), myCallback, IntPtr.Zero);
         //Create memory stream and save resized image into memory stream
         objMemoryStream = new System.IO.MemoryStream();
         myThumbnail.Save(objMemoryStream, System.Drawing.Imaging.ImageFormat.Png);
         //Declare byte array of size memory stream and read memory stream data into array
         var imageData = new byte[objMemoryStream.Length];
         objMemoryStream.Position = 0;
         await objMemoryStream.ReadAsync(imageData, 0, (int)objMemoryStream.Length);
         //send contents of byte array as response to client (browser)
         context.Response.BinaryWrite(imageData);
         myBitmap.Dispose();
     }
     catch
     {
         context.Response.End();
     }
     finally
     {
         if (objMemoryStream != null)
             objMemoryStream.Dispose();
         if (myBitmap != null)
             myBitmap.Dispose();
     }
 }
开发者ID:rabbal,项目名称:AspNetWebForms-Forum,代码行数:44,代码来源:ImageHandler.ashx.cs

示例7: Compress

        /// <summary>
        /// Compresses the specified source stream onto the destination stream.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="destination">The destination.</param>
        /// <returns>An async void.</returns>
        public virtual async Task<long> Compress(Stream source, Stream destination)
        {
            using (var mem = new MemoryStream())
            {
                using (var gzip = this.CreateCompressionStream(mem))
                {
                    await source.CopyToAsync(gzip);
                }

                mem.Position = 0;

                var compressed = new byte[mem.Length];
                await mem.ReadAsync(compressed, 0, compressed.Length);

                var outStream = new MemoryStream(compressed);
                await outStream.CopyToAsync(destination);

                return mem.Length;
            }
        }
开发者ID:SneakyMax,项目名称:Microsoft.AspNet.WebApi.MessageHandlers.Compression,代码行数:26,代码来源:BaseCompressor.cs

示例8: ReadAsync

        /// <summary>
        /// Reads incoming data, and puts it in the buffer for processing.
        /// </summary>
        public async Task ReadAsync()
        {
            var readBuffer = new MemoryStream(BUFFER_SIZE);

            //Set up buffers to store incoming data
            byte[] inputBuffer = new byte[BUFFER_SIZE];
            int bytesRead = 0;

            //Read packet from stream
            bytesRead = await networkStream.ReadAsync(inputBuffer, 0, inputBuffer.Length);

            //Add read data to the read buffer
            await readBuffer.WriteAsync(inputBuffer, 0, bytesRead);

            //Determine if there are terminators in the buffer, because that would signify
            //at least 1 full record. 
            var readBufferArray = readBuffer.ToArray();
            var terminatorStrings = readBufferArray
                .Select((v, i) => new { Value = v, Index = i })
                .Where(a => a.Index < readBufferArray.Length - 1
                    && a.Value == LF
                    && readBufferArray[a.Index + 1] == CR).ToList();

            //Find all full messages in the readBuffer, and process them.
            readBuffer.Position = 0;
            foreach (var termString in terminatorStrings)
            {
                var messageLength = (int)termString.Index - (int)readBuffer.Position;
                var messageContents = new byte[messageLength];
                await readBuffer.ReadAsync(messageContents, 0, messageLength);

                OnRawMessageReceived(new RawMessageReceivedEventArgs(messageContents));
                
                //Increase position by terminator string width.
                readBuffer.Position += 2;

            }
            //All full messages have been processed, so copy whatever is still in the buffer to the
            //start of a new reset buffer.
            var finalPosition = (int)readBuffer.Position;
            var bufferLength = (int)readBuffer.Length;
            var bytesLeft = bufferLength - finalPosition;

            //Create a new readBuffer that can hold the current remaining data and a full extra read.
            readBuffer = new MemoryStream((bytesLeft > 0) ? BUFFER_SIZE + bytesLeft : BUFFER_SIZE);

            if (bytesLeft > 0)
            {
                await readBuffer.WriteAsync(readBufferArray, finalPosition, bytesLeft);
            }


        }
开发者ID:Entalyan,项目名称:EntIRC,代码行数:56,代码来源:IrcConnection.cs

示例9: SaveFileAsync

        public async Task SaveFileAsync(string path, byte[] data)
        {
            if (data == null)
                throw new CustomArgumentException("NULL Data can't be written to Storage!");

            var blob = this.GetBlobReference(path);

            List<string> blocks = new List<string>();

            using (MemoryStream ms = new MemoryStream(data))
            {
                byte[] buffer = new byte[MaxUploadBlobSize];
                int index = 0, offset = 0, readed = 0;

                this.LogMessage($"begin uploading to {path} [{data.Length}]");

                // reading portions from the array
                while ((readed = await ms.ReadAsync(buffer, 0, MaxUploadBlobSize)) > 0)
                {
                    // move through array
                    offset += readed;

                    // generate new blockID
                    var blockID = this.GetBlobBlockID(index);

                    // put block with buffer into storage
                    await blob.PutBlockAsync(blockID, new MemoryStream(buffer, 0, readed), null);

                    // remember blockID to be saved
                    blocks.Add(blockID);

                    this.LogMessage($"uploaded block {index}:{blockID} [{readed}]");

                    // increase index to get next blockID
                    index++;
                }
            }

            // write to storage
            await blob.PutBlockListAsync(blocks);

            this.LogMessage($"complete uploading to {path} [{data.Length}] with {blocks.Count} blocks");
        }
开发者ID:sxkote,项目名称:sxcore,代码行数:43,代码来源:AzureFileStorageService.cs

示例10: RenderLabelToStream

        public async Task<System.IO.MemoryStream> RenderLabelToStream(
            float imageWidth,
            float imageHeight,
            Color4 foregroundColor,
            Vector2 origin,
            TextLayout textLayout,
            float dpi = DEFAULT_DPI,
            SharpDX.DXGI.Format format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            SharpDX.Direct2D1.AlphaMode alpha = AlphaMode.Premultiplied)
        {

            // Get stream
            var pngStream = new MemoryStream();

            using (var renderTarget = RenderLabel(
                imageWidth,
                imageHeight,
                foregroundColor,
                origin,
                textLayout,
                dpi,
                format,
                alpha))
            {

                pngStream.Position = 0;

                // Create a WIC outputstream
                using (var wicStream = new WICStream(FactoryImaging, pngStream))
                {

                    var size = renderTarget.PixelSize;

                    // Initialize a Png encoder with this stream
                    using (var wicBitmapEncoder = new PngBitmapEncoder(FactoryImaging, wicStream))
                    {

                        // Create a Frame encoder
                        using (var wicFrameEncoder = new BitmapFrameEncode(wicBitmapEncoder))
                        {
                            wicFrameEncoder.Initialize();

                            // Create image encoder
                            ImageEncoder wicImageEncoder;
                            ImagingFactory2 factory2 = new ImagingFactory2();
                            wicImageEncoder = new ImageEncoder(factory2, D2DDevice);


                            var imgParams = new ImageParameters();
                            imgParams.PixelFormat =
                                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                                                                    AlphaMode.Premultiplied);

                            imgParams.PixelHeight = (int)size.Height;
                            imgParams.PixelWidth = (int)size.Width;

                            wicImageEncoder.WriteFrame(renderTarget, wicFrameEncoder, imgParams);

                            //// Commit changes
                            wicFrameEncoder.Commit();
                            wicBitmapEncoder.Commit();

                            byte[] buffer = new byte[pngStream.Length];
                            pngStream.Position = 0;
                            await pngStream.ReadAsync(buffer, 0, (int)pngStream.Length);
                        }
                    }
                }
            }

            return pngStream;
        }
开发者ID:haithemaraissia,项目名称:CocosSharp,代码行数:72,代码来源:CCLabel-Renderer81.cs

示例11: DownloadPayloadReferenceAsync

        /// <summary>
        /// Downloads a <see cref="PayloadReference"/> that is referenced from an incoming inbox item.
        /// </summary>
        /// <param name="inboxItem">The inbox item that referenced the <see cref="PayloadReference"/>.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The task representing the asynchronous operation.</returns>
        protected virtual async Task<PayloadReference> DownloadPayloadReferenceAsync(IncomingList.IncomingItem inboxItem, CancellationToken cancellationToken)
        {
            Requires.NotNull(inboxItem, "inboxItem");

            var responseMessage = await this.HttpClient.GetAsync(inboxItem.Location, cancellationToken).ConfigureAwait(false);
            if (responseMessage.StatusCode == HttpStatusCode.NotFound)
            {
                // delete inbox item and move on.
                await this.DeletePayloadReferenceAsync(inboxItem.Location, cancellationToken).ConfigureAwait(false);
                this.Log("Missing payload reference.", null);
                return null;
            }

            responseMessage.EnsureSuccessStatusCode();
            var responseStream = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false);
            var responseStreamCopy = new MemoryStream();
            await responseStream.CopyToAsync(responseStreamCopy, 4096, cancellationToken).ConfigureAwait(false);
            responseStreamCopy.Position = 0;

            var encryptedKey = await responseStreamCopy.ReadSizeAndBufferAsync(cancellationToken).ConfigureAwait(false);
            var key = WinRTCrypto.CryptographicEngine.Decrypt(this.Endpoint.EncryptionKey, encryptedKey);
            var iv = await responseStreamCopy.ReadSizeAndBufferAsync(cancellationToken).ConfigureAwait(false);
            var ciphertextStream = await responseStreamCopy.ReadSizeAndStreamAsync(cancellationToken).ConfigureAwait(false);
            var encryptedVariables = new SymmetricEncryptionVariables(key, iv);

            var plainTextPayloadStream = new MemoryStream();
            await this.CryptoServices.DecryptAsync(ciphertextStream, plainTextPayloadStream, encryptedVariables, cancellationToken).ConfigureAwait(false);

            plainTextPayloadStream.Position = 0;
            AsymmetricAlgorithm? signingHashAlgorithm = null;   //// Encoding.UTF8.GetString(await plainTextPayloadStream.ReadSizeAndBufferAsync(cancellationToken));
            byte[] signature = await plainTextPayloadStream.ReadSizeAndBufferAsync(cancellationToken).ConfigureAwait(false);
            long payloadStartPosition = plainTextPayloadStream.Position;
            var signedBytes = new byte[plainTextPayloadStream.Length - plainTextPayloadStream.Position];
            await plainTextPayloadStream.ReadAsync(signedBytes, 0, signedBytes.Length).ConfigureAwait(false);
            plainTextPayloadStream.Position = payloadStartPosition;
            var plainTextPayloadReader = new BinaryReader(plainTextPayloadStream);

            var recipientPublicSigningKeyBuffer = plainTextPayloadReader.ReadSizeAndBuffer();

            var creationDateUtc = DateTime.FromBinary(plainTextPayloadReader.ReadInt64());
            var notificationAuthor = Utilities.DeserializeDataContract<Endpoint>(plainTextPayloadReader);
            var messageReference = Utilities.DeserializeDataContract<PayloadReference>(plainTextPayloadReader);
            messageReference.ReferenceLocation = inboxItem.Location;
            if (messageReference.HashAlgorithmName == null)
            {
                messageReference.HashAlgorithmName = Utilities.GuessHashAlgorithmFromLength(messageReference.Hash.Length).GetHashAlgorithmName();
            }

            if (!CryptoProviderExtensions.VerifySignatureWithTolerantHashAlgorithm(notificationAuthor.SigningKeyPublicMaterial, signedBytes, signature, signingHashAlgorithm))
            {
                throw new InvalidMessageException();
            }

            if (!Utilities.AreEquivalent(recipientPublicSigningKeyBuffer, this.Endpoint.PublicEndpoint.SigningKeyPublicMaterial))
            {
                throw new InvalidMessageException(Strings.MisdirectedMessage);
            }

            return messageReference;
        }
开发者ID:AArnott,项目名称:IronPigeon,代码行数:66,代码来源:Channel.cs

示例12: UploadPhotoAsync

        public async Task UploadPhotoAsync(Photo photo, HttpPostedFileBase fileToUpload)
        {
            var container = getCloudBlobContainer();

            var fileName = string.Format("Photo-{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(fileToUpload.FileName));

            var blockBlob = container.GetBlockBlobReference(string.Format("{0}/{1}", photo.AlbumID, fileName));

            blockBlob.Properties.ContentType = fileToUpload.ContentType;

            await blockBlob.UploadFromStreamAsync(fileToUpload.InputStream);

            blockBlob.StorageUri.ToString();

            var uriBuilder = new UriBuilder(blockBlob.Uri)
            {
                Scheme = "http"
            };

            photo.FileName = fileName;
            photo.PhotoPath = uriBuilder.ToString();

            //Now upload the created thumbnail.

            var bitMap = Image.FromStream(fileToUpload.InputStream);
            var thumbNail = bitMap.GetThumbnailImage(160, 160, null, IntPtr.Zero);
            var thumbNailFileName = string.Format("{0}/{1}/{2}", photo.AlbumID, "thumbs", fileName);

            var memory = new MemoryStream();

            thumbNail.Save(memory, ImageFormat.Jpeg);

            var byteArray = new byte[memory.Length];
            memory.Position = 0;

            await memory.ReadAsync(byteArray, 0, (int)memory.Length);

            blockBlob = container.GetBlockBlobReference(thumbNailFileName);

            blockBlob.Properties.ContentType = fileToUpload.ContentType;

            await blockBlob.UploadFromByteArrayAsync(byteArray, 0, byteArray.Length);

            uriBuilder = new UriBuilder(blockBlob.Uri)
            {
                Scheme = "http"
            };

            await memory.FlushAsync();

            photo.ThumbnailPath = uriBuilder.ToString();
        }
开发者ID:rpillai,项目名称:PhotoGallery2,代码行数:52,代码来源:PhotoStorageService.cs

示例13: DownloadPayloadReferenceAsync

		/// <summary>
		/// Downloads a <see cref="PayloadReference"/> that is referenced from an incoming inbox item.
		/// </summary>
		/// <param name="inboxItem">The inbox item that referenced the <see cref="PayloadReference"/>.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>The task representing the asynchronous operation.</returns>
		protected virtual async Task<PayloadReference> DownloadPayloadReferenceAsync(IncomingList.IncomingItem inboxItem, CancellationToken cancellationToken) {
			Requires.NotNull(inboxItem, "inboxItem");

			var responseMessage = await this.HttpClient.GetAsync(inboxItem.Location, cancellationToken);
			if (responseMessage.StatusCode == HttpStatusCode.NotFound) {
				// delete inbox item and move on.
				await this.DeletePayloadReferenceAsync(inboxItem.Location, cancellationToken);
				this.Log("Missing payload reference.", null);
				return null;
			}

			responseMessage.EnsureSuccessStatusCode();
			var responseStream = await responseMessage.Content.ReadAsStreamAsync();
			var responseStreamCopy = new MemoryStream();
			await responseStream.CopyToAsync(responseStreamCopy, 4096, cancellationToken);
			responseStreamCopy.Position = 0;

			var encryptedKey = await responseStreamCopy.ReadSizeAndBufferAsync(cancellationToken);
			var key = this.CryptoServices.Decrypt(this.Endpoint.EncryptionKeyPrivateMaterial, encryptedKey);
			var iv = await responseStreamCopy.ReadSizeAndBufferAsync(cancellationToken);
			var ciphertext = await responseStreamCopy.ReadSizeAndBufferAsync(cancellationToken);
			var encryptedPayload = new SymmetricEncryptionResult(key, iv, ciphertext);

			var plainTextPayloadBuffer = this.CryptoServices.Decrypt(encryptedPayload);

			var plainTextPayloadStream = new MemoryStream(plainTextPayloadBuffer);
			var signature = await plainTextPayloadStream.ReadSizeAndBufferAsync(cancellationToken);
			long payloadStartPosition = plainTextPayloadStream.Position;
			var signedBytes = new byte[plainTextPayloadStream.Length - plainTextPayloadStream.Position];
			await plainTextPayloadStream.ReadAsync(signedBytes, 0, signedBytes.Length);
			plainTextPayloadStream.Position = payloadStartPosition;
			var plainTextPayloadReader = new BinaryReader(plainTextPayloadStream);

			var recipientPublicSigningKeyBuffer = plainTextPayloadReader.ReadSizeAndBuffer();

			var creationDateUtc = DateTime.FromBinary(plainTextPayloadReader.ReadInt64());
			var notificationAuthor = Utilities.DeserializeDataContract<Endpoint>(plainTextPayloadReader);
			var messageReference = Utilities.DeserializeDataContract<PayloadReference>(plainTextPayloadReader);
			messageReference.ReferenceLocation = inboxItem.Location;

			if (!this.CryptoServices.VerifySignature(notificationAuthor.SigningKeyPublicMaterial, signedBytes, signature)) {
				throw new InvalidMessageException();
			}

			if (!Utilities.AreEquivalent(recipientPublicSigningKeyBuffer, this.Endpoint.PublicEndpoint.SigningKeyPublicMaterial)) {
				throw new InvalidMessageException(Strings.MisdirectedMessage);
			}

			return messageReference;
		}
开发者ID:raam030,项目名称:IronPigeon,代码行数:56,代码来源:Channel.cs

示例14: EncrypMemoryStreamAsync


//.........这里部分代码省略.........
                outputFullPath = Path.Combine(outputFolder, outputFile);
            }
            else
            {
                //store the output file, just with the fileExtension
                outputFile = filename + fileExtension;
                outputFullPath = Path.Combine(outputFolder, outputFile);
            }
            using (FileStream fileStreamEncrypted = File.OpenWrite(outputFullPath))
            {

                //initialize our file header for encryption
                EncryptedFileHeader encryptedFileHeader = new EncryptedFileHeader(
                    CURRENT_VERSION, NONCE_LENGTH, CHUNK_BASE_NONCE_LENGTH, inputStream.Length,
                    senderPrivateKey, senderPublicKey, recipientPublicKey);
                //protect and set the file name to the header
                encryptedFileHeader.ProtectFileName(filename, MAX_FILENAME_LENGTH);
                //generate and set the checksum to validate our file header on decryption
                encryptedFileHeader.SetHeaderChecksum(HEADER_CHECKSUM_LENGTH);
                //write the file header to the stream
                Serializer.SerializeWithLengthPrefix(fileStreamEncrypted, encryptedFileHeader, PrefixStyle.Base128, 1);
                //we start at chunk number 0
                int chunkNumber = CHUNK_COUNT_START;
                //used to calculate the footer checksum
                long overallChunkLength = 0;
                //used for progress reporting
                long overallBytesRead = 0;
                int bytesRead;
                do
                {
                    //cancel the task if requested
                    cancellationToken.ThrowIfCancellationRequested();
                    //start reading the unencrypted file in chunks of the given length: CHUNK_LENGTH
                    byte[] unencryptedChunk = new byte[CHUNK_LENGTH];
                    bytesRead =
                        await inputStream.ReadAsync(unencryptedChunk, 0, CHUNK_LENGTH, cancellationToken).ConfigureAwait(false);
                    //check if there is still some work
                    if (bytesRead != 0)
                    {
                        //prepare the EncryptedFileChunk
                        EncryptedFileChunk encryptedFileChunk = new EncryptedFileChunk();
                        byte[] readedBytes = new byte[bytesRead];
                        //cut unreaded bytes
                        Array.Copy(unencryptedChunk, readedBytes, bytesRead);
                        //check if the file is smaller or equal the CHUNK_LENGTH
                        if (encryptedFileHeader.UnencryptedFileLength <= CHUNK_LENGTH)
                        {
                            //so we have the one and only chunk
                            encryptedFileChunk = EncryptFileChunk(readedBytes, chunkNumber, encryptedFileHeader.BaseNonce,
                                encryptedFileHeader.UnencryptedEphemeralKey, true);
                        }
                        else
                        {
                            //let`s check if this chunk is smaller than the given CHUNK_LENGTH
                            if (bytesRead < CHUNK_LENGTH)
                            {
                                //it`s the last chunk in the stream
                                encryptedFileChunk = EncryptFileChunk(readedBytes, chunkNumber, encryptedFileHeader.BaseNonce,
                                    encryptedFileHeader.UnencryptedEphemeralKey, true);
                            }
                            else
                            {
                                //it`s a full chunk
                                encryptedFileChunk = EncryptFileChunk(readedBytes, chunkNumber, encryptedFileHeader.BaseNonce,
                                    encryptedFileHeader.UnencryptedEphemeralKey, false);
                            }
                        }
                        overallChunkLength += encryptedFileChunk.Chunk.Length;
                        //write encryptedFileChunk to the output stream
                        Serializer.SerializeWithLengthPrefix(fileStreamEncrypted, encryptedFileChunk, PrefixStyle.Base128, 2);
                        //increment for the next chunk
                        chunkNumber++;
                        overallBytesRead += bytesRead;
                        //report status
                        if (encryptionProgress != null)
                        {
                            var args = new StreamCryptorTaskAsyncProgress();
                            args.ProgressPercentage =
                                (int)
                                    (encryptedFileHeader.UnencryptedFileLength <= 0
                                        ? 0
                                        : (100 * overallBytesRead) / encryptedFileHeader.UnencryptedFileLength);
                            encryptionProgress.Report(args);
                        }
                    }
                    else
                    {
                        //Prepare the EncryptedFileFooter for encryption.
                        EncryptedFileFooter encryptedFileFooter = new EncryptedFileFooter();
                        //generate the FooterChecksum
                        encryptedFileFooter.SetFooterChecksum(BitConverter.GetBytes(chunkNumber),
                            BitConverter.GetBytes(overallChunkLength), encryptedFileHeader.UnencryptedEphemeralKey, FOOTER_CHECKSUM_LENGTH);
                        //put the footer to the stream
                        Serializer.SerializeWithLengthPrefix(fileStreamEncrypted, encryptedFileFooter, PrefixStyle.Base128, 3);
                    }
                } while (bytesRead != 0);

            }
            return outputFile;
        }
开发者ID:bitbeans,项目名称:StreamCryptor,代码行数:101,代码来源:Cryptor.cs

示例15: UploadPackageAsync

		private async Task UploadPackageAsync(ITransferHandler handler)
		{
			using (var ms = new MemoryStream(await handler.ReadAsync()))
			{
				var header = new RequestHeader().Setup(ms);
				var packageBytes = new byte[ms.Length - ms.Position];
				await ms.ReadAsync(packageBytes, 0, packageBytes.Length);

				var package = new RequestPackage(header, packageBytes);
				_packages[(int)package.Header.ClientPlatform] = package;

				await this.SavePackageAsync(package.Header.ClientPlatform, package);
			}
		}
开发者ID:ppetrov,项目名称:iFSA.Service,代码行数:14,代码来源:UpdateServerHandler.cs


注:本文中的System.IO.MemoryStream.ReadAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。