本文整理汇总了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;
}
示例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);
}
}
示例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);
}
示例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;
}
示例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);
}
示例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;
}
示例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);
}
}
示例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);
}
}
}
示例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();
}
示例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();
}
}
示例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();
}
}
示例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();
}
}
示例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();
}
示例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();
}
}
示例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);
}
}