本文整理汇总了C#中System.IO.MemoryStream.Flush方法的典型用法代码示例。如果您正苦于以下问题:C# MemoryStream.Flush方法的具体用法?C# MemoryStream.Flush怎么用?C# MemoryStream.Flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.MemoryStream
的用法示例。
在下文中一共展示了MemoryStream.Flush方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: With_WebSocket_CanReadSmallFrame
public void With_WebSocket_CanReadSmallFrame()
{
var handshake = GenerateSimpleHandshake();
using (var ms = new MemoryStream())
using (WebSocket ws = new WebSocketRfc6455(ms, new WebSocketListenerOptions() { PingTimeout = Timeout.InfiniteTimeSpan }, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1), new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2), handshake.Request,handshake.Response, handshake.NegotiatedMessageExtensions))
{
ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
var reader = ws.ReadMessageAsync(CancellationToken.None).Result;
Assert.IsNotNull(reader);
using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true))
{
String s = sr.ReadToEnd();
Assert.AreEqual("Hi", s);
}
ms.Seek(0, SeekOrigin.Begin);
ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
reader = ws.ReadMessageAsync(CancellationToken.None).Result;
Assert.IsNotNull(reader);
using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true))
{
String s = sr.ReadToEndAsync().Result;
Assert.AreEqual("Hi", s);
}
}
}
示例2: GetBytes
/// <summary>
/// Gets the bytes from the Web using the specified uri.
/// </summary>
/// <param name="uri">File Web location.</param>
/// <param name="onProgress">Function executed when progress changes. Return true to cancel the operation, false to continue.</param>
/// <returns>Encoded image or undefined output in case if the operation is canceled.</returns>
public static byte[] GetBytes(this Uri uri, Func<float, bool> onProgress = null)
{
byte[] output = null;
var request = (HttpWebRequest)WebRequest.Create(uri.AbsoluteUri);
using (WebResponse response = request.GetResponse())
using (Stream source = response.GetResponseStream())
using(MemoryStream target = new MemoryStream())
{
int bytes, copiedBytes = 0;
var buffer = new byte[1024];
while ((bytes = source.Read(buffer, 0, buffer.Length)) > 0)
{
target.Write(buffer, 0, bytes);
copiedBytes += bytes;
if (onProgress != null)
{
bool shouldCancel = onProgress((float)copiedBytes / response.ContentLength);
if (shouldCancel)
break;
}
}
target.Flush();
output = target.ToArray();
}
return output;
}
示例3: Execute
public override bool Execute()
{
Log.LogMessage( MessageImportance.Low, "Packing M-Files Application." );
// Make sure the collections are never null.
References = References ?? new ITaskItem[ 0 ];
SourceFiles = SourceFiles ?? new ITaskItem[ 0 ];
DefaultEnvironments = DefaultEnvironments ?? new string[ 0 ];
// Create the application package contents.
var references = References.Select( item => new Reference( item ) ).ToList();
var files = SourceFiles.Select( item => new PackageFile( item ) ).ToList();
var appDef = CreateApplicationDefinition( references, files );
var outputZip = CreatePackage( references, files );
// Serialize the application definition file.
var stream = new MemoryStream();
var serializer = new XmlSerializer( typeof( ApplicationDefinition ) );
serializer.Serialize( stream, appDef );
stream.Flush();
stream.Position = 0;
outputZip.AddEntry( "appdef.xml", stream );
// Save the zip.
outputZip.Save();
return true;
}
示例4: Encode
public override byte[] Encode(byte[] bytes)
{
using (var inputstr = new MemoryStream(bytes))
using (var outputstr = new MemoryStream())
{
// http://stackoverflow.com/questions/9050260/what-does-a-zlib-header-look-like
// http://stackoverflow.com/questions/18450297/is-it-possible-to-use-the-net-deflatestream-for-pdf-creation
// https://web.archive.org/web/20130905215303/http://connect.microsoft.com/VisualStudio/feedback/details/97064/deflatestream-throws-exception-when-inflating-pdf-streams
//#if IONIC
using (var dstream = new Ionic.Zlib.ZlibStream(outputstr, Ionic.Zlib.CompressionMode.Compress))
{
dstream.FlushMode = Ionic.Zlib.FlushType.Finish;
//#elif NET40
// using (var dstream = new System.IO.Compression.DeflateStream(outputstr, System.IO.Compression.CompressionMode.Compress))
// {
// // Zlib magic header (Default Compression):
// outputstr.WriteByte(0x78);
// outputstr.WriteByte(0x9C);
//#else //NET45+
// using (var dstream = new System.IO.Compression.DeflateStream(outputstr, System.IO.Compression.CompressionLevel.Optimal))
// {
// // Zlib magic header (Best Compression):
// outputstr.WriteByte(0x78);
// outputstr.WriteByte(0xDA);
//#endif
inputstr.CopyTo(dstream);
inputstr.Flush();
}
return outputstr.ToArray();
}
}
示例5: SendMessage
public static void SendMessage(IntPtr hWnd, string message)
{
BinaryFormatter b = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
b.Serialize(stream, message);
stream.Flush();
// Now move the data into a pointer so we can send
// it using WM_COPYDATA:
// Get the length of the data:
int dataSize = (int)stream.Length;
if (dataSize > 0)
{
byte[] data = new byte[dataSize];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(data, 0, dataSize);
IntPtr ptrData = Marshal.AllocCoTaskMem(dataSize);
Marshal.Copy(data, 0, ptrData, dataSize);
COPYDATASTRUCT cds = new COPYDATASTRUCT();
cds.cbData = dataSize;
cds.dwData = IntPtr.Zero;
cds.lpData = ptrData;
int res = SendMessage(hWnd, WM_COPYDATA, 0, ref cds);
// Clear up the data:
Marshal.FreeCoTaskMem(ptrData);
}
stream.Close();
}
示例6: ParseCurrentBuffer
private void ParseCurrentBuffer()
{
try
{
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
var str = TextBox1.Text;
sw.Write(str);
sw.Flush();
ms.Flush();
ms.Position = 0;
try
{
var content = XamlReader.Load(ms);
if (content != null)
{
cc.Children.Clear();
cc.Children.Add((UIElement) content);
}
TextBox1.Foreground = Brushes.Black;
ErrorText.Text = "";
}
catch (XamlParseException xpe)
{
TextBox1.Foreground = Brushes.Red;
TextBox1.TextWrapping = TextWrapping.Wrap;
ErrorText.Text = xpe.Message;
}
}
catch (Exception)
{
// ignored
}
}
示例7: RecordedVideoFrame
public RecordedVideoFrame(ColorImageFrame colorFrame)
{
if (colorFrame != null)
{
byte[] bits = new byte[colorFrame.PixelDataLength];
colorFrame.CopyPixelDataTo(bits);
int BytesPerPixel = colorFrame.BytesPerPixel;
int Width = colorFrame.Width;
int Height = colorFrame.Height;
var bmp = new WriteableBitmap(Width, Height, 96, 96, PixelFormats.Bgr32, null);
bmp.WritePixels(new System.Windows.Int32Rect(0, 0, Width, Height), bits, Width * BytesPerPixel, 0);
JpegBitmapEncoder jpeg = new JpegBitmapEncoder();
jpeg.Frames.Add(BitmapFrame.Create(bmp));
var SaveStream = new MemoryStream();
jpeg.Save(SaveStream);
SaveStream.Flush();
JpegData = SaveStream.ToArray();
}
else
{
return;
}
}
示例8: ProcessAction
public void ProcessAction(Object eventObject)
{
lock (blacklistLock)
{
if(blacklist.Contains(eventObject))
{
blacklist.Remove(eventObject);
return;
}
}
var memoryStream = new MemoryStream();
var gzipStream = new GZipStream(memoryStream, CompressionMode.Compress);
var writer = new StreamWriter(gzipStream);
serializer.Serialize(writer, eventObject);
writer.Flush();
gzipStream.Flush();
memoryStream.Flush();
writer.Close();
gzipStream.Close();
memoryStream.Close();
var obj = new EventObject { MessageType = eventObject.GetType().AssemblyQualifiedName, MessageBody = memoryStream.ToArray(), SessionId = sessionId };
eventRepository.Save(obj);
}
示例9: SaveJPG100
public static void SaveJPG100(this Bitmap image, MemoryStream stream)
{
stream.Flush();
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 75L);
image.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
示例10: Render
public override IDocument Render(IDictionary<string, object> context)
{
Debug.Assert(context != null);
Debug.Assert(this.engine != null);
if (context == null)
{
throw new ArgumentNullException("context");
}
//执行主要内容的渲染过程
using (var inStream = new MemoryStream(base.GetBuffer(), false))
using (var reader = new StreamReader(inStream, Encoding.UTF8))
using (var ws = new MemoryStream())
using (var writer = new StreamWriter(ws))
{
//执行渲染
this.engine.Evaluate(context, reader, writer);
writer.Flush();
ws.Flush();
var resultDoc = new ExcelMLTemplate();
resultDoc.PutBuffer(ws.ToArray());
return resultDoc;
}
}
示例11: Serialize
public void Serialize(object item, BinaryTokenStreamWriter writer, Type expectedType)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
if (item == null)
{
writer.WriteNull();
return;
}
var formatter = new BinaryFormatter();
byte[] bytes;
using (var memoryStream = new MemoryStream())
{
formatter.Serialize(memoryStream, item);
memoryStream.Flush();
bytes = memoryStream.ToArray();
}
writer.Write(bytes.Length);
writer.Write(bytes);
}
示例12: Encrypt
/// <summary>
/// Encrypts a string
/// </summary>
/// <param name="key">The key that will be used to encrypt the data</param>
/// <param name="data">The string you wish to encrypt</param>
/// <returns>Encrypted data</returns>
public static string Encrypt(string key, string data)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(data))
{
byte[] m_Key = new byte[8];
byte[] m_IV = new byte[8];
InitKey(key, ref m_Key, ref m_IV);
DESCryptoServiceProvider csprov = new DESCryptoServiceProvider();
MemoryStream memstream = new MemoryStream();
CryptoStream crstream = new CryptoStream(memstream, csprov.CreateEncryptor(m_Key, m_IV), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(crstream);
sw.Write(data);
sw.Flush();
crstream.FlushFinalBlock();
memstream.Flush();
result = Convert.ToBase64String(memstream.GetBuffer(), 0, Convert.ToInt32(memstream.Length));
sw.Close();
crstream.Close();
memstream.Close();
}
return result;
}
示例13: DocumentIsUpToDate
public void DocumentIsUpToDate()
{
var fullpath = Path.GetFullPath(@"..\..\..\RulesList.xml");
var docText = File.ReadAllText(fullpath);
var children =
_rules.OrderBy(_ => _.ID)
.Select(
rule =>
new XElement(
"rule",
new XElement("id", rule.ID),
new XElement("title", rule.Title),
new XElement("suggestion", rule.Suggestion)))
.Cast<object>()
.ToArray();
var rules = new XElement("rules", children);
var doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), rules);
var currentText = string.Empty;
using (var ms = new MemoryStream())
{
doc.Save(ms);
ms.Flush();
ms.Position = 0;
using (var reader = new StreamReader(ms))
{
currentText = reader.ReadToEnd();
}
}
Assert.AreEqual(docText, currentText);
}
示例14: TestWrite
private bool TestWrite(MemoryStream ms, int BufferLength, int BytesToWrite, int Offset, long ExpectedLength)
{
bool result = true;
long startLength = ms.Position;
long nextbyte = startLength % 256;
byte[] byteBuffer = new byte[BufferLength];
for (int i = Offset; i < (Offset + BytesToWrite); i++)
{
byteBuffer[i] = (byte)nextbyte;
// Reset if wraps past 255
if (++nextbyte > 255)
nextbyte = 0;
}
ms.Write(byteBuffer, Offset, BytesToWrite);
ms.Flush();
if (ExpectedLength < ms.Length)
{
result = false;
Log.Exception("Expeceted final length of " + ExpectedLength + " bytes, but got " + ms.Length + " bytes");
}
return result;
}
示例15: btnCreateReport_Click
/// <summary>
/// Loads the report and binds the data for the selected report
/// </summary>
protected void btnCreateReport_Click(object sender, EventArgs e)
{
getReportName();
//Gets the location of the RDLC file to load
m_rdlcPath = HttpContext.Current.Request.MapPath(".") + "\\" + "Reports" + "\\" + m_reportName + ".rdlc";
//creates the ReportDataSource and populates it based on the selected values
ReportDataSource rds = getDatasource();
//Resets the ReportViewer, adds the new datasource, and changes the name of the report
ReportViewer1.Reset();
ReportViewer1.LocalReport.DataSources.Add(rds);
ReportViewer1.LocalReport.DisplayName = "reportDatasource";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(m_rdlcPath);
using (MemoryStream xmlStream = new MemoryStream())
{
xmldoc.Save(xmlStream);
xmlStream.Flush();
xmlStream.Position = 0;
ReportViewer1.LocalReport.LoadReportDefinition(xmlStream);
}
//binds the data to the reportviewer and refreshes the display
ReportViewer1.DataBind();
ReportViewer1.LocalReport.Refresh();
ReportViewer1.Visible = true;
}