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


C# Stream.WriteAsync方法代码示例

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


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

示例1: CopyStreamsAsyncParallel

        public static async Task<long> CopyStreamsAsyncParallel(Stream src, Stream dst)
        {
            long numCopied = 0;
            byte[][] buffer = new byte[2][];
            buffer[0] = new byte[0x1000];
            buffer[1] = new byte[0x1000];

            var index = 0;
            int numRead = await src.ReadAsync(buffer[index], 0, buffer[index].Length);

            while (numRead > 0)
            {
                var writeAsync = dst.WriteAsync(buffer[index], 0, numRead);
                index = index ^= 1;
                var readAsync = src.ReadAsync(buffer[index], 0, buffer[index].Length);

                Task.WaitAll(writeAsync, readAsync);
                numRead = readAsync.Result;

                numCopied += numRead;
            }
            await dst.FlushAsync();
            src.Dispose();
            dst.Dispose();

            return numCopied;

        }
开发者ID:rikace,项目名称:Experiments,代码行数:28,代码来源:Comp.cs

示例2: WritePairToStream

        async Task WritePairToStream(Stream stream, KeyValuePair<String, char[]> pair)
        {
            byte[] eqValue = Encoding.UTF8.GetBytes("=");
            byte[] utf8Value = null;
            byte[] encodedValue = null;
            try
            {
                // write key (and escape it first)
                utf8Value = Encoding.UTF8.GetBytes(pair.Key);
                encodedValue = WebUtility.UrlEncodeToBytes(utf8Value, 0, utf8Value.Length);
                await stream.WriteAsync(encodedValue, 0, encodedValue.Length);
                // write '='                
                await stream.WriteAsync(eqValue, 0, eqValue.Length);
                Array.Clear(utf8Value, 0, utf8Value.Length);

                // write value (and escape it first)
                utf8Value = Encoding.UTF8.GetBytes(pair.Value);
                encodedValue = WebUtility.UrlEncodeToBytes(utf8Value, 0, utf8Value.Length);
                await stream.WriteAsync(encodedValue, 0, encodedValue.Length);
            } finally
            {                
                if (encodedValue != null)
                    Array.Clear(encodedValue, 0, encodedValue.Length);
                if (utf8Value != null)
                    Array.Clear(utf8Value, 0, utf8Value.Length);
            }
        }
开发者ID:cherepets,项目名称:SeafClient,代码行数:27,代码来源:CredentialFormContent.cs

示例3: WriteAsync

 public async Task WriteAsync(Stream stream, TagVersion version)
 {
     byte[] contentBytes = GetContentBytes(version);
     
     var tagId = Encoding.Default.GetBytes(GetTagId(version)); 
     await stream.WriteAsync(tagId, 0, tagId.Length).ConfigureAwait(false);
     switch (version)
     {
         case TagVersion.V23:
             stream.WriteByte((byte)((contentBytes.Length / (256 * 256 * 256))));
             stream.WriteByte((byte)((contentBytes.Length % (256 * 256 * 256)) / (256 * 256)));
             stream.WriteByte((byte)((contentBytes.Length % (256 * 256)) / 256));
             stream.WriteByte((byte)((contentBytes.Length % 256)));
             break;
         case TagVersion.V24:
             stream.WriteByte((byte)((contentBytes.Length / (128 * 128 * 128))));
             stream.WriteByte((byte)((contentBytes.Length % (128 * 128 * 128)) / (128 * 128)));
             stream.WriteByte((byte)((contentBytes.Length % (128 * 128)) / 128));
             stream.WriteByte((byte)((contentBytes.Length % 128)));
             break;
         default:
             throw new ArgumentException($"Unable to write frame with version {version}", nameof(version));
     }
     stream.WriteByte(0x00);
     stream.WriteByte(0x00);
     await stream.WriteAsync(contentBytes, 0, contentBytes.Length).ConfigureAwait(false);
 }
开发者ID:stebet,项目名称:Stebet.ID3,代码行数:27,代码来源:Frame.cs

示例4: WriteToAsync

		public async Task<FastcgiPacket> WriteToAsync(Stream ClientStream)
		{
			if (Content.Count > ushort.MaxValue) throw(new InvalidDataException("Data too long"));
			var ContentLength = (ushort)Content.Count;
			var PaddingLength = (byte)(MathUtils.Align(ContentLength, 8) - ContentLength);

			var Header = new byte[8];
			Header[0] = Version;
			Header[1] = (byte)Type;
			Header[2] = (byte)((RequestId >> 8) & 0xFF);
			Header[3] = (byte)((RequestId >> 0) & 0xFF);
			Header[4] = (byte)((ContentLength >> 8) & 0xFF);
			Header[5] = (byte)((ContentLength >> 0) & 0xFF);
			Header[6] = PaddingLength;
			Header[7] = 0;
			await ClientStream.WriteAsync(Header, 0, Header.Length);
			if (ContentLength > 0)
			{
				await ClientStream.WriteAsync(Content.Array, Content.Offset, Content.Count);
			}
			if (PaddingLength > 0)
			{
				await ClientStream.WriteAsync(PaddingWrite, 0, PaddingLength);
			}

			//await Console.Out.WriteLineAsync(String.Format("WRITE: Packet({0}): {1}({2}:{3})", RequestId, Type, ContentLength, PaddingLength));

			return this;
		}
开发者ID:soywiz,项目名称:csharputils,代码行数:29,代码来源:FastcgiPacket.cs

示例5: ConnectionHandshake

        public async Task ConnectionHandshake(Stream stream, ILogger logger, string authorizationKey, CancellationToken cancellationToken)
        {
            await stream.WriteAsync(connectHeader, 0, connectHeader.Length, cancellationToken);
            logger.Debug("Sent ReQL header");

            if (String.IsNullOrEmpty(authorizationKey))
            {
                await stream.WriteAsync(new byte[] { 0, 0, 0, 0 }, 0, 4, cancellationToken);
            }
            else
            {
                var keyInBytes = Encoding.UTF8.GetBytes(authorizationKey);
                var authKeyLength = BitConverter.GetBytes(keyInBytes.Length);
                if (!BitConverter.IsLittleEndian)
                    Array.Reverse(authKeyLength, 0, authKeyLength.Length);
                await stream.WriteAsync(authKeyLength, 0, authKeyLength.Length);
                await stream.WriteAsync(keyInBytes, 0, keyInBytes.Length);
            }

            await stream.WriteAsync(ProtocolHeader, 0, ProtocolHeader.Length, cancellationToken);

            byte[] authReponseBuffer = new byte[1024];
            var authResponseLength = await stream.ReadUntilNullTerminator(logger, authReponseBuffer, cancellationToken);
            var authResponse = Encoding.ASCII.GetString(authReponseBuffer, 0, authResponseLength);
            if (authResponse != "SUCCESS")
                throw new RethinkDbRuntimeException("Unexpected authentication response; expected SUCCESS but got: " + authResponse);
        }
开发者ID:karlgrz,项目名称:rethinkdb-net,代码行数:27,代码来源:Version_0_3.cs

示例6: WriteToAsync

        public async Task<FastCGIPacket> WriteToAsync(Stream ClientStream)
        {
            if (Content.Count > ushort.MaxValue) throw (new InvalidDataException("Data too long"));
            var ContentLength = (ushort)Content.Count;
            var PaddingLength = (byte)(Align(ContentLength, 8) - ContentLength);

            var Header = new byte[8];
            Header[0] = Version;
            Header[1] = (byte)Type;
            Header[2] = (byte)((RequestId >> 8) & 0xFF);
            Header[3] = (byte)((RequestId >> 0) & 0xFF);
            Header[4] = (byte)((ContentLength >> 8) & 0xFF);
            Header[5] = (byte)((ContentLength >> 0) & 0xFF);
            Header[6] = PaddingLength;
            Header[7] = 0;
            await ClientStream.WriteAsync(Header, 0, Header.Length);
            if (ContentLength > 0)
            {
                await ClientStream.WriteAsync(Content.Array, Content.Offset, Content.Count);
            }
            if (PaddingLength > 0)
            {
                await ClientStream.WriteAsync(PaddingWrite, 0, PaddingLength);
            }

            return this;
        }
开发者ID:jhaygood86,项目名称:FastCgiServerLibrary,代码行数:27,代码来源:FastCGIPacket.cs

示例7: WriteQueryToStream

        public override async Task WriteQueryToStream(Stream stream, ILogger logger, Spec.Query query, CancellationToken cancellationToken)
        {
            using (var memoryBuffer = new MemoryStream(1024))
            using (var streamWriter = new StreamWriter(memoryBuffer, utf8Encoding))
            {
                WriteQuery(new JsonWriter(streamWriter), query);
                streamWriter.Flush();

                var data = memoryBuffer.ToArray();
                memoryBuffer.Seek(0, SeekOrigin.Begin);

                if (logger.InformationEnabled())
                {
                    string dataStr = Encoding.UTF8.GetString(data);
                    logger.Information("JSON query: {0}", dataStr);
                }

                var tokenHeader = BitConverter.GetBytes(query.token);
                if (!BitConverter.IsLittleEndian)
                    Array.Reverse(tokenHeader, 0, tokenHeader.Length);
                memoryBuffer.Write(tokenHeader, 0, tokenHeader.Length);

                var lengthHeader = BitConverter.GetBytes(data.Length);
                if (!BitConverter.IsLittleEndian)
                    Array.Reverse(lengthHeader, 0, lengthHeader.Length);
                memoryBuffer.Write(lengthHeader, 0, lengthHeader.Length);

                memoryBuffer.Write(data, 0, data.Length);

                logger.Debug("Writing packet, {0} bytes", data.Length);
                data = memoryBuffer.ToArray();
                await stream.WriteAsync(data, 0, data.Length, cancellationToken);
            }
        }
开发者ID:karlgrz,项目名称:rethinkdb-net,代码行数:34,代码来源:Version_0_3_JsonProtocol.cs

示例8: DownloadFileAsync

        public static async Task DownloadFileAsync(this HttpClient client, Uri url, Stream output, IProgress<double> progress)
        {
            using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
            {
                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception($"The request returned with HTTP status code {response.StatusCode}");
                }
                var total = response.Content.Headers.ContentLength ?? -1L;

                using (var stream = await response.Content.ReadAsStreamAsync())
                {
                    var totalRead = 0L;
                    var buffer = new byte[81920]; // Default size from .NET docs on CopyTo
                    while (true)
                    {
                        var read = await stream.ReadAsync(buffer, 0, buffer.Length);
                        if (read == 0)
                        {
                            break;
                        }
                        await output.WriteAsync(buffer, 0, read);
                        totalRead += read;
                        // Can't report progress if there was no Content-Length
                        if (total > 0)
                        {
                            progress?.Report(totalRead * 1d / (total * 1d) * 100);
                        }
                    }
                    progress?.Report(100);
                }
            }
        }
开发者ID:mattolenik,项目名称:winston,代码行数:33,代码来源:Extensions.cs

示例9: SendPacket

        public async Task SendPacket(IPacket packet, Stream netStream)
        {
            var ms = new MemoryStream();
            var bw = new BinaryWriter(ms);

            if (packet is IAutoSerializePacket)
                (packet as IAutoSerializePacket).AutoSerialize(bw);
            else
            {
                bw.Write(packet.ID);
                packet.SerializePacket(bw);
            }

            bw.Flush();

            // Copy ms -> redirect writer to new ms -> prepend packet size prefix -> append packet paylod
            FinalizePacket(ref bw);
            ms.Dispose(); // Dispose of expired ms, writer's basestream is created in FinalizePacket
            ms = bw.BaseStream as MemoryStream;
            // this here failed? ye wait a moment
            await netStream.WriteAsync(ms.ToArray(), 0, (int)ms.Length);

            if (OnPacketSent != null)
                OnPacketSent(null, new PacketEventArgs(null, packet, (int)ms.Length));

            ms.Dispose();
            bw.Dispose();

        }
开发者ID:Numbers11,项目名称:uNet,代码行数:29,代码来源:PacketProcessor.cs

示例10: WriteToStream

        public async System.Threading.Tasks.Task WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
        {
            try
            {
                var buffer = new byte[65536];

                using (var audio = File.Open(m_fileName, FileMode.Open, FileAccess.Read))
                {
                    var length = (int)audio.Length;
                    var bytesRead = 1;

                    while (length > 0 && bytesRead > 0)
                    {
                        bytesRead = audio.Read(buffer, 0, Math.Min(length, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, bytesRead);
                        length -= bytesRead;
                    }
                }
            }
            catch (HttpException ex)
            {
                return;
            }
            finally
            {
                outputStream.Close();
            }
        }
开发者ID:uwe-e,项目名称:BSE.Tunes,代码行数:28,代码来源:AudioStream.cs

示例11: WriteToStream

        public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
        {
            try
            {
                Stream.Seek(0, SeekOrigin.Begin);
                var buffer = new byte[65536];
                var length = (int)Stream.Length;
                var bytesRead = 1;

                while (length > 0 && bytesRead > 0)
                {
                    bytesRead = Stream.Read(buffer, 0, Math.Min(length, buffer.Length));
                    await outputStream.WriteAsync(buffer, 0, bytesRead);
                    length -= bytesRead;
                }

            }
            catch (Exception)
            {
                return;
            }
            finally
            {
                outputStream.Close();
            }
        }
开发者ID:Flasheur111,项目名称:CatMyVideo,代码行数:26,代码来源:VideoStream.cs

示例12: StreamVideo

        public async Task StreamVideo(Stream stream, HttpContent content, TransportContext transport)
        {
            try
            {
                var buffer = new byte[65536];
                var filename = Path.Combine(String.Format("{0}{1}video.{2}", System.Web.HttpContext.Current.Server.MapPath("~"), Constants.FilePath, _fileExtension));
                using (var file = File.Open(filename, FileMode.Open, FileAccess.Read))
                {
                    var videoLength = (int)file.Length;
                    var placeInFile = 1;

                    while (videoLength > 0 && placeInFile > 0)
                    {
                        placeInFile = file.Read(buffer, 0, Math.Min(videoLength, buffer.Length));
                        await stream.WriteAsync(buffer, 0, placeInFile);
                        videoLength -= placeInFile;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.InnerException);
            }
            finally
            {
                stream.Close();
            }
        }
开发者ID:carlingkirk,项目名称:CarlingKirk.com,代码行数:28,代码来源:Video.cs

示例13: Write

        public Task Write(IContent content, Stream outputStream)
        {
            if (content.Model != null)
            {
                object output;

                var enumerable = content.Model as IEnumerable<object>;
                if (enumerable != null)
                {
                    output = ProcessList(enumerable);
                }
                else
                {
                    output = ProcessContent(content);
                }
                byte[] buffer;
                using (var writer = new StringWriter())
                {
                    new JsonWriter().Write(output, writer);
                    buffer = Encoding.Default.GetBytes(writer.ToString());
                }
                return outputStream.WriteAsync(buffer, 0, buffer.Length);
            }

            return TaskHelper.Completed();
        }
开发者ID:vandenbergjp,项目名称:Simple.Web,代码行数:26,代码来源:JsonMediaTypeHandler.cs

示例14: WriteToStream

        async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
        {
            try
            {
                var buffer = new byte[_chunkSize];
                using (var inputStream = OpenInputStream())
                {
                    var length = (int)inputStream.Length;
                    var bytesRead = 1;

                    while (length > 0 && bytesRead > 0)
                    {
                        bytesRead = inputStream.Read(buffer, 0, Math.Min(length, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, bytesRead);
                        length -= bytesRead;
                    }
                }
            }
            catch (HttpException)
            {
            }
            finally
            {
                outputStream.Close();
                outputStream.Dispose();
            }
        }
开发者ID:Robin--,项目名称:Warewolf,代码行数:27,代码来源:HttpPushContentStream.cs

示例15: ArrayPoolCopyToAsyncCore

 /// <summary>Standard read/write loop using ReadAsync on the source and WriteAsync on the destination.</summary>
 private static async Task ArrayPoolCopyToAsyncCore(Stream source, Stream destination, int bufferSize, CancellationToken cancellationToken)
 {
     byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
     bufferSize = 0; // reuse same field for high water mark to avoid needing another field in the state machine
     try
     {
         while (true)
         {
             int bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
             if (bytesRead == 0)
             {
                 break;
             }
             if (bytesRead > bufferSize)
             {
                 bufferSize = bytesRead;
             }
             await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
         }
     }
     finally
     {
         Array.Clear(buffer, 0, bufferSize); // clear only the most we used
         ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
     }
 }
开发者ID:geoffkizer,项目名称:corefx,代码行数:27,代码来源:StreamHelpers.ArrayPoolCopy.cs


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