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


C# MemoryStream.FlushAsync方法代码示例

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


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

示例1: ProcessImage

        /// <summary>
        /// Resizes the image using a high quality.  
        /// From http://stackoverflow.com/questions/1922040/resize-an-image-c-sharp
        /// </summary>
        /// <param name="imageStream"></param>
        /// <returns></returns>
        internal static MemoryStream ProcessImage(MemoryStream imageStream)
        {
            var height = 100;
            var width = 100;

            Image original = Image.FromStream(imageStream);

            var destRect = new Rectangle(0, 0, width, height);
            var destImage = new Bitmap(width, height);

            destImage.SetResolution(original.HorizontalResolution, original.VerticalResolution);

            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(original, destRect, 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            MemoryStream ret = new MemoryStream();
            destImage.Save(ret, original.RawFormat);
            ret.FlushAsync().Wait();
            ret.Position = 0;
            return ret;
        }
开发者ID:kaevans,项目名称:globalscaledemo,代码行数:39,代码来源:PhotoEditor.cs

示例2: ToByteArrayAsync

 public static async Task<byte[]> ToByteArrayAsync(this ArraySegment<byte> source) {
     byte[] data = null;
     using (MemoryStream ms = new MemoryStream()) {
         await ms.WriteAsync(source.Array, source.Offset, source.Count);
         await ms.FlushAsync();
         data = ms.ToArray();
     }
     return data;
 }
开发者ID:Microsoft,项目名称:RTVS,代码行数:9,代码来源:ArraySegmentExtensions.cs

示例3: CompressAsync

        public static async Task<byte[]> CompressAsync(this byte[] data, CancellationToken cancellationToken = default(CancellationToken)) {
            byte[] compressesData;
            using (var outputStream = new MemoryStream()) {
                using (var zip = new GZipStream(outputStream, CompressionMode.Compress, true)) {
                    await zip.WriteAsync(data, 0, data.Length, cancellationToken);
                }

                await outputStream.FlushAsync(cancellationToken);
                compressesData = outputStream.ToArray();
            }

            return compressesData;
        }
开发者ID:aamarber,项目名称:Exceptionless,代码行数:13,代码来源:ByteArrayExtensions.cs

示例4: DownloadToString

 public static async Task<string> DownloadToString(this CloudBlockBlob blob)
 {
     using (var strm = new MemoryStream())
     {
         await
             Task.Factory.FromAsync((cb, state) => blob.BeginDownloadToStream(strm, cb, state),
                                    ar => blob.EndDownloadToStream(ar), 
                                    state: null);
         await strm.FlushAsync();
         strm.Seek(0, SeekOrigin.Begin);
         return await new StreamReader(strm).ReadToEndAsync();
     }
 }
开发者ID:NuGet,项目名称:OpsDashboard,代码行数:13,代码来源:AzureStorageExtensions.cs

示例5: SendMessageAsync

        /// <summary>
        /// Transport the given <paramref name="serialisedMessage"/>.
        /// </summary>
        /// <param name="serialisedMessage">The content of the message to send.</param>
        /// <returns>An awaitable object for the Send operation.</returns>
        public async Task SendMessageAsync(string serialisedMessage)
        {
            using (var outputStream = this._ftpClient.PutFile(string.Concat("/", DateTime.Now.ToFileTimeUtc(), ".msg")))
            {
                using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(serialisedMessage)))
                {
                    await stream.CopyToAsync(outputStream);

                    await stream.FlushAsync();

                    await outputStream.FlushAsync();
                }
            }
        }
开发者ID:dibble-james,项目名称:ServiceBus,代码行数:19,代码来源:FtpMessageSender.cs

示例6: PutMessage

        /// <summary>
        /// Place a raw message onto the FTP Server.
        /// </summary>
        /// <param name="messageLocation">The relative location where the message should be placed.</param>
        /// <param name="serialisedMessage">The raw message content.</param>
        /// <returns>An awaitable object for the Put operation.</returns>
        public async Task PutMessage(Uri messageLocation, string serialisedMessage)
        {
            using (var outputStream = this._ftpClient.PutFile(messageLocation.ToString()))
            {
                using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(serialisedMessage)))
                {
                    await stream.CopyToAsync(outputStream);

                    await stream.FlushAsync();

                    await outputStream.FlushAsync();
                }
            }
        }
开发者ID:dibble-james,项目名称:ServiceBus,代码行数:20,代码来源:FtpQueueClient.cs

示例7: UploadAsync

        public async Task UploadAsync(string url, IDictionary<string, string> headers, string method, string file)
        {
            byte[] data = null;

            // Get the local folder.
            var localStorage = IsolatedStorageFile.GetUserStoreForApplication();

            using (var fileStream = new IsolatedStorageFileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, localStorage))
            {
                using (var memStream = new MemoryStream())
                {
                    await fileStream.CopyToAsync(memStream);
                    await fileStream.FlushAsync();
                    await memStream.FlushAsync();
                    data = memStream.ToArray();
                }
            }
            await UploadAsync(url, headers, method, data);
        }
开发者ID:neilunadkat,项目名称:appacitive-dotnet-sdk,代码行数:19,代码来源:WebClientHttpFileHandler.cs

示例8: ToBase64String

        public async static Task<String> ToBase64String(this Bitmap iBitmap)
        {
            using (MemoryStream pMSmOutput = new MemoryStream())
            {
                using (EncoderParameters pEPsParams = new EncoderParameters(1))
                {
                    EncoderParameter pEPrParam = new EncoderParameter(Encoder.Quality, 100L);
                    pEPsParams.Param[0] = pEPrParam;
                    using (Bitmap pBmpCopy = new Bitmap(iBitmap))
                    {
                        pBmpCopy.Save(pMSmOutput, GetEncoder(ImageFormat.Jpeg), pEPsParams);
                    }
                    await pMSmOutput.FlushAsync();

                    String pStrBase64 = Convert.ToBase64String(pMSmOutput.ToArray());
                    return (pStrBase64);
                }
            }
        }
开发者ID:ebt,项目名称:doesnotwant,代码行数:19,代码来源:BitmapExtensions.cs

示例9: AddUrlResourceAsync

        public async Task<Tuple<Stream,string>> AddUrlResourceAsync(string url,bool needBig)
        {
            string contentType;
            var hash = ComputeMD5(url);
            CloudBlockBlob blobRef = Container.GetBlockBlobReference(hash);
            if (blobRef.Exists())
            {
                MemoryStream ms2=new MemoryStream();
                if(needBig)
                {
                    await blobRef.DownloadToStreamAsync(ms2);
                }
                else
                {
                    await quantizedManager.DownloadToStream(ms2, hash);
                }
                
                ms2.Seek(0, SeekOrigin.Begin);
                contentType = blobRef.Properties.ContentType;
                return new Tuple<Stream, string>(ms2, contentType);
            }

            WebClient wc = new WebClient();
            Stream stream = wc.OpenRead(url);
            contentType=blobRef.Properties.ContentType = wc.ResponseHeaders["Content-Type"];
            if (!whiteMIMEList.Contains(contentType.ToLower())) return null;//これ以外で実行形式などがアップロードされないようにホワイトリスト
            await blobRef.UploadFromStreamAsync(stream);
            MemoryStream ms=new MemoryStream();
            await blobRef.DownloadToStreamAsync(ms);
            await ms.FlushAsync();
            ms.Seek(0, SeekOrigin.Begin);
            Bitmap sourceBitmap = new Bitmap(ms);
            var size = ClampSize(sourceBitmap);
            Bitmap resizedBitmap = ResizeImage(sourceBitmap, size.Item1, size.Item2);
            MemoryStream ms3=new MemoryStream();
            resizedBitmap.Save(ms3,ImageFormat.Jpeg);
            ms3.Seek(0, SeekOrigin.Begin);
            await quantizedManager.UploadResizedBlob(ms3,hash);
            ms3.Seek(0, SeekOrigin.Begin);
            return new Tuple<Stream, string>(ms3,"image/jpeg");
        }
开发者ID:kyasbal-1994,项目名称:linophi,代码行数:41,代码来源:ImageUploaderManager.cs

示例10: DownloadAsync

        public async Task<byte[]> DownloadAsync(string url, IDictionary<string, string> headers, string method)
        {
            var client = new WebClient();
            if (headers != null)
            {
                foreach (var header in headers)
                    client.Headers[header.Key] = header.Value;
            }
            var downloadStream = await client.OpenReadTaskAsync(url);
            byte[] buffer = new byte[1024];
            using (MemoryStream stream = new MemoryStream())
            {
                while (downloadStream.Read(buffer, 0, buffer.Length) > 0)
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
                await stream.FlushAsync();
                return stream.ToArray();
            }

        }
开发者ID:neilunadkat,项目名称:appacitive-dotnet-sdk,代码行数:21,代码来源:WebClientHttpFileHandler.cs

示例11: Compress

        internal override async Task Compress(Func<IDictionary<string, object>, Task> next, OwinContext context, ICompressor compressor, Stream httpOutputStream)
        {
            using (var uncompressedStream = new MemoryStream())
            {
                context.Response.Body = uncompressedStream;
                await next.Invoke(context.Environment);
                await uncompressedStream.FlushAsync();

                if (uncompressedStream.Length > 0)
                {
                    uncompressedStream.Position = 0;

                    if (ShouldCompress(context.Response.ContentType))
                    {
                        await CompressToHttpOutputStream(context, compressor, httpOutputStream, uncompressedStream);
                    }
                    else
                    {
                        await uncompressedStream.CopyToAsync(httpOutputStream, BufferSize);
                    }
                }
            }
        }
开发者ID:mikegore1000,项目名称:SqueezeMe,代码行数:23,代码来源:ConfigurableCompressionStrategy.cs

示例12: RaiseOutputMessageEvent

        public async Task RaiseOutputMessageEvent() {
            // Arrange
            const string message = "Hello node.js!";
            string formattedMessage = string.Format("Content-Length: {0}{1}{1}{2}", Encoding.UTF8.GetByteCount(message), Environment.NewLine, message);
            byte[] rawMessage = Encoding.UTF8.GetBytes(formattedMessage);

            var memoryStream = new MemoryStream();
            await memoryStream.WriteAsync(rawMessage, 0, rawMessage.Length);
            await memoryStream.FlushAsync();
            memoryStream.Seek(0, SeekOrigin.Begin);

            var tcpClientMock = new Mock<INetworkClient>();
            tcpClientMock.Setup(p => p.GetStream()).Returns(() => memoryStream);
            tcpClientMock.SetupGet(p => p.Connected).Returns(() => true);

            var tcpClientFactoryMock = new Mock<INetworkClientFactory>();
            tcpClientFactoryMock.Setup(p => p.CreateNetworkClient(It.IsAny<Uri>())).Returns(() => tcpClientMock.Object);

            var debuggerConnection = new DebuggerConnection(tcpClientFactoryMock.Object);
            object sender = null;
            MessageEventArgs args = null;
            bool inital = debuggerConnection.Connected;

            // Act
            debuggerConnection.OutputMessage += (s, a) => {
                sender = s;
                args = a;
            };
            debuggerConnection.Connect(new Uri("tcp://localhost:5858"));
            bool afterConnection = debuggerConnection.Connected;

            await Task.Delay(TimeSpan.FromMilliseconds(100));
            memoryStream.Close();

            // Assert
            Assert.IsNotNull(sender);
            Assert.AreEqual(debuggerConnection, sender);
            Assert.IsNotNull(args);
            Assert.AreEqual(message, args.Message);
            Assert.IsFalse(inital);
            Assert.IsTrue(afterConnection);
        }
开发者ID:lioaphy,项目名称:nodejstools,代码行数:42,代码来源:DebuggerConnectionTests.cs

示例13: Save2Async

		private async Task<bool> Save2Async(StorageFile file = null)
		{
			//for (int i = 0; i < 100000000; i++) //wait a few seconds, for testing
			//{
			//    String aaa = i.ToString();
			//}
			await Logger.AddAsync("MetaBriefcase about to save", Logger.FileErrorLogFilename, Logger.Severity.Info).ConfigureAwait(false);
			bool result = false;

			// save xml properties
			try
			{
				_localDataSemaphore.WaitOne();

				if (file == null)
				{
					file = await GetDirectory()
						.TryGetItemAsync(FILENAME).AsTask().ConfigureAwait(false) as StorageFile;
				}

				string savedData = string.Empty;
				if (file != null)
				{
					using (var localFileContent = await file.OpenStreamForReadAsync().ConfigureAwait(false))
					{
						using (StreamReader streamReader = new StreamReader(localFileContent))
						{
							savedData = streamReader.ReadToEnd();
						}
					}
				}

				using (var memoryStream = new MemoryStream())
				{
					var serializer = new DataContractSerializer(typeof(MetaBriefcase));
					serializer.WriteObject(memoryStream, this);

					string currentMetaBriefcase = string.Empty;
					memoryStream.Seek(0, SeekOrigin.Begin);
					using (StreamReader streamReader = new StreamReader(memoryStream))
					{
						currentMetaBriefcase = streamReader.ReadToEnd();

						if (!currentMetaBriefcase.Trim().Equals(savedData.Trim()))
						{
							if (file == null)
							{
								file = await GetDirectory()
									.CreateFileAsync(FILENAME, CreationCollisionOption.ReplaceExisting).AsTask().ConfigureAwait(false);
							}

							using (var fileStream = await file.OpenStreamForWriteAsync().ConfigureAwait(false))
							{
								fileStream.SetLength(0); // avoid leaving crap at the end if overwriting a file that was longer
								memoryStream.Seek(0, SeekOrigin.Begin);
								await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false);
								await memoryStream.FlushAsync().ConfigureAwait(false);
								await fileStream.FlushAsync().ConfigureAwait(false);
							}
						}
					}
				}
				Debug.WriteLine("ended method MetaBriefcase.SaveAsync()");
				result = true;
			}
			catch (Exception ex)
			{
				Logger.Add_TPL(ex.ToString(), Logger.FileErrorLogFilename);
			}
			finally
			{
				// save non-xml properties
				result = result & RegistryAccess.TrySetValue(ConstantData.REG_MBC_IS_ELEVATED, IsElevated.ToString());
				SemaphoreExtensions.TryRelease(_localDataSemaphore);
			}

			return result;
		}
开发者ID:lolluslollus,项目名称:UniFiler10,代码行数:78,代码来源:MetaBriefcase.cs

示例14: AssembleFilesBlock

        private async Task<IEnumerable<byte[]>> AssembleFilesBlock(ICollection<string> filePaths, byte[] additionalData) {
            const int assembleFileExtraBytes = 134;
            var result = new List<byte[]>();

            var formattedBoundary = GetFormattedBoundary(false);
            var needSize = (from f in filePaths select new FileInfo(f).Length).Sum() +
                           (from f in filePaths select Encoding.UTF8.GetByteCount(Path.GetFileName(f))).Sum() +
                           (formattedBoundary.Length + assembleFileExtraBytes) * filePaths.Count +
                           additionalData.Length;
            var memoryStream = new MemoryStream((int) Math.Min(needSize, int.MaxValue));

            var streamWillExceedCapacity = new Func<MemoryStream, byte[], bool>((stream, file) => stream.Length + formattedBoundary.Length + file.Length + additionalData.Length > stream.Capacity);

            // Todo: get rid of this when API will be fixed
            var numberOfFilesCanBeUploadedPerSingleRequest = 20;
            var getStreamData = new Func<MemoryStream, byte[]>(stream => stream.Length == stream.Capacity ? stream.GetBuffer() : stream.ToArray());
            // <------------------------------------------------------------

            foreach (var t in filePaths) {
                var file = await AssembleFile(t);

                if (streamWillExceedCapacity(memoryStream, file) || numberOfFilesCanBeUploadedPerSingleRequest < 1) {
                    await memoryStream.WriteAsync(additionalData, 0, additionalData.Length);
                    await memoryStream.FlushAsync();
                    result.Add(getStreamData(memoryStream));
                    memoryStream.Dispose();
                    memoryStream = new MemoryStream((int) Math.Min(needSize, int.MaxValue));
                    numberOfFilesCanBeUploadedPerSingleRequest = 20;
                }
                await memoryStream.WriteAsync(formattedBoundary, 0, formattedBoundary.Length);
                await memoryStream.WriteAsync(file, 0, file.Length);

                needSize -= formattedBoundary.Length + file.Length;
                --numberOfFilesCanBeUploadedPerSingleRequest;
            }
            await memoryStream.WriteAsync(additionalData, 0, additionalData.Length);
            await memoryStream.FlushAsync();

            result.Add(getStreamData(memoryStream));
            memoryStream.Dispose();
            return result;
        }
开发者ID:maximbaz,项目名称:BoxSimpleSync,代码行数:42,代码来源:Files.cs

示例15: RetrieveNodeVersion

        public async Task RetrieveNodeVersion() {
            // Arrange
            const string version = "0.10.25";
            string message = string.Format("Embedding-Host: node v{0}\r\n\r\n", version);
            byte[] rawMessage = Encoding.UTF8.GetBytes(message);

            var memoryStream = new MemoryStream();
            await memoryStream.WriteAsync(rawMessage, 0, rawMessage.Length);
            await memoryStream.FlushAsync();
            memoryStream.Seek(0, SeekOrigin.Begin);

            var tcpClientMock = new Mock<INetworkClient>();
            tcpClientMock.Setup(p => p.GetStream()).Returns(() => memoryStream);
            tcpClientMock.SetupGet(p => p.Connected).Returns(() => true);

            var tcpClientFactoryMock = new Mock<INetworkClientFactory>();
            tcpClientFactoryMock.Setup(p => p.CreateNetworkClient(It.IsAny<Uri>())).Returns(() => tcpClientMock.Object);

            var debuggerConnection = new DebuggerConnection(tcpClientFactoryMock.Object);

            // Act
            debuggerConnection.Connect(new Uri("tcp://localhost:5858"));
            for (int i = 0; i < 10 && debuggerConnection.NodeVersion == null; ++i) {
                await Task.Delay(TimeSpan.FromMilliseconds(100));
            }
            memoryStream.Close();

            // Assert
            Assert.IsNotNull(debuggerConnection.NodeVersion);
            Assert.AreEqual(version, debuggerConnection.NodeVersion.ToString());
       }
开发者ID:lioaphy,项目名称:nodejstools,代码行数:31,代码来源:DebuggerConnectionTests.cs


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