当前位置: 首页>>代码示例>>C#>>正文


C# MemoryStream.SetLength方法代码示例

本文整理汇总了C#中System.IO.MemoryStream.SetLength方法的典型用法代码示例。如果您正苦于以下问题:C# MemoryStream.SetLength方法的具体用法?C# MemoryStream.SetLength怎么用?C# MemoryStream.SetLength使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.MemoryStream的用法示例。


在下文中一共展示了MemoryStream.SetLength方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ReceiveAsync

        public async Task<Message> ReceiveAsync(CancellationToken cancellationToken = default(CancellationToken)) {
            const int blockSize = 0x10000;
            var buffer = new MemoryStream(blockSize);

            while (true) {
                cancellationToken.ThrowIfCancellationRequested();

                int index = (int)buffer.Length;
                buffer.SetLength(index + blockSize);

                await _receiveLock.WaitAsync(cancellationToken);
                WebSocketReceiveResult wsrr;
                try {
                    wsrr = await _socket.ReceiveAsync(new ArraySegment<byte>(buffer.GetBuffer(), index, blockSize), cancellationToken);
                } catch (Exception ex) when(IsTransportException(ex)) {
                    throw new MessageTransportException(ex);
                } finally {
                    _receiveLock.Release();
                }

                buffer.SetLength(index + wsrr.Count);

                if (wsrr.CloseStatus != null) {
                    return null;
                }

                if (wsrr.EndOfMessage) {
                    return Message.Parse(buffer.ToArray());
                }
            }
        }
开发者ID:Microsoft,项目名称:RTVS,代码行数:31,代码来源:WebSocketMessageTransport.cs

示例2: UrlDecode

        // decodes a quoted-printable encoded string
        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 ();
        }
开发者ID:pulb,项目名称:basenji,代码行数:60,代码来源:DecoderUtility.cs

示例3: 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.GetEncoding (28591);
	
			StringBuilder output = new StringBuilder ();
			long len = s.Length;
			NumberStyles hexa = NumberStyles.HexNumber;
			MemoryStream bytes = new MemoryStream ();
	
			for (int i = 0; i < len; i++) {
				if (s [i] == '%' && i + 2 < len) {
					if (s [i + 1] == 'u' && i + 5 < len) {
						if (bytes.Length > 0) {
							output.Append (GetChars (bytes, e));
							bytes.SetLength (0);
						}
						output.Append ((char) Int32.Parse (s.Substring (i + 2, 4), hexa));
						i += 5;
					} else {
						bytes.WriteByte ((byte) Int32.Parse (s.Substring (i + 1, 2), hexa));
						i += 2;
					}
					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 ();
		}
开发者ID:runefs,项目名称:Marvin,代码行数:51,代码来源:HttpUtility.cs

示例4: RunTestIssue103

        private static void RunTestIssue103(int loop, TypeA typeA, TypeB typeB, TypeModel model, string caption)
        {
            // for JIT and preallocation
            MemoryStream ms = new MemoryStream();
            ms.SetLength(0);
            model.Serialize(ms, typeA);
            ms.Position = 0;
            model.Deserialize(ms, null, typeof(TypeA));

            Stopwatch typeASer = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
                ms.SetLength(0);
                model.Serialize(ms, typeA);
            }
            typeASer.Stop();
            Stopwatch typeADeser = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
                ms.Position = 0;
                model.Deserialize(ms, null, typeof(TypeA));
            }
            typeADeser.Stop();

            ms.SetLength(0);
            model.Serialize(ms, typeB);
            ms.Position = 0;
            TypeB clone = (TypeB)model.Deserialize(ms, null, typeof(TypeB));
            Assert.AreEqual(typeB.containedType.Count, clone.containedType.Count);

            Stopwatch typeBSer = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
                ms.SetLength(0);
                model.Serialize(ms, typeB);
            }
            typeBSer.Stop();
            Stopwatch typeBDeser = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
                ms.Position = 0;
                model.Deserialize(ms, null, typeof(TypeB));
            }
            typeBDeser.Stop();

            Console.WriteLine(caption + " A/ser\t" + (typeASer.ElapsedMilliseconds * 1000 / loop) + " μs/item");
            Console.WriteLine(caption + " A/deser\t" + (typeADeser.ElapsedMilliseconds * 1000 / loop) + " μs/item");
            Console.WriteLine(caption + " B/ser\t" + (typeBSer.ElapsedMilliseconds * 1000 / loop) + " μs/item");
            Console.WriteLine(caption + " B/deser\t" + (typeBDeser.ElapsedMilliseconds * 1000 / loop) + " μs/item");
        }
开发者ID:XewTurquish,项目名称:vsminecraft,代码行数:50,代码来源:Issue103.cs

示例5: TestMbr

        public void TestMbr()
        {
            MemoryStream ms = new MemoryStream();
            ms.SetLength(1024 * 1024);

            byte[] newMbr = new byte[512];
            for (int i = 0; i < 512; i++)
            {
                newMbr[i] = (byte)i;
            }

            Raw.Disk rawDisk = new DiscUtils.Raw.Disk(ms, Ownership.Dispose);
            rawDisk.SetMasterBootRecord(newMbr);

            byte[] readMbr = rawDisk.GetMasterBootRecord();
            Assert.AreEqual(512, readMbr.Length);

            for (int i = 0; i < 512; i++)
            {
                if (readMbr[i] != (byte)i)
                {
                    Assert.Fail("Mismatch on byte {0}, expected {1} was {2}", i, (byte)i, readMbr[i]);
                }
            }
        }
开发者ID:alexcmd,项目名称:DiscUtils,代码行数:25,代码来源:VirtualDiskTest.cs

示例6: Convert

        public static Stream Convert(Stream originalStream)
        {
            var copyData = new byte[originalStream.Length];
            originalStream.Read(copyData, 0, copyData.Length);
            var copyStream = new MemoryStream(copyData);

            var encoding = DetectEncoding(copyData);

            if (encoding == null)
                return copyStream;

            var utf8Suffix = new byte[] { 0xC2 };

            if (encoding == Encoding.UTF8 && IsDataSuffixed(copyData, utf8Suffix))
                copyStream.SetLength(copyStream.Length - utf8Suffix.Length);

            using (var copyReader = new StreamReader(copyStream, encoding))
            {
                var originalText = copyReader.ReadToEnd();
                var asciiData = Encoding.ASCII.GetBytes(originalText);
                var asciiText = Encoding.ASCII.GetString(asciiData);

                if (originalText == asciiText)
                    return new MemoryStream(asciiData);

                return CreateSuffixedStream(originalText, Encoding.UTF8, utf8Suffix);
            }
        }
开发者ID:bleissem,项目名称:SymbolSource.Community,代码行数:28,代码来源:SourceConverter.cs

示例7: EncodeObject

 static ByteString EncodeObject (object value, Type type, MemoryStream buffer, CodedOutputStream stream)
 {
     buffer.SetLength (0);
     if (value != null && !type.IsInstanceOfType (value))
         throw new ArgumentException ("Value of type " + value.GetType () + " cannot be encoded to type " + type);
     if (value == null && !type.IsSubclassOf (typeof(RemoteObject)) && !IsACollectionType (type))
         throw new ArgumentException ("null cannot be encoded to type " + type);
     if (value == null)
         stream.WriteUInt64 (0);
     else if (value is Enum)
         stream.WriteInt32 ((int)value);
     else {
         switch (Type.GetTypeCode (type)) {
         case TypeCode.Int32:
             stream.WriteInt32 ((int)value);
             break;
         case TypeCode.Int64:
             stream.WriteInt64 ((long)value);
             break;
         case TypeCode.UInt32:
             stream.WriteUInt32 ((uint)value);
             break;
         case TypeCode.UInt64:
             stream.WriteUInt64 ((ulong)value);
             break;
         case TypeCode.Single:
             stream.WriteFloat ((float)value);
             break;
         case TypeCode.Double:
             stream.WriteDouble ((double)value);
             break;
         case TypeCode.Boolean:
             stream.WriteBool ((bool)value);
             break;
         case TypeCode.String:
             stream.WriteString ((string)value);
             break;
         default:
             if (type.Equals (typeof(byte[])))
                 stream.WriteBytes (ByteString.CopyFrom ((byte[])value));
             else if (IsAClassType (type))
                 stream.WriteUInt64 (((RemoteObject)value).id);
             else if (IsAMessageType (type))
                 ((IMessage)value).WriteTo (buffer);
             else if (IsAListType (type))
                 WriteList (value, type, buffer);
             else if (IsADictionaryType (type))
                 WriteDictionary (value, type, buffer);
             else if (IsASetType (type))
                 WriteSet (value, type, buffer);
             else if (IsATupleType (type))
                 WriteTuple (value, type, buffer);
             else
                 throw new ArgumentException (type + " is not a serializable type");
             break;
         }
     }
     stream.Flush ();
     return ByteString.CopyFrom (buffer.GetBuffer (), 0, (int)buffer.Length);
 }
开发者ID:paperclip,项目名称:krpc,代码行数:60,代码来源:Encoder.cs

示例8: sendEmail

        private bool sendEmail()
        {
            List<string> MyEmailList = new List<string>();
            MyEmailList.Add(tbEmailAddress.Text);
            EmailAttachment MyEmailAttachment = new EmailAttachment();

            using (FileStream fileStream = File.OpenRead(Server.MapPath("/AttachmentExample.txt")))
            {
                MemoryStream memStream = new MemoryStream();
                memStream.SetLength(fileStream.Length);
                fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
                MyEmailAttachment.AttachmentMemoryStream = memStream;
                MyEmailAttachment.AttachmentFileInfo = new FileInfo(Server.MapPath("/AttachmentExample.txt"));
            }

            List<EmailAttachment> MyEmailAttachmentList = new List<EmailAttachment>();
            MyEmailAttachmentList.Add(MyEmailAttachment);

            Email MyEmail = new Email(MyEmailList, MyEmailAttachmentList, "Test subject", "Test body", null, ConfigurationManager.AppSettings["EmailFrom"]);
            if (!MyEmail.SendEmail())
            {
                ErrorMessage = MyEmail.ErrorMessage;
                return false;
            }
            return true;
        }
开发者ID:garethduncan87,项目名称:csharpEmailClass,代码行数:26,代码来源:Default.aspx.cs

示例9: Encrypt

        /// <summary>
        /// Do Encry for plainString.
        /// </summary>
        /// <param name="plainString">Plain string.</param>
        /// <returns>Encrypted string as base64.</returns>
        public string Encrypt(string plainString)
        {
            // Create the file streams to handle the input and output files.
            MemoryStream fout = new MemoryStream(200);
            fout.SetLength(0);

            // Create variables to help with read and write.
            byte[] bin = System.Text.Encoding.Unicode.GetBytes(plainString);
            DES des = new DESCryptoServiceProvider();

            // des.KeySize=64;
            CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
            encStream.Write(bin, 0, bin.Length);
            encStream.FlushFinalBlock();

            fout.Flush();
            fout.Seek(0, SeekOrigin.Begin);

            // read all string
            byte[] bout = new byte[fout.Length];
            fout.Read(bout, 0, bout.Length);
            encStream.Close();
            fout.Close();

            return Convert.ToBase64String(bout, 0, bout.Length);
        }
开发者ID:RuhuiCheng,项目名称:Talent,代码行数:31,代码来源:Sym_DES.cs

示例10: ReadPersianNumber

        public static Stream ReadPersianNumber(int number, string tempDirectory)
        {
            if (number > 99 || number < 1)
                return
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(
                        "Fardis.Audio.Wave.Invalid.wav");

            var reminder = number % 10;

            if (number <= 20 || reminder == 0)
                return PrepareSingle(number, tempDirectory);

            int quotient = number / 10;
            var firstPart = quotient * 10;

            var fileName = Concatenate(new[]
                {
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    string.Format("Fardis.Audio.Wave.{0}.wav", firstPart)),
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    "Fardis.Audio.Wave.And.wav"),
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    string.Format("Fardis.Audio.Wave.{0}.wav", reminder)),
                }, tempDirectory);

            var memStream = new MemoryStream();
            using (var fileStream = File.OpenRead(fileName))
            {
                memStream.SetLength(fileStream.Length);
                fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
            }

            return memStream;
        }
开发者ID:arabsoheyl,项目名称:fardis,代码行数:34,代码来源:PersianNumberRead.cs

示例11: LoadConfiguration

		public static MulticlientConfiguration LoadConfiguration(string password)
		{
			try
			{
				EncryptHelper.DecryptFile(AppDataFolderHelper.GetMulticlientFile(), AppDataFolderHelper.GetTempMulticlientFile(), password);
			}
			catch (System.Security.Cryptography.CryptographicException)
			{
				return null;
			}
			try
			{
				var memoryStream = new MemoryStream();
				using (var fileStream = new FileStream(AppDataFolderHelper.GetTempMulticlientFile(), FileMode.Open))
				{
					memoryStream.SetLength(fileStream.Length);
					fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);
				}
				File.Delete(AppDataFolderHelper.GetTempMulticlientFile());
				var dataContractSerializer = new DataContractSerializer(typeof(MulticlientConfiguration));
				var configuration = (MulticlientConfiguration)dataContractSerializer.ReadObject(memoryStream);
				return configuration;
			}
			catch (Exception e)
			{
				Logger.Error(e, "MulticlientConfigurationHelper.LoadConfiguration");
			}
			return null;
		}
开发者ID:saeednazari,项目名称:Rubezh,代码行数:29,代码来源:MulticlientConfigurationHelper.cs

示例12: deepCopyFromFileToObject

        public static object deepCopyFromFileToObject(string fileName)
        {
            FileStream inStream = File.OpenRead(fileName);
            MemoryStream memoryStream = new MemoryStream();

            memoryStream.SetLength(inStream.Length);
            inStream.Read(memoryStream.GetBuffer(), 0, (int)inStream.Length);

            memoryStream.Flush();
            memoryStream.Position = 0;
            inStream.Close();

            object deserializedObject = null;

            try
            {
                BinaryFormatter serializer = new BinaryFormatter();
                deserializedObject = serializer.Deserialize(memoryStream);
            }
            finally
            {
                if (memoryStream != null)
                    memoryStream.Close();
            }
            return deserializedObject;
        }
开发者ID:sorvis,项目名称:Fast-Script,代码行数:26,代码来源:ObjectSerializing.cs

示例13: ReadLine

        /// <summary>
        /// Reads byte[] line from stream. NOTE: Returns null if end of stream reached.
        /// </summary>
        /// <returns>Return null if end of stream reached.</returns>
        public byte[] ReadLine()
        {
            MemoryStream strmLineBuf = new MemoryStream();
            byte      prevByte = 0;

            int currByteInt = m_StrmSource.ReadByte();
            while(currByteInt > -1){
                strmLineBuf.WriteByte((byte)currByteInt);

                // Line found
                if((prevByte == (byte)'\r' && (byte)currByteInt == (byte)'\n')){
                    strmLineBuf.SetLength(strmLineBuf.Length - 2); // Remove <CRLF>

                    return strmLineBuf.ToArray();
                }

                // Store byte
                prevByte = (byte)currByteInt;

                // Read next byte
                currByteInt = m_StrmSource.ReadByte();
            }

            // Line isn't terminated with <CRLF> and has some bytes left, return them.
            if(strmLineBuf.Length > 0){
                return strmLineBuf.ToArray();
            }

            return null;
        }
开发者ID:jeske,项目名称:StepsDB-alpha,代码行数:34,代码来源:StreamLineReader.cs

示例14: DoDecrypt

 /// <summary>
 /// 解密
 /// </summary>
 /// <param name="encryptedText"></param>
 /// <param name="key"></param>
 /// <param name="encoding"></param>
 /// <returns></returns>
 public string DoDecrypt(string encryptedText, string key, Encoding encoding)
 {
     try
     {
         desKey = Encoding.Unicode.GetBytes(key);
         encryptedText = encryptedText.Replace("{z1}", "=");
         encryptedText = encryptedText.Replace("{z2}", "&");
         MemoryStream stream = new MemoryStream(200);
         stream.SetLength(0L);
         byte[] buffer = Convert.FromBase64String(encryptedText);
         Rijndael rijndael = new RijndaelManaged();
         rijndael.KeySize = 0x100;
         CryptoStream stream2 = new CryptoStream(stream, rijndael.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
         stream2.Write(buffer, 0, buffer.Length);
         stream2.FlushFinalBlock();
         stream.Flush();
         stream.Seek(0L, SeekOrigin.Begin);
         byte[] buffer2 = new byte[stream.Length];
         stream.Read(buffer2, 0, buffer2.Length);
         stream2.Close();
         stream.Close();
         return Encoding.Unicode.GetString(buffer2);
     }
     catch (Exception ex)
     {
         return "";
     }
 }
开发者ID:ZhouHengYi,项目名称:HFramework,代码行数:35,代码来源:EncryHelper.cs

示例15: StringTestAsync

        public async Task StringTestAsync()
        {
            MemoryStream memStream = new MemoryStream();
            BigEndianStream bigEndianStream = new BigEndianStream(memStream);

            string testString = "Hello, World!";

            await bigEndianStream.WriteAsync(testString);

            memStream.Seek(0, SeekOrigin.Begin);

            var result = await bigEndianStream.ReadString16Async();

            Assert.AreEqual(testString, result);

            Assert.AreEqual(memStream.Position, memStream.Length);


            memStream.SetLength(0);

            bigEndianStream.Write8(testString);

            memStream.Seek(0, SeekOrigin.Begin);

            result = await bigEndianStream.ReadString8Async();

            Assert.AreEqual(testString, result);

            Assert.AreEqual(memStream.Position, memStream.Length);
        }
开发者ID:splitice,项目名称:Pdelvo.Minecraft,代码行数:30,代码来源:BigEndianStreamTests.cs


注:本文中的System.IO.MemoryStream.SetLength方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。