本文整理汇总了C#中Stream.Flush方法的典型用法代码示例。如果您正苦于以下问题:C# Stream.Flush方法的具体用法?C# Stream.Flush怎么用?C# Stream.Flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Stream
的用法示例。
在下文中一共展示了Stream.Flush方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: connect
public void connect() {
try {
if (connected) {
throw new SocketIoClientException("already connected");
}
socket = createSocket();
stream = socket.GetStream();
input = new StreamReader(stream);
byte[] bytes = handshake.getHandshake();
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
bool handshakeComplete = false;
List<string> handshakeLines = new List<string>();
string line;
while(!handshakeComplete) {
line = input.ReadLine().Trim();
if (line.Length>0) {
handshakeLines.Add(line);
} else {
handshakeComplete = true;
}
}
char[] response = new char[16];
input.ReadBlock(response, 0, response.Length);
handshake.verifyServerStatusLine(handshakeLines[0]);
/* Verifying handshake fails... */
//handshake.verifyServerResponse(response);
handshakeLines.RemoveAt(0);
Dictionary<string, string> headers = new Dictionary<string, string>();
foreach (string l in handshakeLines) {
string[] keyValue = l.Split(new char[] {':'},2);
headers.Add(keyValue[0].Trim(), keyValue[1].Trim());
}
handshake.verifyServerHandshakeHeaders(headers);
receiver = new SocketIoClientReceiver(this);
connected = true;
eventHandler.OnOpen();
(new Thread(receiver.run)).Start();
} catch (SocketIoClientException wse) {
throw wse;
} catch (IOException ioe) {
throw new SocketIoClientException("error while connecting: " + ioe.StackTrace, ioe);
}
}
示例2: Merge
public void Merge(Stream outputStream) {
if (outputStream == null || !outputStream.CanWrite)
throw new Exception("OutputStream is null or is read only!");
Document newDocument = null;
try {
newDocument = new Document();
PdfWriter pdfWriter = PdfWriter.GetInstance(newDocument, outputStream);
newDocument.Open();
PdfContentByte pdfContentByte = pdfWriter.DirectContent;
if (EnablePagination)
documents.ForEach(delegate(PdfReader doc)
{
totalPages += doc.NumberOfPages;
});
int currentPage = 1;
foreach (PdfReader pdfReader in documents) {
for (int page = 1; page <= pdfReader.NumberOfPages; page++) {
newDocument.NewPage();
PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader, page);
pdfContentByte.AddTemplate(importedPage, 0, 0);
if (EnablePagination) {
pdfContentByte.BeginText();
pdfContentByte.SetFontAndSize(baseFont, 9);
pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER,
string.Format("{0} od {1}", currentPage++, totalPages), 520, 5, 0);
pdfContentByte.EndText();
}
}
}
}
finally {
outputStream.Flush();
if (newDocument != null)
newDocument.Close();
outputStream.Close();
}
}
示例3: DecodeBinaryXML
/// <summary>
/// Decode a bytestream that was encoded by WCF's BinaryEncodingBindingElement. Will throw if the bytestream does
/// not decode properly or the result is not valid XML. I/O streams are flushed but not closed.
/// </summary>
/// <param name="explodeNewlines">if true, the returned string will be nicely indented according to
/// element depth, and each attribute will be placed on its own line</param>
/// <returns></returns>
public void DecodeBinaryXML(Stream binaryInput, Stream xmlOutput, bool? explodeNewlines)
{
// defaults
var explode = explodeNewlines ?? false;
// parse bytestream into the XML DOM
var doc = new XmlDocument();
using (var binaryReader = XmlDictionaryReader.CreateBinaryReader(binaryInput, WcfDictionaryBuilder.Dict, XmlDictionaryReaderQuotas.Max))
{
doc.Load(binaryReader);
}
// write document to the output stream with customized settings
var settings = new XmlWriterSettings()
{
CheckCharacters = false,
CloseOutput = false,
ConformanceLevel = ConformanceLevel.Auto,
Encoding = m_encoding,
Indent = explode,
IndentChars = "\t",
NewLineChars = Environment.NewLine,
NewLineHandling = explode ? NewLineHandling.Replace : NewLineHandling.None,
NewLineOnAttributes = explode
// QuoteChar = '"'
};
using (var writer = XmlWriter.Create(xmlOutput, settings))
{
doc.Save(writer);
writer.Flush();
xmlOutput.Flush();
}
}
示例4: NegativeConsoleOutputTests
private static void NegativeConsoleOutputTests(Stream stream)
{
//ConsoleStream.Length should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => { long x = stream.Length; });
//ConsoleStream.get_Position should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => { long x = stream.Position; });
//ConsoleStream.set_Position should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => stream.Position = 50L);
//ConsoleStream.SetLength should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => stream.SetLength(50L));
// Flushing a stream is fine.
stream.Flush();
//Read and write methods
//ConsoleStream.Read(null) should throw ArgumentNullException
Assert.Throws<ArgumentNullException>(() => stream.Read(null, 0, 1));
//ConsoleStream.Read() should throw ArgumentOutOfRangeException
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(new byte[] { 0, 1 }, -1, 0));
//ConsoleStream.Read() should throw ArgumentOutOfRangeException
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(new byte[] { 0, 1 }, 0, -1));
//ConsoleStream.Read() should throw ArgumentException
Assert.Throws<ArgumentException>(() => stream.Read(new byte[] { 0, 1 }, 0, 50));
//ConsoleStream.Read() should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => stream.Read(new byte[] { 0, 1 }, 0, 2));
//ConsoleStream.Write() should throw ArgumentNullException
Assert.Throws<ArgumentNullException>(() => stream.Write(null, 0, 1));
//ConsoleStream.Write() should throw ArgumentOutOfRangeException
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(new byte[] { 0, 1 }, -1, 0));
//ConsoleStream.Write() should throw ArgumentOutOfRangeException
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(new byte[] { 0, 1 }, 0, -1));
//ConsoleStream.Write() should throw ArgumentException
Assert.Throws<ArgumentException>(() => stream.Write(new byte[] { 0, 1 }, 0, 50));
//ConsoleStream.Write() should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => stream.Seek(0L, SeekOrigin.Begin));
// Close the stream and make sure we can no longer read, write or flush
stream.Dispose();
//ConsoleStream.Read() should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => stream.Read(new byte[] { 0, 1 }, 0, 1));
//ConsoleStream.Write() should throw NotSupportedException
Assert.Throws<NotSupportedException>(() => stream.Write(new byte[] { 0, 1 }, 0, 1));
//ConsoleStream.Flush() should throw NotSupportedException
Assert.Throws<ObjectDisposedException>(() => stream.Flush());
}
示例5: Copy
public void Copy(Stream source, Stream target)
{
byte[] buffer = new byte[2054];//new byte[0x10000];
int bytes;
try {
while ((bytes = source.Read(buffer, 0, buffer.Length)) > 0) {
target.Write(buffer, 0, bytes);
}
}
finally {
target.Flush();
// Or target.Close(); if you're done here already.
}
}
示例6: ExtractFile
/// <summary>
/// Copy the contents of a stored file into an opened stream
/// </summary>
/// <param name="zfe">
/// Entry information of file to extract
/// </param>
/// <param name="stream">
/// Stream to store the uncompressed data
/// </param>
/// <returns>
/// True if success, false if not.
/// </returns>
/// <remarks>
/// Unique compression methods are Store and Deflate
/// </remarks>
public bool ExtractFile(ZipFileEntry zfe, Stream stream)
{
if (!stream.CanWrite)
{
throw new InvalidOperationException("Stream cannot be written");
}
// check signature
var signature = new byte[4];
this.zipFileStream.Seek(zfe.HeaderOffset, SeekOrigin.Begin);
this.zipFileStream.Read(signature, 0, 4);
if (BitConverter.ToUInt32(signature, 0) != 0x04034b50)
{
return false;
}
// Select input stream for inflating or just reading
Stream inStream = this.GetZipStream(zfe);
if (inStream == null)
{
return false;
}
// Buffered copy
var buffer = new byte[16384];
this.zipFileStream.Seek(zfe.FileOffset, SeekOrigin.Begin);
uint bytesPending = zfe.FileSize;
while (bytesPending > 0)
{
int bytesRead = inStream.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length));
stream.Write(buffer, 0, bytesRead);
bytesPending -= (uint)bytesRead;
}
stream.Flush();
if (zfe.Method == Compression.Deflate)
{
inStream.Dispose();
}
return true;
}
示例7: WriteTransformedXmlDataToStream
/// <summary>
/// Always use UTF-8 for encoding, else you will screw it up.
/// </summary>
/// <param name="s"></param>
/// <param name="xmlData"></param>
/// <param name="transform"></param>
/// <param name="args"></param>
private void WriteTransformedXmlDataToStream(Stream s, string xmlData, XslCompiledTransform transform, XsltArgumentList args)
{
XPathDocument data = new XPathDocument(new MemoryStream(Encoding.UTF8.GetBytes(xmlData)));
transform.Transform(data, args, s);
s.Flush();
data = null;
}
示例8: getFileSize
/* Get the Size of a File */
public string getFileSize(string fileName)
{
string _result = null;
string _fileInfo = null;
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Establish Return Communication with the FTP Server */
ftpStream = ftpResponse.GetResponseStream();
/* Get the FTP Server's Response Stream */
StreamReader _ftpReader = new StreamReader(ftpStream);
/* Store the Raw Response */
/* Read the Full Response Stream */
while (_ftpReader.Peek() != -1)
{
_fileInfo = _ftpReader.ReadToEnd();
}
_ftpReader.Close();
/* Return File Size */
_result = _fileInfo;
}
catch (Exception ex)
{
//Console.WriteLine(ex.ToString());
_result = ex.Message.ToString();
}
finally
{
/* Resource Cleanup */
ftpStream.Flush();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
return _result;
}
示例9: ExtractFile
/// <summary>
/// Copy the contents of a stored file into an opened stream
/// </summary>
/// <param name="_zfe">Entry information of file to extract</param>
/// <param name="_stream">Stream to store the uncompressed data</param>
/// <returns>True if success, false if not.</returns>
/// <remarks>Unique compression methods are Store and Deflate</remarks>
public bool ExtractFile(ZipFileEntry _zfe, Stream _stream)
{
if (!_stream.CanWrite)
throw new InvalidOperationException("Stream cannot be written");
// check signature
byte[] signature = new byte[4];
this.ZipFileStream.Seek(_zfe.HeaderOffset, SeekOrigin.Begin);
this.ZipFileStream.Read(signature, 0, 4);
if (BitConverter.ToUInt32(signature, 0) != 0x04034b50)
return false;
// Select input stream for inflating or just reading
Stream inStream;
if (_zfe.Method == Compression.Store)
inStream = this.ZipFileStream;
else if (_zfe.Method == Compression.Deflate)
inStream = new DeflateStream(this.ZipFileStream, CompressionMode.Decompress, true);
else
return false;
// Buffered copy
byte[] buffer = new byte[16384];
this.ZipFileStream.Seek(_zfe.FileOffset, SeekOrigin.Begin);
uint bytesPending = _zfe.FileSize;
while (bytesPending > 0)
{
int bytesRead = inStream.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length));
_stream.Write(buffer, 0, bytesRead);
bytesPending -= (uint)bytesRead;
}
_stream.Flush();
if (_zfe.Method == Compression.Deflate)
inStream.Dispose();
return true;
}
示例10: Decompress
private static void Decompress(Stream inputStream, Stream outputStream)
{
SevenZip.Compression.LZMA.Decoder coder = new SevenZip.Compression.LZMA.Decoder();
// Read decoder properties
byte[] properties = new byte[5]; // 5 comes from kPropSize (LzmaEncoder.cs)
inputStream.Read(properties, 0, 5);
// Read the size of the output stream.
byte [] fileLengthBytes = new byte[8];
inputStream.Read(fileLengthBytes, 0, 8);
long fileLength = BitConverter.ToInt64(fileLengthBytes, 0);
// Decode
coder.SetDecoderProperties(properties);
coder.Code(inputStream, outputStream, inputStream.Length, fileLength, null);
outputStream.Flush();
outputStream.Close();
}
示例11: Compress
private static void Compress(Stream inputStream, Stream outputStream, LZMADictionarySize dictSize)
{
SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder();
Int32 dictSize32 = (Int32)dictSize;
coder.SetCoderProperties (new SevenZip.CoderPropID[] {SevenZip.CoderPropID.DictionarySize}, new object[] {dictSize32});
// Write encoder properties to output stream
coder.WriteCoderProperties(outputStream);
// Write size of input stream to output stream.
outputStream.Write(BitConverter.GetBytes(inputStream.Length), 0, 8);
// Encode
coder.Code(inputStream, outputStream, inputStream.Length, -1, null);
outputStream.Flush();
outputStream.Close();
}
示例12: CopyStream
/// <summary>
/// CopyStream utility that is guaranteed to return the number of bytes copied (may be less then requested,
/// if source stream doesn't have enough data)
/// </summary>
/// <param name="sourceStream">stream to read from</param>
/// <param name="targetStream">stream to write to </param>
/// <param name="bytesToCopy">number of bytes to be copied(use Int64.MaxValue if the whole stream needs to be copied)</param>
/// <param name="bufferSize">number of bytes to be copied (usually it is 4K for scenarios where we expect a lot of data
/// like in SparseMemoryStream case it could be larger </param>
/// <returns>bytes copied (might be less than requested if source stream is too short</returns>
/// <remarks>Neither source nor target stream are seeked; it is up to the caller to make sure that their positions are properly set.
/// Target stream isn't truncated even if it has more data past the area that was copied.</remarks>
internal static long CopyStream(Stream sourceStream, Stream targetStream, long bytesToCopy, int bufferSize)
{
Debug.Assert(sourceStream != null);
Debug.Assert(targetStream != null);
Debug.Assert(bytesToCopy >= 0);
Debug.Assert(bufferSize > 0);
byte[] buffer = new byte[bufferSize];
// let's read the whole block into our buffer
long bytesLeftToCopy = bytesToCopy;
while (bytesLeftToCopy > 0)
{
int bytesRead = sourceStream.Read(buffer, 0, (int)Math.Min(bytesLeftToCopy, (long)bufferSize));
if (bytesRead == 0)
{
targetStream.Flush();
return bytesToCopy - bytesLeftToCopy;
}
targetStream.Write(buffer, 0, bytesRead);
bytesLeftToCopy -= bytesRead;
}
// It must not be negative
Debug.Assert(bytesLeftToCopy == 0);
targetStream.Flush();
return bytesToCopy;
}
示例13: MakeGifRoutine
static IEnumerator MakeGifRoutine(List<RenderTexture> textures, float frameLength, Stream output, bool closeWhenDone)
{
var gifEncoder = new Gif.Components.AnimatedGifEncoder();
gifEncoder.SetQuality(10);
gifEncoder.SetRepeat(0);
gifEncoder.SetDelay((int)(frameLength * 1000));
gifEncoder.Start(output);
int w = textures[0].width;
int h = textures[0].height;
var tex = new Texture2D(w,h, TextureFormat.ARGB32, false, true);
var imageStart = new ManualResetEvent(false);
Gif.Components.Image image = null;
bool done = false;
bool processed = false;
var worker = new Thread(() => {
while (!done) {
imageStart.WaitOne();
imageStart.Reset();
gifEncoder.AddFrame(image);
processed = true;
}
});
worker.Start();
for (int picCount = 0; picCount < textures.Count; picCount++) {
var tempTex = textures[picCount];
RenderTexture.active = tempTex;
tex.ReadPixels(new Rect(0, 0, w, h), 0, 0);
RenderTexture.ReleaseTemporary(tempTex);
image = new Gif.Components.Image(tex);
processed = false;
imageStart.Set();
while (!processed) {
yield return null;
}
}
done = true;
textures.Clear();
gifEncoder.Finish();
DestroyImmediate(tex);
output.Flush();
if (closeWhenDone) {
output.Close();
}
}
示例14: upload
/* Upload File */
public string upload(string remoteFile, string localFile)
{
string _result = null;
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + host + "/" + remoteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
/* Establish Return Communication with the FTP Server */
ftpStream = ftpRequest.GetRequestStream();
/* Open a File Stream to Read the File for Upload */
/* use openorcreate as just open will overwrite the file if it already exists */
FileStream _localFileStream = new FileStream(localFile, FileMode.OpenOrCreate);
/* Buffer for the Downloaded Data */
byte[] _byteBuffer = new byte[bufferSize];
int _bytesSent = _localFileStream.Read(_byteBuffer, 0, bufferSize);
/* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
//try
//{
while (_bytesSent != 0)
{
ftpStream.Write(_byteBuffer, 0, _bytesSent);
_bytesSent = _localFileStream.Read(_byteBuffer, 0, bufferSize);
}
//}
//catch (Exception ex) { Console.WriteLine(ex.ToString()); }
_localFileStream.Close();
}
catch (Exception ex)
{
//Console.WriteLine(ex.ToString());
_result = ex.Message.ToString();
}
finally
{
/* Resource Cleanup */
ftpStream.Flush();
ftpStream.Close();
ftpRequest = null;
}
return _result;
}
示例15: directoryListDetailed
/* List Directory Contents in Detail (Name, Size, Created, etc.) */
public List<string> directoryListDetailed(string directory)
{
List<string> _directoryList = null;
string _chr = "|";
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Establish Return Communication with the FTP Server */
ftpStream = ftpResponse.GetResponseStream();
/* Get the FTP Server's Response Stream */
StreamReader _ftpReader = new StreamReader(ftpStream);
/* Store the Raw Response */
string _directoryRaw = null;
/* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
while (_ftpReader.Peek() != -1)
{
_directoryRaw += _ftpReader.ReadLine() + _chr;
}
_ftpReader.Close();
/* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
_directoryList = _directoryRaw.Split(_chr.ToCharArray()).ToList();
}
catch (Exception ex) {
//Console.WriteLine(ex.ToString());
_directoryList.Add(ex.Message.ToString());
}
finally
{
/* Resource Cleanup */
ftpStream.Flush();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
/* Return an Empty string Array if an Exception Occurs */
return _directoryList;
}