本文整理汇总了C#中MemoryStream.SetLength方法的典型用法代码示例。如果您正苦于以下问题:C# MemoryStream.SetLength方法的具体用法?C# MemoryStream.SetLength怎么用?C# MemoryStream.SetLength使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MemoryStream
的用法示例。
在下文中一共展示了MemoryStream.SetLength方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Start
void Start()
{
Screen.sleepTimeout = SleepTimeout.NeverSleep;
m_listenSocket = SetupListening(AndroidRemotePort);
m_tcpClient = null;
m_copyBuffer = new byte[128 * 1024];
m_readBuffer = new byte[StreamBufferSize];
m_readStream = new MemoryStream(m_readBuffer);
m_readStream.Position = 0;
m_readStream.SetLength(0);
m_writeStream = new MemoryStream(StreamBufferSize);
m_webCamStreamer = new WebCamStreamer();
}
示例2: MemStreamClearWriteByteTest
public static bool MemStreamClearWriteByteTest()
{
Console.WriteLine("Ensuring that we clear data > Length in a MemoryStream when we write past the end via WriteByte");
const int len = 10;
const int spanPastEnd = 5;
MemoryStream ms = new MemoryStream(3*len);
byte[] bytes = new byte[len];
for(int i=0; i<bytes.Length; i++)
bytes[i] = (byte) i;
ms.Write(bytes, 0, bytes.Length);
for(int i=0; i<2*len; i++)
ms.WriteByte((byte)255);
ms.SetLength(len);
ms.Seek(spanPastEnd, SeekOrigin.End);
for(int i=0; i<bytes.Length; i++)
ms.WriteByte(bytes[i]);
ms.Position = bytes.Length;
byte[] newData = new byte[bytes.Length + spanPastEnd];
int n = ms.Read(newData, 0, newData.Length);
if (n != newData.Length)
{
iCountErrors++ ;
throw new Exception("Hmmm, maybe a bug in the stream. Asked to read "+newData.Length+", but got back "+n+" bytes.");
}
for(int i=0; i<spanPastEnd; i++)
{
if (newData[i] != 0)
{
iCountErrors++ ;
throw new Exception(String.Format("New data in the middle of the stream should have been all 0's, but at position {0} I got a wrong byte: {1} [0x{1:x}]!", i+bytes.Length, newData[i]));
}
}
for(int i=0; i<bytes.Length; i++)
{
if (newData[i+spanPastEnd] != bytes[i])
{
iCountErrors++ ;
throw new Exception(String.Format("New data at the end of the stream should have been equal to our byte[], but the {0}'th new byte was a wrong byte: {1} [0x{1:x}]!", i, newData[i+spanPastEnd]));
}
}
ms.Flush();
ms.Close();
return true;
}
示例3: Serialize
/// <summary>Serialize the instance into the stream</summary>
public static void Serialize(Stream stream, FileDescriptorProto instance)
{
using (var msField = new MemoryStream(0))
{
if (instance.Name != null)
{
// Key for field: 1, LengthDelimited
stream.WriteByte(10);
global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Name));
}
if (instance.Package != null)
{
// Key for field: 2, LengthDelimited
stream.WriteByte(18);
global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Package));
}
if (instance.Dependency != null)
{
foreach (var i3 in instance.Dependency)
{
// Key for field: 3, LengthDelimited
stream.WriteByte(26);
global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(i3));
}
}
if (instance.PublicDependency != null)
{
foreach (var i10 in instance.PublicDependency)
{
// Key for field: 10, Varint
stream.WriteByte(80);
global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)i10);
}
}
if (instance.WeakDependency != null)
{
foreach (var i11 in instance.WeakDependency)
{
// Key for field: 11, Varint
stream.WriteByte(88);
global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)i11);
}
}
if (instance.MessageType != null)
{
foreach (var i4 in instance.MessageType)
{
// Key for field: 4, LengthDelimited
stream.WriteByte(34);
msField.SetLength(0);
Google.protobuf.DescriptorProto.Serialize(msField, i4);
// Length delimited byte array
uint length4 = (uint)msField.Length;
global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length4);
stream.Write(msField.GetBuffer(), 0, (int)length4);
}
}
if (instance.EnumType != null)
{
foreach (var i5 in instance.EnumType)
{
// Key for field: 5, LengthDelimited
stream.WriteByte(42);
msField.SetLength(0);
Google.protobuf.EnumDescriptorProto.Serialize(msField, i5);
// Length delimited byte array
uint length5 = (uint)msField.Length;
global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length5);
stream.Write(msField.GetBuffer(), 0, (int)length5);
}
}
if (instance.Service != null)
{
foreach (var i6 in instance.Service)
{
// Key for field: 6, LengthDelimited
stream.WriteByte(50);
msField.SetLength(0);
Google.protobuf.ServiceDescriptorProto.Serialize(msField, i6);
// Length delimited byte array
uint length6 = (uint)msField.Length;
global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length6);
stream.Write(msField.GetBuffer(), 0, (int)length6);
}
}
if (instance.Extension != null)
{
foreach (var i7 in instance.Extension)
{
// Key for field: 7, LengthDelimited
stream.WriteByte(58);
msField.SetLength(0);
Google.protobuf.FieldDescriptorProto.Serialize(msField, i7);
// Length delimited byte array
uint length7 = (uint)msField.Length;
global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length7);
//.........这里部分代码省略.........
示例4: WriteNoRepeater
private void WriteNoRepeater(MemoryStream NoRepeatBytes)
{
// write the length of non repeted data
_Compressed.WriteByte((byte)((int)NoRepeatBytes.Length - 1));
// write the non repeated data put literally
_Compressed.Write(NoRepeatBytes.ToArray(), 0, (int)NoRepeatBytes.Length);
// re-set non repeat byte storage stream
NoRepeatBytes.SetLength(0);
}
示例5: runTest
//.........这里部分代码省略.........
ms.Capacity = ( ms.Capacity - 1 );
++iCountErrors;
Console.WriteLine( "Err_001i, should have thrown NotSupportedException when setting capacity to something less then" );
}
catch ( NotSupportedException )
{
}
catch(Exception ex)
{
Console.WriteLine("Err_563243wefsg! Wrong exception thrown. " + ex);
}
}
}
catch (Exception ex)
{
++iCountErrors;
Console.WriteLine( "Err_001j, Unexpected exception was thrown ex: strLoc=" + strLoc + ", " + ex.ToString() );
}
if ( verbose ) Console.WriteLine( "Construct MemoryStream with null byte[]" );
try
{
++iCountTestcases;
MemoryStream ms = new MemoryStream( null );
++iCountErrors;
Console.WriteLine( "Err_002a, Expected exception ArgumentNullException was not thrown." );
}
catch ( ArgumentNullException )
{}
catch (Exception ex)
{
++iCountErrors;
Console.WriteLine( "Err_002b, Unexpected exception was thrown ex: " + ex.ToString() );
}
if ( verbose ) Console.WriteLine( "try to see if stream can by truncated using SetLength" );
try
{
byte [][] byteArrs = new byte[100][];
for ( int i = 0; i < byteArrs.Length; i++ )
{
byteArrs[i] = new byte[i];
}
for ( int i = 0; i < byteArrs.Length; i++ )
{
if ( verbose ) Console.WriteLine( "Trying test on byte[" + i + "]" );
++iCountTestcases;
MemoryStream ms = new MemoryStream(byteArrs[i]);
for ( int j = byteArrs[i].Length; j >= 0; j-- )
{
ms.SetLength( j );
}
}
}
catch (Exception ex)
{
++iCountErrors;
Console.WriteLine( "Err_003a, Unexpected exception was thrown ex: " + ex.ToString() );
}
if ( verbose ) Console.WriteLine( "try to see if stream can be expanded with SetLength, it should not be" );
try
{
byte [][] byteArrs = new byte[100][];
for ( int i = 0; i < byteArrs.Length; i++ )
{
byteArrs[i] = new byte[i];
}
for ( int i = 0; i < byteArrs.Length; i++ )
示例6: GetLanguageList
public static List<ComboBoxItem> GetLanguageList()
{
if (LanguageItems == null)
{
LanguageItems = new List<ComboBoxItem>();
foreach (Language language in Languages.Values)
{
ComboBoxItem c = new ComboBoxItem();
c.Style = Application.Current.FindResource("ComboBoxItem") as Style;
StackPanel panel = new StackPanel();
panel.Orientation = Orientation.Horizontal;
c.Content = panel;
string fileName = "langs/" + language.Resource["LangCode"] + ".png";
if (System.IO.File.Exists(fileName))
{
MemoryStream ms = new MemoryStream();
FileStream stream = new FileStream(fileName, FileMode.Open);
ms.SetLength(stream.Length);
stream.Read(ms.GetBuffer(), 0, (int)stream.Length);
ms.Flush();
stream.Close();
Image i = new Image();
BitmapImage img = new BitmapImage();
img.BeginInit();
img.StreamSource = ms;
img.EndInit();
i.Source = img;
i.Margin = new Thickness(0, 0, 10, 0);
panel.Children.Add(i);
}
TextBlock text = new TextBlock();
text.Name = "Label";
text.VerticalAlignment = VerticalAlignment.Center;
text.Text = language.Resource["LangName"] as String;
panel.Children.Add(text);
LanguageItems.Add(c);
}
}
return LanguageItems;
}
示例7: UrlDecode
public static string UrlDecode(string s, Encoding e)
{
if (null == s)
return null;
if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1)
return s;
if (e == null)
e = Encoding.UTF8;
StringBuilder output = new StringBuilder ();
long len = s.Length;
MemoryStream bytes = new MemoryStream ();
int xchar;
for (int i = 0; i < len; i++) {
if (s [i] == '%' && i + 2 < len && s [i + 1] != '%') {
if (s [i + 1] == 'u' && i + 5 < len) {
if (bytes.Length > 0) {
output.Append (GetChars (bytes, e));
bytes.SetLength (0);
}
xchar = GetChar (s, i + 2, 4);
if (xchar != -1) {
output.Append ((char) xchar);
i += 5;
} else {
output.Append ('%');
}
} else if ((xchar = GetChar (s, i + 1, 2)) != -1) {
bytes.WriteByte ((byte) xchar);
i += 2;
} else {
output.Append ('%');
}
continue;
}
if (bytes.Length > 0) {
output.Append (GetChars (bytes, e));
bytes.SetLength (0);
}
if (s [i] == '+') {
output.Append (' ');
} else {
output.Append (s [i]);
}
}
if (bytes.Length > 0) {
output.Append (GetChars (bytes, e));
}
bytes = null;
return output.ToString ();
}
示例8: MemoryStream_LengthTest
public static void MemoryStream_LengthTest()
{
using (MemoryStream ms2 = new MemoryStream())
{
// [] Get the Length when position is at length
ms2.SetLength(50);
ms2.Position = 50;
StreamWriter sw2 = new StreamWriter(ms2);
for (char c = 'a'; c < 'f'; c++)
sw2.Write(c);
sw2.Flush();
Assert.Equal(55, ms2.Length);
// Somewhere in the middle (set the length to be shorter.)
ms2.SetLength(30);
Assert.Equal(30, ms2.Length);
Assert.Equal(30, ms2.Position);
// Increase the length
ms2.SetLength(100);
Assert.Equal(100, ms2.Length);
Assert.Equal(30, ms2.Position);
}
}
示例9: runTest
public bool runTest()
{
Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
int iCountErrors = 0;
int iCountTestcases = 0;
String strLoc = "Loc_000oo";
String strValue = String.Empty;
try
{
MemoryStream ms2;
Byte[] bytArrRet;
Byte[] bytArr = new Byte[] {
Byte.MinValue
,Byte.MaxValue
,1
,2
,3
,4
,5
,6
,128
,250
};
strLoc = "Loc_00001";
ms2 = new MemoryStream();
bytArrRet = ms2.ToArray();
iCountTestcases++;
if(bytArrRet.Length != 0)
{
iCountErrors++;
printerr( "Error_00002! Unexpected length of array=="+bytArrRet.Length);
}
ms2.Close();
strLoc = "Loc_00003";
ms2 = new MemoryStream();
ms2.Write(bytArr, 0, bytArr.Length);
ms2.Flush();
bytArrRet = ms2.ToArray();
iCountTestcases++;
if(bytArrRet.Length != bytArr.Length)
{
iCountErrors++;
printerr( "Error_00004! Unexpected length, expected=="+bytArr.Length+", got=="+bytArrRet.Length);
}
for(int i = 0 ; i < bytArr.Length ; i++)
{
iCountTestcases++;
if(bytArrRet[i] != bytArr[i])
{
iCountErrors++;
printerr( "Error_00005_"+i+"! Expected=="+bytArr[i]+", got=="+bytArrRet[i]);
}
}
ms2.Close();
strLoc = "Loc_00006";
ms2 = new MemoryStream();
ms2.Write(bytArr, 0, bytArr.Length);
ms2.SetLength(5);
ms2.Flush();
bytArrRet = ms2.ToArray();
iCountTestcases++;
if(bytArrRet.Length != 5)
{
iCountErrors++;
printerr( "Error_00007! Expected==5, got=="+bytArrRet.Length);
}
for(int i = 0 ; i < 5 ; i++)
{
iCountTestcases++;
if(bytArrRet[i] != bytArr[i])
{
iCountErrors++;
printerr( "Error_00008_"+i+"! Expected=="+bytArr[i]+", got=="+bytArrRet[i]);
}
}
ms2.Close();
}
catch (Exception exc_general )
{
++iCountErrors;
Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString());
}
if ( iCountErrors == 0 )
{
Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString());
return true;
}
else
{
Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums );
return false;
}
}
示例10: MemoryStream_LengthTest_Negative
public static void MemoryStream_LengthTest_Negative()
{
using (MemoryStream ms2 = new MemoryStream())
{
Assert.Throws<ArgumentOutOfRangeException>(() => ms2.SetLength(Int64.MaxValue));
Assert.Throws<ArgumentOutOfRangeException>(() => ms2.SetLength(-2));
}
}
示例11: TrimBeginning
private static void TrimBeginning(MemoryStream stream)
{
// skopiowanie pozostalych bajtow na poczatek strumienia
int otherBytesLength = (int) (stream.Length - stream.Position);
byte[] otherBytes = new byte[otherBytesLength];
stream.Read(otherBytes, 0, otherBytesLength);
stream.SetLength(otherBytesLength);
stream.Position = 0;
stream.Write(otherBytes, 0, otherBytesLength);
}
示例12: decomposeImage
static Rect decomposeImage(Image pImage, PixelFormat pPixelFormat,
out Texture2D[] lOut, out int lXCount)
{
lXCount = Mathf.CeilToInt((float)pImage.Width / (float)maxSize);
int lYCount = Mathf.CeilToInt((float)pImage.Height / (float)maxSize);
lOut = new Texture2D[lXCount * lYCount];
//Bitmap lBitmap = new Bitmap(pImage);
print("lXCount:" + lXCount);
print("lYCount:" + lYCount);
Rect lRightBottomRect = new Rect((lXCount - 1) * maxSize, (lYCount - 1) * maxSize,
pImage.Width % maxSize, pImage.Height % maxSize);
MemoryStream lMemoryStream = new MemoryStream(maxSize * maxSize*4 +1024*1024);
for (int y = 0; y < lYCount; ++y)
{
for (int x=0;x<lXCount;++x)
{
int lWidth = (x==lXCount-1) ?(pImage.Width%maxSize):maxSize;
int lHeight = (y == lYCount - 1) ? (pImage.Height % maxSize) : maxSize;
//using (Bitmap lBitmap = new Bitmap(lWidth, lHeight,PixelFormat.Format32bppArgb))
//{
print("count:" + (x + lXCount * y) + " x:" + x + " y:" + y);
Bitmap lBitmap = new Bitmap(lWidth, lHeight, pPixelFormat);
//print("start:"+System.DateTime.Now);
var lGraphics = System.Drawing.Graphics.FromImage(lBitmap);
var lDestRect = new Rectangle(0, 0, lWidth, lHeight);
var lSrcRect = new Rectangle(x * maxSize, y * maxSize, lWidth, lHeight);
print("lRect:" + lSrcRect + " " + System.DateTime.Now);
lGraphics.DrawImage(pImage, lDestRect, lSrcRect, GraphicsUnit.Pixel);
lMemoryStream.SetLength(0);
lMemoryStream.Position = 0;
print("After DrawImageUnscaled:" + System.DateTime.Now);
lBitmap.Save(lMemoryStream, ImageFormat.Png);
print("After Bitmap.Save:" + System.DateTime.Now);
//print("after Graphics.DrawImageUnscaled:" + System.DateTime.Now);
Texture2D lTexture = new Texture2D(lWidth, lHeight, TextureFormat.ARGB32, false);
//BitmapToTexture2D(lBitmap, lRect,lTexture);
lTexture.LoadImage(lMemoryStream.GetBuffer());
print("After Texture.LoadImage:" + System.DateTime.Now);
//if (pCompress)
// lTexture.Compress(true);
//print("After Texture.Compress:" + System.DateTime.Now);
fillPowerOfTwo(lTexture);
print("After fillPowerOfTwo:" + System.DateTime.Now);
lOut[x + lXCount * y] = lTexture;
//lGraphics.Dispose();
//print("end:" + System.DateTime.Now);
//}
lBitmap.Dispose();
lGraphics.Dispose();
}
}
lMemoryStream.Dispose();
return lRightBottomRect;
}
示例13: runTest
public bool runTest()
{
Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
int iCountErrors = 0;
int iCountTestcases = 0;
String strLoc = "Loc_000oo";
String strValue = String.Empty;
try
{
MemoryStream ms2;
StreamWriter sw2;
String filName = s_strTFAbbrev+"Test.tmp";
try
{
new FileInfo(filName).Delete();
}
catch (Exception) {}
strLoc = "Loc_98yc8";
ms2 = new MemoryStream();
iCountTestcases++;
if(ms2.Length != 0)
{
iCountErrors++;
printerr( "Error_2898t! Incorrect length=="+ms2.Length);
}
iCountTestcases++;
try
{
ms2.SetLength(-2);
iCountErrors++;
printerr( "Error_23890! Expected exception not thrown, position=="+ms2.Position);
}
catch (ArgumentOutOfRangeException aexc)
{
printinfo( "Info_328xj! Caught expected exception, aexc=="+aexc.Message);
}
catch (Exception exc)
{
iCountErrors++;
printerr( "Error_289ux! Incorrect exception thrown, exc=="+exc.ToString());
}
ms2.Close();
strLoc = "Loc_27yxc";
ms2 = new MemoryStream();
ms2.SetLength(50);
ms2.Position = 50;
sw2 = new StreamWriter(ms2);
for(char c = 'a' ; c < 'f' ; c++)
sw2.Write(c);
sw2.Flush();
iCountTestcases++;
if(ms2.Length != 55)
{
iCountErrors++;
printerr( "Error_389xd! Incorrect stream length=="+ms2.Length);
}
ms2.SetLength(30);
iCountTestcases++;
if(ms2.Length != 30)
{
iCountErrors++;
printerr( "Error_28xye! Incorrect length=="+ms2.Length);
}
iCountTestcases++;
if(ms2.Position != 30)
{
iCountErrors++;
printerr( "Error_3989a! Incorrect position=="+ms2.Position);
}
ms2.SetLength(100);
iCountTestcases++;
if(ms2.Length != 100)
{
iCountErrors++;
printerr( "Error_2090x! Incorrect length=="+ms2.Length);
}
iCountTestcases++;
if(ms2.Length != 100)
{
iCountErrors++;
printerr( "Error_297ty! Incorrect length=="+ms2.Length);
}
ms2.Close();
strLoc = "Loc_99189";
ms2 = new MemoryStream();
iCountTestcases++;
try
{
ms2.SetLength(Int64.MaxValue);
iCountErrors++;
printerr( "Error_209xu! Expected exception not thrown, ms2.Length=="+ms2.Length);
}
catch (ArgumentException aexc)
{
printinfo( "Info_0999d! Caught expected exception, aexc=="+aexc.Message);
}
catch (IOException iexc)
{
printinfo( "Info_49283! Caught expceted exception, iexc=="+iexc.Message);
}
//.........这里部分代码省略.........
示例14: shiftMemoryStream
void shiftMemoryStream(MemoryStream ms, int shiftsize )
{
byte[] buf = ms.GetBuffer();
// Debug.Log( "shiftsize:" + shiftsize + " msl:" + ms.Length );
Buffer.BlockCopy( buf, shiftsize, buf, 0, (int)ms.Length - shiftsize );
ms.SetLength( ms.Length - shiftsize );
}
示例15: Flush
/// <summary>
/// Override flush by writing out the cached stream data
/// </summary>
public override void Flush()
{
if (IsCaptured && _cacheStream.Length > 0)
{
// Check for transform implementations
_cacheStream = OnTransformCompleteStream(_cacheStream);
_cacheStream = OnTransformCompleteStringInternal(_cacheStream);
OnCaptureStream(_cacheStream);
OnCaptureStringInternal(_cacheStream);
// write the stream back out if output was delayed
if (IsOutputDelayed)
_stream.Write(_cacheStream.ToArray(), 0, (int)_cacheStream.Length);
// Clear the cache once we've written it out
_cacheStream.SetLength(0);
}
// default flush behavior
_stream.Flush();
}