System.IO.MemoryStream.Read(byte[], int, int)

Here are the examples of the csharp api System.IO.MemoryStream.Read(byte[], int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

553 Examples 7

19 View Source File : TestDataFetcher.cs
License : MIT License
Project Creator : Azure99

private byte[] CreateZip(InnerFile[] files, string dataVersion)
        {
            byte[] zipData;
            using (MemoryStream ms = new MemoryStream())
            {
                using (ZipArchive zip = new ZipArchive(ms, ZipArchiveMode.Create))
                {
                    foreach (InnerFile file in files)
                    {
                        ZipArchiveEntry entry = null;
                        if (file.Name.EndsWith(".in"))
                            entry = zip.CreateEntry("input/" + file.Name);
                        else if (file.Name.EndsWith(".out"))
                            entry = zip.CreateEntry("output/" + file.Name);
                        else if (CheckIsSpecialJudgeFile(file.Name))
                        {
                            entry = zip.CreateEntry("spj/" + SpjManager.SpjSourceFilename +
                                                    Path.GetExtension(file.Name));
                        }

                        if (entry == null)
                            continue;

                        using (Stream stream = entry.Open())
                        {
                            stream.Write(file.Data);
                        }
                    }

                    ZipArchiveEntry verEntry = zip.CreateEntry("version.txt");
                    using (StreamWriter writer = new StreamWriter(verEntry.Open()))
                    {
                        writer.Write(dataVersion);
                    }

                    zip.UpdateBaseStream();

                    zipData = new byte[ms.Length];
                    int nowPos = (int) ms.Position;
                    ms.Position = 0;
                    ms.Read(zipData, 0, (int) ms.Length);
                    ms.Position = nowPos;
                }
            }

            return zipData;
        }

19 View Source File : HttpHelper.cs
License : MIT License
Project Creator : bp2008

private static byte[] GetResponseData(WebResponse webResponseObj, SortedList<string, string> headers = null)
		{
			byte[] data;
			using (HttpWebResponse webResponse = (HttpWebResponse)webResponseObj)
			{
				using (MemoryStream ms = new MemoryStream())
				{
					using (Stream responseStream = webResponse.GetResponseStream())
					{
						// Dump the response stream into the MemoryStream ms
						int bytesRead = 1;
						while (bytesRead > 0)
						{
							byte[] buffer = new byte[8000];
							bytesRead = responseStream.Read(buffer, 0, buffer.Length);
							if (bytesRead > 0)
								ms.Write(buffer, 0, bytesRead);
						}
						data = new byte[ms.Length];

						// Dump the data into the byte array
						ms.Seek(0, SeekOrigin.Begin);
						ms.Read(data, 0, data.Length);
						responseStream.Close();

						if (headers != null)
							foreach (string key in webResponse.Headers.AllKeys)
								headers[key.ToLower()] = webResponse.Headers[key];
					}
				}
				webResponse.Close();
			}
			return data;
		}

19 View Source File : SimpleMeshSerializer.cs
License : MIT License
Project Creator : anderm

public static byte[] Serialize(IEnumerable<Mesh> meshes)
        {
            byte[] data;

            using (MemoryStream stream = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    foreach (Mesh mesh in meshes)
                    {
                        WriteMesh(writer, mesh);
                    }

                    stream.Position = 0;
                    data = new byte[stream.Length];
                    stream.Read(data, 0, data.Length);
                }
            }

            return data;
        }

19 View Source File : HttpHelpers.cs
License : Apache License 2.0
Project Creator : aws-samples

public static void InvokeHttpRequest(Uri endpointUri,
                                             string httpMethod,
                                             IDictionary<string, string> headers,
                                             string requestBody)
        {
            try
            {
                var request = ConstructWebRequest(endpointUri, httpMethod, headers);

                if (!string.IsNullOrEmpty(requestBody))
                {
                    var buffer = new byte[8192]; // arbitrary buffer size                        
                    var requestStream = request.GetRequestStream();
                    using (var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(requestBody)))
                    {
                        var bytesRead = 0;
                        while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            requestStream.Write(buffer, 0, bytesRead);
                        }
                    }
                }

                GetResponse(request);
            }
            catch (WebException ex)
            {
                using (var response = ex.Response as HttpWebResponse)
                {
                    if (response != null)
                    {
                        var errorMsg = ReadResponseBody(response);
                        Logger.LogError($"\n-- HTTP call failed with exception '{errorMsg}', status code '{response.StatusCode}'");
                    }
                }
            }
        }

19 View Source File : RSAHelper.cs
License : Apache License 2.0
Project Creator : anjoy8

public string Encrypt(string text)
		{
			if (_publicKeyRsaProvider == null)
			{
				throw new Exception("_publicKeyRsaProvider is null");
			} 
			var bufferSize = (_publicKeyRsaProvider.KeySize / 8 - 11); 
			byte[] buffer = new byte[bufferSize];//待加密块

			using (MemoryStream msInput = new MemoryStream(_encoding.GetBytes(text)))
			{
				using (MemoryStream msOutput = new MemoryStream())
				{
					int readLen; while ((readLen = msInput.Read(buffer, 0, bufferSize)) > 0)
					{
						byte[] dataToEnc = new byte[readLen];
						Array.Copy(buffer, 0, dataToEnc, 0, readLen); byte[] encData = _publicKeyRsaProvider.Encrypt(dataToEnc, RSAEncryptionPadding.Pkcs1);
						msOutput.Write(encData, 0, encData.Length);
					}
					byte[] result = msOutput.ToArray(); 
					return Convert.ToBase64String(result);
				}
			}
		}

19 View Source File : RSAEncryptor.cs
License : Apache License 2.0
Project Creator : alipay

protected override string DoDecrypt(string cipherTextBase64, string charset, string privateKey)
        {
            using (RSACryptoServiceProvider rsaService = BuildRSAServiceProvider(Convert.FromBase64String(privateKey)))
            {
                byte[] data = Convert.FromBase64String(cipherTextBase64);

                //解密块最大长度
                int maxBlockSize = rsaService.KeySize / 8;

                //如果密文长度小于等于单个解密块最大长度,直接单次调用解密接口完成解密
                if (data.Length <= maxBlockSize)
                {
                    byte[] cipherbytes = rsaService.Decrypt(data, false);
                    return Encoding.GetEncoding(charset).GetString(cipherbytes);
                }

                //如果密文长度大于单个解密块最大长度,在内存中循环调用解密接口完成解密
                using (MemoryStream plainStream = new MemoryStream())
                {
                    using (MemoryStream cipherStream = new MemoryStream(data))
                    {
                        Byte[] buffer = new Byte[maxBlockSize];
                        int readSize = cipherStream.Read(buffer, 0, maxBlockSize);
                        while (readSize > 0)
                        {
                            Byte[] cipherBlock = new Byte[readSize];
                            Array.Copy(buffer, 0, cipherBlock, 0, readSize);
                            Byte[] plainBlock = rsaService.Decrypt(cipherBlock, false);
                            plainStream.Write(plainBlock, 0, plainBlock.Length);
                            readSize = cipherStream.Read(buffer, 0, maxBlockSize);
                        }
                    }
                    return Encoding.GetEncoding(charset).GetString(plainStream.ToArray());
                }

            }
        }

19 View Source File : Models.cs
License : MIT License
Project Creator : BlazorPlus

static public CommandMessage Unpack(MemoryStream ms)
		{
			byte[] header = new byte[12];
			ms.Read(header, 0, 12);
			string h8 = System.Text.Encoding.ASCII.GetString(header, 0, 8);
			if (STR_H8 != h8)
				throw new Exception("Invalid header : " + h8);
			uint size = BitConverter.ToUInt32(header, 8);
			if (size > MAX_PACKAGE_SIZE)
				throw new Exception("reach MAX_PACKAGE_SIZE:" + size);
			return UnpackRest(ms);
		}

19 View Source File : AudioPlayer.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

private void Filler(IntPtr data, int size)
        {
            int blockCount = _wave.BlockCount;
            byte[] b = new byte[size];

            if (_file != null && (_looped || _lastBlock < blockCount))
            {
                MemoryStream ms = new MemoryStream();

                if (_leftOverBuffer != null)
                {
                    ms.Write(_leftOverBuffer, 0, _leftOverBuffer.Length);
                }
                
                while (ms.Position < size)
                {
                    _lastBlock++;

                    if (_lastBlock >= blockCount)
                    {
                        if (!_looped)
                        {
                            while(ms.Position < size)
                            {
                                ms.WriteByte(0);
                            }
                            break;
                        }
                        else
                        {
                            _lastBlock = 0;
                            _state = new DviAdpcmDecoder.AdpcmState();
                        }
                    }

                    _file.SoundBank.ExportWaveBlockAsPCM(_wave.Index, _lastBlock, ref _state, _file.Stream, ms);
                }

                int extraData = (int)(ms.Position - size);
                
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(b, 0, size);

                if (extraData > 0)
                {
                    _leftOverBuffer = new byte[extraData];
                    ms.Read(_leftOverBuffer, 0, extraData);
                }
                else
                {
                    _leftOverBuffer = null;
                }
            }
            else
            {
                for (int i = 0; i < b.Length; i++)
                {
                    b[i] = 0;
                }
            }
            System.Runtime.InteropServices.Marshal.Copy(b, 0, data, size);
        }

19 View Source File : SimpleMeshSerializer.cs
License : GNU General Public License v3.0
Project Creator : brownhci

public static byte[] Serialize(IEnumerable<MeshFilter> meshes, Transform secondarySpace = null)
        {
            byte[] data = null;

            using (MemoryStream stream = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    foreach (MeshFilter meshFilter in meshes)
                    {
                        WriteMesh(writer, meshFilter.sharedMesh, meshFilter.transform, secondarySpace);
                    }

                    stream.Position = 0;
                    data = new byte[stream.Length];
                    stream.Read(data, 0, data.Length);
                }
            }

            return data;
        }

19 View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

public static unsafe BitmapSource DdsToPng(MemoryStream buffer) {
            Pfim.IImage image;
            var tag = stackalloc byte[4];
            buffer.Read(new Span<byte>(tag, 4));
            bool dispose;
            if (dispose = * (int*)tag != 0x20534444) // "DDS "
                buffer = new MemoryStream(BrotliSharpLib.Brotli.DecompressBuffer(buffer.ToArray(), 4, (int)buffer.Length - 4));
            buffer.Seek(0, SeekOrigin.Begin);
            image = Pfim.Pfim.FromStream(buffer);
            image.Decompress();
            if (dispose)
                buffer.Close();
            return BitmapSource.Create(image.Width, image.Height, 96.0, 96.0,
            PixelFormat(image), null, image.Data, image.Stride);
        }

19 View Source File : EncryptionHandler.cs
License : Apache License 2.0
Project Creator : Appdynamics

private byte[] EncryptData(byte[] key, byte[] data, bool useDataSize)
        {
#if (Core)
            var aes = Aes.Create();
#else
            RijndaelManaged aes = new RijndaelManaged();
#endif
            aes.KeySize = key.Length * 8;
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.Zeros;

            //Encrypt the data
            var crypt = aes.CreateEncryptor(key, null);
            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, crypt, CryptoStreamMode.Write);
            cs.Write(data, 0, data.Length);

            cs.FlushFinalBlock();

            byte[] ret;
            if (useDataSize)
            {
                ret = new byte[data.Length];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(ret, 0, data.Length);  //Truncate any padded Zeros
                return ret;
            }
            else
            {
                return ms.ToArray();
            }
        }

19 View Source File : MemoryStreamWrapper.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public short ReadInt16()
        {
            byte[] buffer = new byte[Constant.SHORT_BYTES];
            lock (stream)
            {
                stream.Read(buffer, 0, Constant.SHORT_BYTES);
            }          
            return BitConverter.ToInt16(buffer, 0);
        }

19 View Source File : SimpleAES.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

public string Decrypt(byte[] EncryptedValue)
        {
            #region Write the encrypted value to the decryption stream
            MemoryStream encryptedStream = new MemoryStream();
            CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
            decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
            decryptStream.FlushFinalBlock();
            #endregion

            #region Read the decrypted value from the stream.
            encryptedStream.Position = 0;
            Byte[] decryptedBytes = new Byte[encryptedStream.Length];
            encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
            encryptedStream.Close();
            #endregion
            return UTFEncoder.GetString(decryptedBytes);
        }

19 View Source File : AyFuncBitmapWithWpf.cs
License : MIT License
Project Creator : ay2015

public byte[] ImageToBytes(Image Image, System.Drawing.Imaging.ImageFormat imageFormat)
        {

            if (Image == null) { return null; }
            byte[] data = null;
            using (MemoryStream ms = new MemoryStream())
            {
                using (Bitmap Bitmap = new Bitmap(Image))
                {
                    Bitmap.Save(ms, imageFormat);
                    ms.Position = 0;
                    data = new byte[ms.Length];
                    ms.Read(data, 0, Convert.ToInt32(ms.Length));
                    ms.Flush();
                }
            }
            return data;
        }

19 View Source File : MemoryIterator.cs
License : Apache License 2.0
Project Creator : aequabit

public bool Read<TResult>(long offset, SeekOrigin origin, out TResult result) where TResult: struct
        {
            result = default(TResult);
            try
            {
                this._base.Seek(offset, origin);
                byte[] buffer = new byte[Marshal.SizeOf(typeof(TResult))];
                this._base.Read(buffer, 0, buffer.Length);
                if (!this._ubuffer.Translate<TResult>(buffer, out result))
                {
                    throw this._ubuffer.GetLastError();
                }
                return true;
            }
            catch (Exception exception)
            {
                return base.SetLastError(exception);
            }
        }

19 View Source File : InjectionHelper.cs
License : MIT License
Project Creator : b9q

public static byte[] decrypt_cheat(byte[] cheat_file, string preplacedword)
    {
        try
        {
            byte[] preplacedword_bytes = Encoding.UTF8.GetBytes(preplacedword);
            byte[] salt = new byte[32];

            //var ms_1 = new MemoryStream(File.ReadAllBytes(cheat_file), false);
            //ms_1.Read(salt, 0, salt.Length);

            MemoryStream ms_crypt = new MemoryStream(cheat_file);
            //FileStream fs_crypt = new FileStream(cheat_file, FileMode.Open);
            ms_crypt.Read(salt, 0, salt.Length);

            RijndaelManaged AES = new RijndaelManaged {KeySize = 256, BlockSize = 128};

            var key = new Rfc2898DeriveBytes(preplacedword_bytes, salt, 50000);
            AES.Key = key.GetBytes(AES.KeySize / 8);
            AES.IV = key.GetBytes(AES.BlockSize / 8);
            AES.Padding = PaddingMode.PKCS7;
            AES.Mode = CipherMode.CFB;

            CryptoStream cs = new CryptoStream(ms_crypt, AES.CreateDecryptor(), CryptoStreamMode.Read);
            MemoryStream ms = new MemoryStream();

            int read;
            byte[] buffer = new byte[1048576];

            while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
                ms.Write(buffer, 0, read);

            //ms_1.Close();
            ms.Close();
            ms_crypt.Close();
            return ms.ToArray();
        }
        catch (Exception)
        {
            MessageBox.Show("Unable to decrypt cheat.", "decryption failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        return null;
    }

19 View Source File : HttpErrorResponseExceptionHandler.cs
License : MIT License
Project Creator : aliyunmq

public override bool HandleException(IExecutionContext executionContext, HttpErrorResponseException exception)
        {
            var requestContext = executionContext.RequestContext;
            var httpErrorResponse = exception.Response;

            // If 404 was suppressed and successfully unmarshalled,
            // don't rethrow the original exception.
            if (HandleSuppressed404(executionContext, httpErrorResponse))
                return false;

            AliyunServiceException errorResponseException = null;
            // Unmarshall the service error response and throw the corresponding service exception
            string responseContent = null;
            try
            {
                using (httpErrorResponse.ResponseBody)
                {
                    var unmarshaller = requestContext.Unmarshaller;

                    var errorContext = unmarshaller.CreateContext(httpErrorResponse, httpErrorResponse.ResponseBody.OpenResponse());

                    using (MemoryStream stream = new MemoryStream())
                    {
                        AliyunSDKUtils.CopyTo(errorContext.ResponseStream, stream);
                        stream.Seek(0, SeekOrigin.Begin);
                        byte[] bytes = new byte[stream.Length];
                        stream.Read(bytes, 0, (int)stream.Length);
                        responseContent = Encoding.UTF8.GetString(bytes);
                        stream.Seek(0, SeekOrigin.Begin);

                        errorContext.ResponseStream = stream;

                        errorResponseException = unmarshaller.UnmarshallException(errorContext,
                            exception, httpErrorResponse.StatusCode);
                        Debug.replacedert(errorResponseException != null);
                    }
                }
            }
            catch (ResponseUnmarshallException unmarshallException)
            {
                if (responseContent != null)
                {
                    throw new AliyunServiceException(responseContent, unmarshallException,
                                                     ErrorCode.InternalError,
                        null, null, httpErrorResponse.StatusCode);
                }
                throw;
            }

            throw errorResponseException;
        }

19 View Source File : RtspTransportClientTests.cs
License : MIT License
Project Creator : BogdanovKirill

protected override Task<int> ReadAsync(byte[] buffer, int offset, int count)
            {
                EnsureResponseCreated();

                int read = count > 0 ? _responseStream.Read(buffer, offset, 1) : 0;

                return Task.FromResult(read);
            }

19 View Source File : SevenZipHelper.cs
License : MIT License
Project Creator : 91Act

public static MemoryStream StreamDecompress(MemoryStream newInStream, long outSize)
        {
            Decoder decoder = new Decoder();

            newInStream.Seek(0, 0);
            MemoryStream newOutStream = new MemoryStream();

            byte[] properties2 = new byte[5];
            if (newInStream.Read(properties2, 0, 5) != 5)
                throw (new Exception("input .lzma is too short"));
            decoder.SetDecoderProperties(properties2);

            long compressedSize = newInStream.Length - newInStream.Position;
            decoder.Code(newInStream, newOutStream, compressedSize, outSize, null);

            newOutStream.Position = 0;
            return newOutStream;
        }

19 View Source File : GZipCompressor.cs
License : GNU General Public License v3.0
Project Creator : BRH-Media

public static byte[] CompressBytes(byte[] buffer)
        {
            var memoryStream = new MemoryStream();
            using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
            {
                gZipStream.Write(buffer, 0, buffer.Length);
            }

            memoryStream.Position = 0;

            var compressedData = new byte[memoryStream.Length];
            memoryStream.Read(compressedData, 0, compressedData.Length);

            var gZipBuffer = new byte[compressedData.Length + 4];
            Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
            Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);

            return gZipBuffer;
        }

19 View Source File : ResponseStream.cs
License : MIT License
Project Creator : andruzzzhka

private void flushBody (bool closing)
    {
      using (_body) {
        var len = _body.Length;
        if (len > Int32.MaxValue) {
          _body.Position = 0;
          var buffLen = 1024;
          var buff = new byte[buffLen];
          var nread = 0;
          while ((nread = _body.Read (buff, 0, buffLen)) > 0)
            _writeBody (buff, 0, nread);
        }
        else if (len > 0) {
          _writeBody (_body.GetBuffer (), 0, (int) len);
        }
      }

      _body = !closing ? new MemoryStream () : null;
    }

19 View Source File : RSAHelper.cs
License : Apache License 2.0
Project Creator : anjoy8

public string Decrypt(string cipherText)
		{
			if (_privateKeyRsaProvider == null)
			{
				throw new Exception("_privateKeyRsaProvider is null");
			} 
			var bufferSize = (_privateKeyRsaProvider.KeySize / 8); 
			byte[] buffer = new byte[bufferSize];//待解密块  
			using (MemoryStream msInput = new MemoryStream(Convert.FromBase64String(cipherText)))
			{
				using (MemoryStream msOutput = new MemoryStream())
				{
					int readLen; while ((readLen = msInput.Read(buffer, 0, bufferSize)) > 0)
					{
						byte[] dataToEnc = new byte[readLen];
						Array.Copy(buffer, 0, dataToEnc, 0, readLen); byte[] encData = _privateKeyRsaProvider.Decrypt(dataToEnc, RSAEncryptionPadding.Pkcs1);
						msOutput.Write(encData, 0, encData.Length);
					}
					byte[] result = msOutput.ToArray(); 
					return _encoding.GetString(result);
				}
			}
		}

19 View Source File : HttpHelper.cs
License : GNU General Public License v3.0
Project Creator : aduskin

static WebList Http_DownSteam(HttpWebResponse response, Encoding encoding)
      {
         WebList _web = new WebList
         {
            Encoding = encoding,
            StatusCode = (int)response.StatusCode,
            Type = response.ContentType,
            AbsoluteUri = response.ResponseUri.AbsoluteUri
         };
         string header = "";
         foreach (string str in response.Headers.AllKeys)
         {
            if (str == "Set-Cookie")
            {
               _web.SetCookie = response.Headers[str];
            }
            else if (str == "Location")
            {
               _web.Location = response.Headers[str];
            }
            header = header + str + ":" + response.Headers[str] + "\r\n";
         }
         string cookie = "";
         foreach (Cookie str in response.Cookies)
         {
            cookie = cookie + str.Name + "=" + str.Value + ";";
         }

         _web.Header = header;
         _web.Cookie = cookie;

         #region 下载流
         using (Stream stream = response.GetResponseStream())
         {
            using (MemoryStream file = new MemoryStream())
            {
               int _value = 0;
               byte[] _cache = new byte[1024];
               int osize = stream.Read(_cache, 0, 1024);

               while (osize > 0)
               {
                  _value += osize;

                  file.Write(_cache, 0, osize);
                  osize = stream.Read(_cache, 0, 1024);
               }

               file.Seek(0, SeekOrigin.Begin);
               byte[] _byte = new byte[_value];
               file.Read(_byte, 0, _value);

               file.Seek(0, SeekOrigin.Begin);
               string fileclreplaced = GetFileClreplaced(file);
               if (fileclreplaced == "31139")
               {
                  //_web.OriginalSize = _byte.Length;
                  _web.Byte = Decompress(_byte);
               }
               else
               {
                  _web.Byte = _byte;
               }
            }
         }
         #endregion
         return _web;
      }

19 View Source File : MemoryStreamWrapper.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public int ReadInt32()
        {
            byte[] buffer = new byte[Constant.INTEGER_BYTES];
            lock (stream)
            {
                stream.Read(buffer, 0, Constant.INTEGER_BYTES);
            }
            return BitConverter.ToInt32(buffer, 0);
        }

19 View Source File : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static Bitmap _MakeTransparentGif(Bitmap bitmap, Color color)
		{
			byte R = color.R;
			byte G = color.G;
			byte B = color.B;

			MemoryStream fin = new MemoryStream();
			bitmap.Save(fin, System.Drawing.Imaging.ImageFormat.Gif);

			MemoryStream fout = new MemoryStream((int)fin.Length);
			int count = 0;
			byte[] buf = new byte[256];
			byte transparentIdx = 0;
			fin.Seek(0, SeekOrigin.Begin);
			//header
			count = fin.Read(buf, 0, 13);
			if ((buf[0] != 71) || (buf[1] != 73) || (buf[2] != 70)) return null; //GIF

			fout.Write(buf, 0, 13);

			int i = 0;
			if ((buf[10] & 0x80) > 0)
			{
				i = 1 << ((buf[10] & 7) + 1) == 256 ? 256 : 0;
			}

			for (; i != 0; i--)
			{
				fin.Read(buf, 0, 3);
				if ((buf[0] == R) && (buf[1] == G) && (buf[2] == B))
				{
					//transparentIdx = (byte)(256 - i);
				}
				fout.Write(buf, 0, 3);
			}

			bool gcePresent = false;
			while (true)
			{
				fin.Read(buf, 0, 1);
				fout.Write(buf, 0, 1);
				if (buf[0] != 0x21) 
					break;
				fin.Read(buf, 0, 1);
				fout.Write(buf, 0, 1);
				gcePresent = (buf[0] == 0xf9);
				while (true)
				{
					fin.Read(buf, 0, 1);
					fout.Write(buf, 0, 1);
					if (buf[0] == 0) 
						break;
					count = buf[0];
					if (fin.Read(buf, 0, count) != count) return null;
					if (gcePresent)
					{
						if (count == 4)
						{
							buf[0] |= 0x01;
							buf[3] = transparentIdx;
						}
					}
					fout.Write(buf, 0, count);
				}
			}
			while (count > 0)
			{
				count = fin.Read(buf, 0, 1);
				fout.Write(buf, 0, 1);
			}
			fin.Close();
			fout.Flush();

			return new Bitmap(fout);
		}

19 View Source File : BuilderPlug.cs
License : GNU General Public License v3.0
Project Creator : anotak

public bool[][] LoadTabel()
		{
			// Load the reject data
			using(MemoryStream stream = General.Map.GetLumpData("REJECT"))
			{
				byte[] data = new byte[stream.Length];
				stream.Read(data, 0, (int)stream.Length);

				// If the data does not cover all sectors, resize the array
				// to match (extra bytes are initialied with zeros)
				int numsectors = General.Map.Map.Sectors.Count;
				int requiredsize = (int)Math.Ceiling((double)(numsectors * numsectors) / 8.0);
				if(data.Length > requiredsize) return null;
				if(data.Length < requiredsize) Array.Resize(ref data, requiredsize);

				// Expand the table
				int databit = 0;
				bool[][] table = new bool[numsectors][];
				for(int ss = 0; ss < table.Length; ss++)
				{
					table[ss] = new bool[numsectors];
					bool[] sectors = table[ss];
					for(int ts = 0; ts < sectors.Length; ts++)
					{
						int byteindex = databit >> 3;
						int bitmask = 1 << (databit & 0x07);
						sectors[ts] = (data[byteindex] & bitmask) != 0;
						databit++;
					}
				}

				return table;
			}
		}

19 View Source File : MemoryStreamWrapper.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

private byte[] ReadStreamAt(int offset, int numberOfBytes)
        {
            lock (stream)
            {
                byte[] buffer = new byte[numberOfBytes];
                var oldPos = stream.Position;
                stream.Position = offset;
                stream.Read(buffer, 0, numberOfBytes);
                stream.Position = oldPos;
                return buffer;
            }
        }

19 View Source File : SimpleAES.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

public byte[] Encrypt(string TextValue)
        {
            //Translates our text value into a byte array.
            Byte[] bytes = UTFEncoder.GetBytes(TextValue);

            //Used to stream the data in and out of the CryptoStream.
            MemoryStream memoryStream = new MemoryStream();

            /*
             * We will have to write the unencrypted bytes to the stream,
             * then read the encrypted result back from the stream.
             */
            #region Write the decrypted value to the encryption stream
            CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write);
            cs.Write(bytes, 0, bytes.Length);
            cs.FlushFinalBlock();
            #endregion

            #region Read encrypted value back out of the stream
            memoryStream.Position = 0;
            byte[] encrypted = new byte[memoryStream.Length];
            memoryStream.Read(encrypted, 0, encrypted.Length);
            #endregion

            //Clean up.
            cs.Close();
            memoryStream.Close();

            return encrypted;
        }

19 View Source File : CompoundDocumentFile.cs
License : Apache License 2.0
Project Creator : Appdynamics

public static bool IsCompoundDoreplacedent(MemoryStream ms)
        {
            var pos = ms.Position;
            ms.Position = 0;
            var b=new byte[8];
            ms.Read(b, 0, 8);
            ms.Position = pos;
            return IsCompoundDoreplacedent(b);
        }

19 View Source File : MemoryIterator.cs
License : Apache License 2.0
Project Creator : aequabit

public bool Read(long offset, SeekOrigin origin, byte[] buffer)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer", "Parameter cannot be null");
            }
            try
            {
                this._base.Seek(offset, origin);
                this._base.Read(buffer, 0, buffer.Length);
            }
            catch (Exception exception)
            {
                this.SetLastError(exception);
                buffer = null;
            }
            return (buffer != null);
        }

19 View Source File : Image.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d

[OgreVersion(1, 7, 2)]
#if NET_40
		public static Image FromStream( Stream stream, string type = "" )
#else
        public static Image FromStream(Stream stream, string type)
#endif
        {
            // find the codec for this file type
            Codec codec = null;

            if (!string.IsNullOrEmpty(type))
            {
                // use named codec
                codec = CodecManager.Instance.GetCodec(type);
            }
            else
            {
                // derive from magic number
                // read the first 32 bytes or file size, if less
                var magicLen = Axiom.Math.Utility.Min((int)stream.Length, 32);
                var magicBuf = new byte[magicLen];
                stream.Read(magicBuf, 0, magicLen);
                // return to start
                stream.Position = 0;
                codec = CodecManager.Instance.GetCodec(magicBuf, magicLen);
            }

            if (codec == null)
            {
                throw new AxiomException(
                    "Unable to load image: Image format is unknown. Unable to identify codec. Check it or specify format explicitly.");
            }

            var res = codec.Decode(stream);
            var decoded = (MemoryStream)res.First;
            var data = (ImageCodec.ImageData)res.Second;

            if (data == null)
            {
                return null;
            }

            // copy the image data
            var image = new Image
            {
                height = data.height,
                width = data.width,
                depth = data.depth,
                size = data.size,
                numMipMaps = data.numMipMaps,
                flags = data.flags,
                // Get the format and compute the pixel size
                format = data.format,
            };

            // stuff the image data into an array
            var buffer = new byte[decoded.Length];
            decoded.Position = 0;
            decoded.Read(buffer, 0, buffer.Length);
            decoded.Close();

            image.SetBuffer(buffer);

            return image;
        }

19 View Source File : ImageUtils.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public static ImageSource ImageFromClipboardDib(MemoryStream ms)
        {
            if (ms != null)
            {
                byte[] dibBuffer = new byte[ms.Length];
                ms.Read(dibBuffer, 0, dibBuffer.Length);

                BITMAPINFOHEADER infoHeader =
                    BinaryStructConverter.FromByteArray<BITMAPINFOHEADER>(dibBuffer);

                int fileHeaderSize = Marshal.SizeOf(typeof(BITMAPFILEHEADER));
                int infoHeaderSize = infoHeader.biSize;
                int fileSize = fileHeaderSize + infoHeader.biSize + infoHeader.biSizeImage;

                BITMAPFILEHEADER fileHeader = new BITMAPFILEHEADER
                {
                    bfType = BITMAPFILEHEADER.BM,
                    bfSize = fileSize,
                    bfReserved1 = 0,
                    bfReserved2 = 0,
                    bfOffBits = fileHeaderSize + infoHeaderSize + (infoHeader.biClrUsed * 4),
                };

                byte[] fileHeaderBytes =
                    BinaryStructConverter.ToByteArray<BITMAPFILEHEADER>(fileHeader);

                MemoryStream msBitmap = new MemoryStream();
                msBitmap.Write(fileHeaderBytes, 0, fileHeaderSize);
                msBitmap.Write(dibBuffer, 0, dibBuffer.Length);
                msBitmap.Seek(0, SeekOrigin.Begin);

                return BitmapFrame.Create(msBitmap);
            }

            return null;
        }

19 View Source File : SVNFileSystemStream.cs
License : MIT License
Project Creator : azist

protected override int DoRead(byte[] buffer, int offset, int count)
      {
        return BufferStream.Read(buffer, offset, count);
      }

19 View Source File : SevenZipHelper.cs
License : MIT License
Project Creator : 91Act

public static MemoryStream StreamDecompress(MemoryStream newInStream)
        {
            Decoder decoder = new Decoder();

            newInStream.Seek(0, 0);
            MemoryStream newOutStream = new MemoryStream();

            byte[] properties2 = new byte[5];
            if (newInStream.Read(properties2, 0, 5) != 5)
                throw (new Exception("input .lzma is too short"));
            long outSize = 0;
            for (int i = 0; i < 8; i++)
            {
                int v = newInStream.ReadByte();
                if (v < 0)
                    throw (new Exception("Can't Read 1"));
                outSize |= ((long)(byte)v) << (8 * i);
            }
            decoder.SetDecoderProperties(properties2);

            long compressedSize = newInStream.Length - newInStream.Position;
            decoder.Code(newInStream, newOutStream, compressedSize, outSize, null);

            newOutStream.Position = 0;
            return newOutStream;
        }

19 View Source File : TestDataFetcher.cs
License : MIT License
Project Creator : Azure99

private byte[] ChangeVersionFileName(byte[] data)
        {
            byte[] newData;
            using (MemoryStream stream = new MemoryStream())
            {
                stream.Write(data);
                stream.Position = 0;
                using (ZipArchive zipArchive = new ZipArchive(stream, ZipArchiveMode.Update))
                {
                    string version = "";
                    ZipArchiveEntry oldEntry = zipArchive.GetEntry("last_modified");
                    if (oldEntry != null)
                    {
                        using (StreamReader reader = new StreamReader(oldEntry.Open()))
                        {
                            version = reader.ReadToEnd();
                        }
                    }

                    ZipArchiveEntry newEntry = zipArchive.CreateEntry("version.txt");
                    using (StreamWriter writer = new StreamWriter(newEntry.Open()))
                    {
                        writer.Write(version);
                    }

                    zipArchive.UpdateBaseStream();

                    int nowPos = (int) stream.Position;
                    newData = new byte[stream.Length];
                    stream.Position = 0;
                    stream.Read(newData, 0, (int) stream.Length);
                    stream.Position = nowPos;
                }
            }

            return newData;
        }

19 View Source File : RSAEncryptor.cs
License : Apache License 2.0
Project Creator : alipay

protected override string DoEncrypt(string plainText, string charset, string publicKey)
        {
            using (RSACryptoServiceProvider rsaService = new RSACryptoServiceProvider())
            {
                rsaService.PersistKeyInCsp = false;
                rsaService.ImportParameters(ConvertFromPemPublicKey(publicKey));
                byte[] data = Encoding.GetEncoding(charset).GetBytes(plainText);

                //加密块最大长度
                int maxBlockSize = rsaService.KeySize / 8 - 11;

                //如果明文长度小于等于单个加密块最大长度,直接单次调用加密接口完成加密
                if (data.Length <= maxBlockSize)
                {
                    byte[] cipherbytes = rsaService.Encrypt(data, false);
                    return Convert.ToBase64String(cipherbytes);
                }

                //如果明文长度大于单个加密块最大长度,在内存中循环调用加密接口完成加密
                using (MemoryStream cipherStream = new MemoryStream())
                {
                    using (MemoryStream plainStream = new MemoryStream(data))
                    {
                        Byte[] buffer = new Byte[maxBlockSize];
                        int readSize = plainStream.Read(buffer, 0, maxBlockSize);
                        while (readSize > 0)
                        {
                            Byte[] plainBlock = new Byte[readSize];
                            Array.Copy(buffer, 0, plainBlock, 0, readSize);
                            Byte[] cipherBlock = rsaService.Encrypt(plainBlock, false);
                            cipherStream.Write(cipherBlock, 0, cipherBlock.Length);
                            readSize = plainStream.Read(buffer, 0, maxBlockSize);
                        }
                    }
                    return Convert.ToBase64String(cipherStream.ToArray(), Base64FormattingOptions.None);
                }
            }
        }

19 View Source File : StreamExtensionsTests.cs
License : MIT License
Project Creator : BEagle1984

[Fact]
        public void Read_StreamPortion_SliceReturned()
        {
            var stream = new MemoryStream(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 });

            var result = stream.Read(2);
            result.Should().BeEquivalentTo(new byte[] { 0x01, 0x02 });

            result = stream.Read(3);
            result.Should().BeEquivalentTo(new byte[] { 0x03, 0x04, 0x05 });
        }

19 View Source File : MemoryIterator.cs
License : Apache License 2.0
Project Creator : aequabit

public bool ReadString(long offset, SeekOrigin origin, out string lpBuffer, int len = -1, Encoding stringEncoding = null)
        {
            lpBuffer = null;
            byte[] buffer = new byte[(len > 0) ? len : 0x40];
            if (stringEncoding == null)
            {
                stringEncoding = Encoding.ASCII;
            }
            try
            {
                this._base.Seek(offset, origin);
                StringBuilder builder = new StringBuilder((len > 0) ? len : 260);
                int length = -1;
                int num2 = 0;
                int startIndex = 0;
                while ((length == -1) && ((num2 = this._base.Read(buffer, 0, buffer.Length)) > 0))
                {
                    builder.Append(stringEncoding.GetString(buffer));
                    length = builder.ToString().IndexOf('\0', startIndex);
                    startIndex += num2;
                    if ((len > 0) && (startIndex >= len))
                    {
                        break;
                    }
                }
                if (length > -1)
                {
                    lpBuffer = builder.ToString().Substring(0, length);
                }
                else if ((startIndex >= len) && (len > 0))
                {
                    lpBuffer = builder.ToString().Substring(0, len);
                }
                return (lpBuffer != null);
            }
            catch (Exception exception)
            {
                return this.SetLastError(exception);
            }
        }

19 View Source File : Compression.cs
License : MIT License
Project Creator : BleuBleu

public static byte[] DecompressBytes(byte[] compressedBuffer, int offset = 0)
        {
            var inputStream = new MemoryStream(compressedBuffer);
            inputStream.Seek(offset, SeekOrigin.Begin);
            var bytes = new byte[4];
            inputStream.Read(bytes, 0, 4);
            var decompressedSize = BitConverter.ToInt32(bytes, 0);
            DeflateStream compStream = new DeflateStream(inputStream, CompressionMode.Decompress);
            var buffer = new byte[decompressedSize];
            compStream.Read(buffer, 0, buffer.Length);
            compStream.Close();
            return buffer;
        }

19 View Source File : SnappyInMemoryStream.cs
License : MIT License
Project Creator : aloneguid

public override int Read(byte[] buffer, int offset, int count)
      {
         return _ms.Read(buffer, offset, count);
      }

19 View Source File : RtspTransportClientTests.cs
License : MIT License
Project Creator : BogdanovKirill

protected override Task ReadExactAsync(byte[] buffer, int offset, int count)
            {
                EnsureResponseCreated();

                int read = _responseStream.Read(buffer, offset, count);

                return Task.FromResult(read);
            }

19 View Source File : RdpPacket.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent

public override int Read(byte[] buffer, int offset, int count)
        {
            if ((this.Position + count) > this.Length)
            {
                this.ReadFromSocket(count);
            }

            return base.Read(buffer, offset, count);
        }

19 View Source File : SimpleProxy.cs
License : GNU General Public License v3.0
Project Creator : bp2008

private static byte[] GetResponse(HttpWebRequest webRequest)
		{
			byte[] data;
			using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
			{
				using (MemoryStream ms = new MemoryStream())
				{
					using (Stream responseStream = webResponse.GetResponseStream())
					{
						// Dump the response stream into the MemoryStream ms
						int bytesRead = 1;
						while (bytesRead > 0)
						{
							byte[] buffer = new byte[8000];
							bytesRead = responseStream.Read(buffer, 0, buffer.Length);
							if (bytesRead > 0)
								ms.Write(buffer, 0, bytesRead);
						}
						data = new byte[ms.Length];

						// Dump the data into the byte array
						ms.Seek(0, SeekOrigin.Begin);
						ms.Read(data, 0, data.Length);
						responseStream.Close();
					}
				}
				webResponse.Close();
			}
			return data;
		}

19 View Source File : SimpleMeshSerializer.cs
License : MIT License
Project Creator : anderm

public static byte[] Serialize(IEnumerable<MeshFilter> meshes)
        {
            byte[] data = null;

            using (MemoryStream stream = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    foreach (MeshFilter meshFilter in meshes)
                    {
                        WriteMesh(writer, meshFilter.sharedMesh, meshFilter.transform);
                    }

                    stream.Position = 0;
                    data = new byte[stream.Length];
                    stream.Read(data, 0, data.Length);
                }
            }

            return data;
        }

19 View Source File : ResourceFile.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public void Read(Stream data)
        {
            _header = new ResourceHeader();

            var br = new BinaryReader(data);
            _header.Read(br);
            if (_header.Magic != ResourceHeader.MagicValue)
            {
                throw new Exception("Not a valid resource");
            }

            switch (_header.CompressCodec)
            {
                case CompressionType.LZX:
                    _codec = CompressionCodecFactory.LZX;
                    break;
                case CompressionType.Deflate:
                    _codec = CompressionCodecFactory.Deflate;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            var ms = new MemoryStream();
            _codec.Decompress( data, ms );

            ms.Seek(0, SeekOrigin.Begin);

            _systemMemData = new byte[SystemMemSize];
            ms.Read(_systemMemData, 0, SystemMemSize);

            _graphicsMemData = new byte[GraphicsMemSize];
            ms.Read(_graphicsMemData, 0, GraphicsMemSize);

            ms.Close();
        }

19 View Source File : StreamSerializeTest.cs
License : MIT License
Project Creator : 1996v

public override int Read(byte[] buffer, int offset, int count)
        {
            return this.stream.Read(buffer, offset, count);
        }

19 View Source File : SevenZipHelper.cs
License : MIT License
Project Creator : 91Act

public static byte[] Decompress(byte[] inputBytes)
        {
            MemoryStream newInStream = new MemoryStream(inputBytes);

            Decoder decoder = new Decoder();

            newInStream.Seek(0, 0);
            MemoryStream newOutStream = new MemoryStream();

            byte[] properties2 = new byte[5];
            if (newInStream.Read(properties2, 0, 5) != 5)
                throw (new Exception("input .lzma is too short"));
            long outSize = 0;
            for (int i = 0; i < 8; i++)
            {
                int v = newInStream.ReadByte();
                if (v < 0)
                    throw (new Exception("Can't Read 1"));
                outSize |= ((long)(byte)v) << (8 * i);
            }
            decoder.SetDecoderProperties(properties2);

            long compressedSize = newInStream.Length - newInStream.Position;
            decoder.Code(newInStream, newOutStream, compressedSize, outSize, null);

            byte[] b = newOutStream.ToArray();

            return b;
        }

19 View Source File : StringCompressor.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public static string CompressString(string text)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(text);
            MemoryStream memoryStream = new MemoryStream();
            using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
            {
                gzipStream.Write(bytes, 0, bytes.Length);
            }
            memoryStream.Position = 0L;
            byte[] array = new byte[memoryStream.Length];
            memoryStream.Read(array, 0, array.Length);
            byte[] array2 = new byte[array.Length + 4];
            Buffer.BlockCopy(array, 0, array2, 4, array.Length);
            Buffer.BlockCopy(BitConverter.GetBytes(bytes.Length), 0, array2, 0, 4);
            return Convert.ToBase64String(array2);
        }

19 View Source File : Mnemonic.cs
License : Apache License 2.0
Project Creator : ajuna-network

public static byte[] PBKDF2Sha512GetBytes(int dklen, byte[] preplacedword, byte[] salt, int iterationCount)
        {
            using (var hmac = new HMACSHA512(preplacedword))
            {
                int hashLength = hmac.HashSize / 8;
                if ((hmac.HashSize & 7) != 0)
                    hashLength++;
                int keyLength = dklen / hashLength;
                if (dklen > (0xFFFFFFFFL * hashLength) || dklen < 0)
                {
                    throw new ArgumentOutOfRangeException("dklen");
                }
                if (dklen % hashLength != 0)
                {
                    keyLength++;
                }
                byte[] extendedkey = new byte[salt.Length + 4];
                Buffer.BlockCopy(salt, 0, extendedkey, 0, salt.Length);
                using (var ms = new MemoryStream())
                {
                    for (int i = 0; i < keyLength; i++)
                    {
                        extendedkey[salt.Length] = (byte)(((i + 1) >> 24) & 0xFF);
                        extendedkey[salt.Length + 1] = (byte)(((i + 1) >> 16) & 0xFF);
                        extendedkey[salt.Length + 2] = (byte)(((i + 1) >> 8) & 0xFF);
                        extendedkey[salt.Length + 3] = (byte)(((i + 1)) & 0xFF);
                        byte[] u = hmac.ComputeHash(extendedkey);
                        Array.Clear(extendedkey, salt.Length, 4);
                        byte[] f = u;
                        for (int j = 1; j < iterationCount; j++)
                        {
                            u = hmac.ComputeHash(u);
                            for (int k = 0; k < f.Length; k++)
                            {
                                f[k] ^= u[k];
                            }
                        }
                        ms.Write(f, 0, f.Length);
                        Array.Clear(u, 0, u.Length);
                        Array.Clear(f, 0, f.Length);
                    }
                    byte[] dk = new byte[dklen];
                    ms.Position = 0;
                    ms.Read(dk, 0, dklen);
                    ms.Position = 0;
                    for (long i = 0; i < ms.Length; i++)
                    {
                        ms.WriteByte(0);
                    }
                    Array.Clear(extendedkey, 0, extendedkey.Length);
                    return dk;
                }
            }
        }

19 View Source File : ByteBufferIO.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public static void Write(Stream output, MemoryStream inputStream)
        {
            try
            {
                lock (output)
                {
                    BinaryWriter dataOutput = new BinaryWriter(output);

                    var oldPosition = inputStream.Position;
                    inputStream.Position = 0;
                    dataOutput.WriteRawInt32((int)inputStream.Length);
                    byte[] buffer = new byte[BUFFER_CAPACITY];
                    int readLength;

                    while (inputStream.HasRemaining())
                    {
                        readLength = inputStream.Read(buffer, 0, buffer.Length);
                        dataOutput.Write(buffer, 0, readLength);
                    }
                }
            }
            catch (Exception e)
            {
                throw new IOException("ByteBufferIO.Write: " + e.Message);
            }
        }

See More Examples