本文整理汇总了C#中System.IO.Stream.Flush方法的典型用法代码示例。如果您正苦于以下问题:C# Stream.Flush方法的具体用法?C# Stream.Flush怎么用?C# Stream.Flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Stream
的用法示例。
在下文中一共展示了Stream.Flush方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendResponse
/// <summary>
/// // TODO
/// </summary>
/// <param name="stream"></param>
/// <param name="data"></param>
/// <param name="statusCode"></param>
/// <param name="headers"></param>
/// <param name="closeConnection">we don’t currently support persistent connection via Http1.1 so closeConnection:true</param>
/// <returns></returns>
public static int SendResponse(Stream stream, byte[] data, int statusCode, IDictionary<string,string[]> headers = null, bool closeConnection = true)
{
string initialLine = "HTTP/1.1 " + statusCode + " " + StatusCode.GetReasonPhrase(statusCode) + "\r\n";
string headersPack = initialLine;
if (headers == null)
headers = new Dictionary<string,string[]>(StringComparer.OrdinalIgnoreCase);
if (!headers.ContainsKey("Connection") && closeConnection)
{
headers.Add("Connection", new[] { "Close" });
}
if (!headers.ContainsKey("Content-Length"))
{
headers.Add("Content-Length", new [] { Convert.ToString(data.Length) });
}
headersPack = headers.Aggregate(headersPack, (current, header) => current + (header.Key + ": " + String.Join(",", header.Value) + "\r\n")) + "\r\n";
int sent = stream.Write(Encoding.UTF8.GetBytes(headersPack));
//Send headers and body separately
//TODO It's needed for our client. Think out a way to avoid separate sending.
stream.Flush();
if (data.Length > 0)
sent += stream.Write(data);
Thread.Sleep(200);
stream.Flush();
return sent;
}
示例2: CopyStream
public static void CopyStream(Stream outputStream, Stream inputStream)
{
int bytesRead;
var buffer = new byte[Globals.BufferSize];
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, bytesRead);
outputStream.Flush();
}
outputStream.Flush();
}
示例3: ReceiveStream
public static void ReceiveStream(Stream stream, Stream out_stream)
{
long _len = ReceiveLong(stream);
long _read = 0;
byte[] _buffer = new byte[blocksize];
while (_read < _len)
{
_read = _read + stream.Read(_buffer, 0, blocksize);
out_stream.Write(_buffer, 0, blocksize);
out_stream.Flush();
}
out_stream.Write(_buffer, 0, Convert.ToInt32(_len-_read));
out_stream.Flush();
}
示例4: GetData
public override void GetData(object target, Stream outgoingData)
{
var bodyFrame = (target as BodyFrame);
if (bodyFrame == null)
return;
var formatter = new BinaryFormatter();
var internalBodyFrame = new InternalBody2DFrame();
var frameDescription = bodyFrame.GetFrameDescription();
internalBodyFrame.FrameDescription = new InternalFrameDescription()
{
BytesPerPixel = frameDescription.BytesPerPixel,
DiagonalFieldOfView = frameDescription.DiagonalFieldOfView,
Height = frameDescription.Height,
HorizontalFieldOfView = frameDescription.HorizontalFieldOfView,
LengthInPixels = frameDescription.LengthInPixels,
VerticalFieldOfView = frameDescription.VerticalFieldOfView,
Width = frameDescription.Width,
};
internalBodyFrame.BodyCount = bodyFrame.BodyCount;
internalBodyFrame.FloorClipPlane = bodyFrame.FloorClipPlane.ToInternalVector4();
internalBodyFrame.RelativeTime = bodyFrame.RelativeTime;
var array = bodyFrame.GetNewPixelArray();
bodyFrame.ToBitmapSource(true, 5, 3).CopyPixels(array, frameDescription.Width * ((PixelFormats.Bgr32.BitsPerPixel + 7) / 8), 0);
internalBodyFrame.Image = array;
formatter.Serialize(outgoingData, internalBodyFrame);
outgoingData.Flush();
}
开发者ID:andreasassetti,项目名称:Kinect-v2-Visual-Studio-Visualizer,代码行数:35,代码来源:BodyFrameVisualizerObjectSource.cs
示例5: SavePngAsync
/// <summary>
/// Encodes a WriteableBitmap object into a PNG stream.
/// </summary>
/// <param name="writeableBitmap">The writeable bitmap.</param>
/// <param name="outputStream">The image data stream.</param>
/// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
public static async Task SavePngAsync(this WriteableBitmap writeableBitmap, Stream outputStream)
{
#if WINDOWS_PHONE
WriteHeader(outputStream, writeableBitmap);
WritePhysics(outputStream);
////WriteGamma(outputStream);
WriteDataChunks(outputStream, writeableBitmap);
WriteFooter(outputStream);
outputStream.Flush();
await Task.FromResult(0);
#else
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, outputStream.AsRandomAccessStream());
var pixels = writeableBitmap.PixelBuffer.ToArray();
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, ResolutionDpi, ResolutionDpi, pixels);
await encoder.FlushAsync();
#endif
}
示例6: Copy
/// <summary>
/// Copy the contents of one <see cref="Stream"/> to another.
/// </summary>
/// <param name="source">The stream to source data from.</param>
/// <param name="destination">The stream to write data to.</param>
/// <param name="buffer">The buffer to use during copying.</param>
public static void Copy(Stream source, Stream destination, byte[] buffer)
{
if (source == null) {
throw new ArgumentNullException(nameof(source));
}
if (destination == null) {
throw new ArgumentNullException(nameof(destination));
}
if (buffer == null) {
throw new ArgumentNullException(nameof(buffer));
}
// Ensure a reasonable size of buffer is used without being prohibitive.
if (buffer.Length < 128) {
throw new ArgumentException("Buffer is too small", nameof(buffer));
}
bool copying = true;
while (copying) {
int bytesRead = source.Read(buffer, 0, buffer.Length);
if (bytesRead > 0) {
destination.Write(buffer, 0, bytesRead);
} else {
destination.Flush();
copying = false;
}
}
}
示例7: Workaround_Ladybug318918
public static void Workaround_Ladybug318918(Stream s)
{
// This is a workaround for this issue:
// https://connect.microsoft.com/VisualStudio/feedback/details/318918
// It's required only on NETCF.
s.Flush();
}
示例8: CopyStream
/// <summary>
/// Копирование из потока в поток
/// </summary>
/// <param name="input"></param>
/// <param name="output"></param>
public static void CopyStream(Stream input, Stream output)
{
try
{
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
while (true)
{
int read = input.Read(buffer, 0, buffer.Length);
if (read <= 0)
{
input.Flush();
input.Close();
return;
}
output.Write(buffer, 0, read);
}
}
catch (Exception ex)
{
DebugHelper.WriteLogEntry(ex, "Streem copy error");
output = null;
}
}
示例9: Copy
private void Copy(NetworkStream src, Stream dest, int bufferSize)
{
if(!src.DataAvailable)
return;
try
{
var buffer = new byte[bufferSize];
var bytesRead = 0;
do
{
bytesRead = src.Read(buffer, 0, buffer.Length);
dest.Write(buffer, 0, bytesRead);
PrintHexData(buffer, bytesRead);
} while (bytesRead > 0 && src.DataAvailable);
dest.Flush();
}
catch(IOException ioException)
{
if(ioException.InnerException is SocketException)
{
var se = (SocketException)ioException.InnerException;
if (se.SocketErrorCode != SocketError.ConnectionAborted)
throw;
}
}
}
示例10: ReadFile
/// <summary>
/// Читает из архива очередной файл.
/// </summary>
/// <param name="outputStream">
/// Поток, в который записывается содержимое прочитанного файла.
/// </param>
/// <returns>Имя прочитанного файла или null, если прочесть нечего.</returns>
public string ReadFile( Stream outputStream )
{
// прочитать очередную запись из архива
ZipEntry entry = zipStream.GetNextEntry();
// записей больше нет
if (entry == null)
return null;
// прочитать имя файла
string fileName = entry.Name;
byte[] buffer = new byte[4096];
while (true)
{
// прочитать блок из архива
int bytesRead = zipStream.Read( buffer, 0, buffer.Length );
string str = Encoding.UTF8.GetString(buffer);
// если ничего не прочитано, прекратить считывание
if (bytesRead == 0)
break;
// иначе, записать блок в результирующий поток
outputStream.Write( buffer, 0, bytesRead );
}
// переместить указатель результирующего потока на начало
outputStream.Flush();
outputStream.Seek( 0, SeekOrigin.Begin );
return fileName;
}
示例11: GetData
public override void GetData(object target, Stream outgoingData)
{
var longExposureInfraredFrame = (target as LongExposureInfraredFrame);
if (longExposureInfraredFrame == null)
return;
var formatter = new BinaryFormatter();
var internalLongExposureInfraredFrame = new InternalLongExposureInfraredFrame();
internalLongExposureInfraredFrame.FrameDescription = new InternalFrameDescription()
{
BytesPerPixel = longExposureInfraredFrame.FrameDescription.BytesPerPixel,
DiagonalFieldOfView = longExposureInfraredFrame.FrameDescription.DiagonalFieldOfView,
Height = longExposureInfraredFrame.FrameDescription.Height,
HorizontalFieldOfView = longExposureInfraredFrame.FrameDescription.HorizontalFieldOfView,
LengthInPixels = longExposureInfraredFrame.FrameDescription.LengthInPixels,
VerticalFieldOfView = longExposureInfraredFrame.FrameDescription.VerticalFieldOfView,
Width = longExposureInfraredFrame.FrameDescription.Width,
};
internalLongExposureInfraredFrame.RelativeTime = longExposureInfraredFrame.RelativeTime;
internalLongExposureInfraredFrame.Image = longExposureInfraredFrame.GetPixelArrayFrame();
formatter.Serialize(outgoingData, internalLongExposureInfraredFrame);
outgoingData.Flush();
}
开发者ID:andreasassetti,项目名称:Kinect-v2-Visual-Studio-Visualizer,代码行数:28,代码来源:LongExposureInfraredFrameVisualizerObjectSource.cs
示例12: SendHeader
public static void SendHeader(Header header, Stream stream)
{
string sBuffer = "";
sBuffer = header.ToString();
stream.Write(Encoding.ASCII.GetBytes(sBuffer), 0, sBuffer.Length);
stream.Flush();
}
示例13: Copy
public static void Copy(Stream source, Stream destination, byte[] buffer)
{
if (source == null) {
throw new ArgumentNullException("source");
}
if (destination == null) {
throw new ArgumentNullException("destination");
}
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if (buffer.Length < 128) {
throw new ArgumentException("Buffer is too small", "buffer");
}
bool copying = true;
while (copying) {
int bytesRead = source.Read(buffer, 0, buffer.Length);
if (bytesRead > 0) {
destination.Write(buffer, 0, bytesRead);
}
else {
destination.Flush();
copying = false;
}
}
}
示例14: SendHttpResponse
private void SendHttpResponse(TcpClient client, Stream stream, HttpListenerResponse response, byte[] body)
{
// Status line
var statusLine = $"HTTP/1.1 {response.StatusCode} {response.StatusDescription}\r\n";
var statusBytes = Encoding.ASCII.GetBytes(statusLine);
stream.Write(statusBytes, 0, statusBytes.Length);
// Headers
foreach (var key in response.Headers.AllKeys)
{
var value = response.Headers[key];
var line = $"{key}: {value}\r\n";
var lineBytes = Encoding.ASCII.GetBytes(line);
stream.Write(lineBytes, 0, lineBytes.Length);
}
// Content-Type header
var contentType = Encoding.ASCII.GetBytes($"Content-Type: {response.ContentType}\r\n");
stream.Write(contentType, 0, contentType.Length);
// Content-Length header
var contentLength = Encoding.ASCII.GetBytes($"Content-Length: {body.Length}\r\n");
stream.Write(contentLength, 0, contentLength.Length);
// "Connection: close", to tell the client we can't handle persistent TCP connections
var connection = Encoding.ASCII.GetBytes("Connection: close\r\n");
stream.Write(connection, 0, connection.Length);
// Blank line to indicate end of headers
stream.Write(new[] { (byte)'\r', (byte)'\n' }, 0, 2);
// Body
stream.Write(body, 0, body.Length);
stream.Flush();
// Graceful socket shutdown
client.Client.Shutdown(SocketShutdown.Both);
client.Dispose();
}
示例15: AsyncCopy
public static WaitHandle AsyncCopy(this Stream src, Stream dst)
{
var evt = new ManualResetEvent(false);
var buffer = new byte[BUFFER_SIZE];
AsyncCallback cbk = null;
cbk = (asyncReadResult) =>
{
int bytesRead = src.EndRead(asyncReadResult);
if (bytesRead > 0)
{
//Console.Write("r");
dst.BeginWrite(buffer, 0, bytesRead,
(asyncWriteResult) =>
{
//Console.Write("w");
dst.EndWrite(asyncWriteResult);
src.BeginRead(buffer, 0, buffer.Length, cbk, null);
}, null);
}
else
{
Console.WriteLine();
dst.Flush();
dst.Position = 0;
evt.Set();
}
};
src.BeginRead(buffer, 0, buffer.Length, cbk, buffer);
return evt;
}