public Read ( byte buffer, int offset, int count ) : int | ||
buffer | byte | |
offset | int | |
count | int | |
return | int |
/// <summary> /// Convert Image to Byte[] /// Image img = Image.FromFile("c:\\hcha.jpg"); /// </summary> /// <param name="image"></param> /// <returns></returns> public static byte[] ImageToBytes(Image image) { ImageFormat format = image.RawFormat; using (MemoryStream ms = new MemoryStream()) { if (format.Equals(ImageFormat.Jpeg)) { image.Save(ms, ImageFormat.Jpeg); } else if (format.Equals(ImageFormat.Png)) { image.Save(ms, ImageFormat.Png); } else if (format.Equals(ImageFormat.Bmp)) { image.Save(ms, ImageFormat.Bmp); } else if (format.Equals(ImageFormat.Gif)) { image.Save(ms, ImageFormat.Gif); } else if (format.Equals(ImageFormat.Icon)) { image.Save(ms, ImageFormat.Icon); } byte[] buffer = new byte[ms.Length]; //Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin ms.Seek(0, SeekOrigin.Begin); ms.Read(buffer, 0, buffer.Length); return buffer; } }
static void Main(string[] args) { //CopySelfToDes(); MemoryStream ms = new MemoryStream(); ms.Seek(0, SeekOrigin.End); byte[] bts1 = Encoding.Default.GetBytes("情人"); ms.Write(bts1, 0, bts1.Length); byte[] bts2 = Encoding.Default.GetBytes("我是你的"); ms.Write(bts2, 0, bts2.Length); int totalLen = bts1.Length + bts2.Length; byte[] bts = new byte[totalLen - 2]; //ms.Seek(0, SeekOrigin.Begin); ms.Seek( -4, SeekOrigin.End);//倒着读 int len = ms.Read(bts, 0,4);//你的 ms.Seek(0, SeekOrigin.End);//移到最后 追加 byte[] bts3 = Encoding.Default.GetBytes("淡淡"); ms.Write(bts3, 0, 4); ms.Seek(0, SeekOrigin.Begin); byte[] btsRead = new byte[totalLen+ bts3.Length]; ms.Read(btsRead, 0, totalLen + bts3.Length); ms.Close(); string s = Encoding.Default.GetString(btsRead); Console.WriteLine(s); Console.Read(); }
private static void ReturnImage(HttpContext context, string imageNameQuery) { if (!string.IsNullOrWhiteSpace(imageNameQuery)) { using (var db = new AvensiaWebshopEntities()) { var imageQuery = db.ProductPhoto.FirstOrDefault(i => i.LargePhotoFileName == imageNameQuery); if (imageQuery == null) { Return404(context); return; } context.Response.ContentType = "image/gif"; Stream strm = new MemoryStream(imageQuery.LargePhoto); byte[] buffer = new byte[4096]; int byteSeq = strm.Read(buffer, 0, 4096); while (byteSeq > 0) { context.Response.OutputStream.Write(buffer, 0, byteSeq); byteSeq = strm.Read(buffer, 0, 4096); } } } }
private static Queue<byte[]> GetFileParts(byte[] file) { var fileParts = new Queue<byte[]>(); const int maxFilePart = 512 * 1024; using (var stream = new MemoryStream(file)) { while (stream.Position != stream.Length) { if ((stream.Length - stream.Position) > maxFilePart) { var temp = new byte[maxFilePart]; stream.Read(temp, 0, maxFilePart); fileParts.Enqueue(temp); } else { var length = stream.Length - stream.Position; var temp = new byte[length]; stream.Read(temp, 0, (int)(length)); fileParts.Enqueue(temp); } } } return fileParts; }
public void TLLongSerialization() { var buffer1 = BitConverter.GetBytes(25565L); var buffer2 = BitConverter.GetBytes(99999L); var pos = 0; CollectionAssert.AreEquivalent(buffer1, new TLLong(buffer1, ref pos).ToBytes()); pos = 0; CollectionAssert.AreEquivalent(buffer2, new TLLong(buffer2, ref pos).ToBytes()); using (var stream = new MemoryStream()) { new TLLong(25565L).ToStream(stream); new TLLong(99999L).ToStream(stream); stream.Position = 0; var actualBuffer1 = new byte[8]; var actualBuffer2 = new byte[8]; stream.Read(actualBuffer1, 0, 8); stream.Read(actualBuffer2, 0, 8); CollectionAssert.AreEquivalent(buffer1, actualBuffer1); CollectionAssert.AreEquivalent(buffer2, actualBuffer2); } }
/// <summary> /// Default constructor. /// </summary> /// <param name="mimeEntry"></param> /// <param name="mime"></param> public MimeEntry(byte[] mimeEntry,MimeParser mime) { MemoryStream entryStrm = new MemoryStream(mimeEntry); m_Headers = MimeParser.ParseHeaders(entryStrm); m_ContentType = mime.ParseContentType(m_Headers); m_Entries = new ArrayList(); // != multipart content if(m_ContentType.ToLower().IndexOf("multipart") == -1){ m_CharSet = ParseCharSet(m_Headers); m_ContentEncoding = ParseEncoding(m_Headers); m_Data = new byte[entryStrm.Length - entryStrm.Position]; entryStrm.Read(m_Data,0,m_Data.Length); } // multipart content, get nested entries else{ long s = (int)entryStrm.Position; string boundaryID = MimeParser.ParseHeaderFiledSubField("Content-Type:","boundary",m_Headers); m_Entries = mime.ParseEntries(entryStrm,(int)entryStrm.Position,boundaryID); entryStrm.Position = s; m_Data = new byte[entryStrm.Length - s]; entryStrm.Read(m_Data,0,m_Data.Length); } }
private static byte[] DecryptDataAsBytes(byte[] encryptedData, string privateKeyPem, string publicKeyPem) { using (var encryptedDataStream = new MemoryStream(encryptedData)) using (var encryptedDataWithoutKeyPair = new MemoryStream()) { var signatureLengthBytes = new byte[4]; var bytesRead = encryptedDataStream.Read(signatureLengthBytes, 0, 4); if (bytesRead == -1) throw new Exception("Unexpected end of encrypted data (expected encrypted key size)"); var signatureLength = BitConverter.ToInt32(signatureLengthBytes, 0); var signature = new byte[signatureLength]; bytesRead = encryptedDataStream.Read(signature, 0, signatureLength); if (bytesRead != signatureLength) throw new Exception("Unexpected end of encrypted data (expected encrypted key)"); encryptedDataStream.CopyTo(encryptedDataWithoutKeyPair); var decryptedData = EncryptedDataWithKeyPair.DecryptDataAsBytes( encryptedDataWithoutKeyPair.ToArray(), privateKeyPem); var signatureVerified = AsymmetricCryptoUtil.VerifySignature(decryptedData, signature, publicKeyPem); if (!signatureVerified) throw new Exception("Message could not be verified"); return decryptedData; } }
public int Deserialize(byte[] data) { int r = 0; using (MemoryStream ms = new MemoryStream(data)) { byte[] _t = new byte[sizeof(long)]; r += ms.Read(_t, 0, _t.Length); long time = BitConverter.ToInt64(_t, 0); this._timestamp = new DateTime(time, DateTimeKind.Utc); _t = new byte[sizeof(short)]; r += ms.Read(_t, 0, _t.Length); this._tag = BitConverter.ToInt16(_t, 0); _t = new byte[sizeof(int)]; r += ms.Read(_t, 0, _t.Length); int str_len = BitConverter.ToInt32(_t, 0); _t = new byte[str_len]; r += ms.Read(_t, 0, _t.Length); this._message = UnicodeEncoding.UTF8.GetString(_t); _t = new byte[sizeof(int)]; r += ms.Read(_t, 0, _t.Length); str_len = BitConverter.ToInt32(_t, 0); _t = new byte[str_len]; r += ms.Read(_t, 0, _t.Length); this._details = UnicodeEncoding.UTF8.GetString(_t); _t = ms.ToArray(); } return r; }
public MemoryStream Encode(MemoryStream memoryStream) { memoryStream.Position = 0; byte[] buffer320 = new byte[320]; byte[] buffer32 = new byte[32]; MemoryStream raw2armData = new MemoryStream(); raw2armData.Write(Encoding.UTF8.GetBytes("#!AMR\n"), 0, 6); AMR_Encoder enc = new AMR_Encoder(); int start = 0; int end = Convert.ToInt32(memoryStream.Length); memoryStream.Position = start; while (true) { if (end - start < 320) { memoryStream.Read(buffer320, 0, end - start); for (int i = end - start; i < 320; i++) { buffer320[i] = 0; } } else { memoryStream.Read(buffer320, 0, 320); } enc.Encode(buffer320, 0, buffer32, 0); raw2armData.Write(buffer32, 0, buffer32.Length); start += 320; if (start >= end) break; } return raw2armData; }
public byte[] GetUncompressedNdfbinary(byte[] data) { using (var ms = new MemoryStream(data)) { var header = ReadHeader(ms); if (header.IsCompressedBody) { using (var uncompStream = new MemoryStream()) { ms.Seek(0, SeekOrigin.Begin); var headBuffer = new byte[header.HeaderSize]; ms.Read(headBuffer, 0, headBuffer.Length); uncompStream.Write(headBuffer, 0, headBuffer.Length); ms.Seek((long)header.HeaderSize, SeekOrigin.Begin); var buffer = new byte[4]; ms.Read(buffer, 0, buffer.Length); uint compressedblocklen = BitConverter.ToUInt32(buffer, 0); var contentBuffer = new byte[(ulong)(data.Length) - header.HeaderSize]; ms.Read(contentBuffer, 0, contentBuffer.Length); //Compressor.Decomp(contentBuffer, uncompStream); var da = Compressor.Decomp(contentBuffer); uncompStream.Write(da, 0, da.Length); data = uncompStream.ToArray(); } } } return data; }
public override bool UploadFile() { FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(this.UrlString); reqFTP.KeepAlive = true; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.ContentLength = this.FileData.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; MemoryStream ms = new MemoryStream(this.FileData); try { int contenctLength; using (Stream strm = reqFTP.GetRequestStream()) { contenctLength = ms.Read(buff, 0, buffLength); while (contenctLength > 0) { strm.Write(buff, 0, contenctLength); contenctLength = ms.Read(buff, 0, buffLength); } } return true; } catch (Exception ex) { throw new Exception("上传失败", ex.InnerException); } }
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is byte[]) { var components = new List<CassandraType>(); using (var bytes = new MemoryStream((byte[])value)) { byte[] byteCount = new byte[2]; while (true) { if (bytes.Read(byteCount, 0, 2) == 0) break; ushort count = BitConverter.ToUInt16(byteCount, 0); byte[] buffer = new byte[count]; bytes.Read(buffer, 0, count); components.Add((BytesType)buffer); if (bytes.ReadByte() != 0) break; } } } if (value is List<CassandraType>) return (List<CassandraType>)value; return null; }
/// <summary> /// Extract WAV data from Memory Stream (assumes mono, 16-bit signed PCM for now) /// </summary> /// <param name="stream">MemoryStream</param> /// <returns>Short array with all data</returns> public static short[] ReadWAVFile(MemoryStream stream) { if (!stream.CanSeek) throw new Exception("Can't seek stream to read wav header"); stream.Seek(40, SeekOrigin.Begin); Byte[] lengthData = new Byte[4]; int numBytesRead = stream.Read(lengthData, 0, 4); if (numBytesRead != 4) throw new Exception("Stream ended while reading length value"); int lengthBytes = BitConverter.ToInt32(lengthData, 0); System.Diagnostics.Debug.WriteLine("Bytes read: " + lengthBytes); int dataStartByte = 44; stream.Seek(dataStartByte, SeekOrigin.Begin); Byte[] audioData = new Byte[lengthBytes]; numBytesRead = stream.Read(audioData, 0, lengthBytes); if (numBytesRead != lengthBytes) throw new Exception("Could not read " + lengthBytes + " bytes, only read " + numBytesRead + " bytes."); short[] shortData = new short[lengthBytes / 2]; for (int i = 0; i < lengthBytes; i += 2) { shortData[i / 2] = BitConverter.ToInt16(audioData, i); } return shortData; }
private CommandBuilder(Connection connection, byte[] receivedBuffer) { m_ReceivedBuffer = receivedBuffer; MemoryStream command = new MemoryStream(m_ReceivedBuffer); byte[] header = new byte[Encoding.ASCII.GetByteCount(Constants.Protocol)]; command.Read(header, 0, header.Length); if (!Encoding.ASCII.GetString(header).Equals(Constants.Protocol)) throw new InvalidDataException(); m_EncryptionMethod = (EncryptionMethod)command.ReadByte(); byte[] encryptedDataLength = new byte[2]; command.Read(encryptedDataLength, 0, encryptedDataLength.Length); byte[] encryptedData = new byte[BitConverter.ToUInt16(encryptedDataLength, 0)]; if (encryptedData.Length > command.Position + encryptedData.Length) throw new InvalidDataException(); command.Read(encryptedData, 0, encryptedData.Length); switch (m_EncryptionMethod) { case EncryptionMethod.None: m_CommandData = new MemoryStream(encryptedData); break; case EncryptionMethod.Rijndael: m_CommandData = new MemoryStream(Core.RijndaelDecrypt(connection.ReceivingKey, encryptedData)); break; case EncryptionMethod.RSA: m_CommandData = new MemoryStream(Core.RSADecrypt(encryptedData)); break; default: throw new InvalidDataException(); } }
public DescriptionMessage(byte[] bytes) { using (MemoryStream ms = new MemoryStream(bytes, false)) { Name = TextHelper.DeStreamString(ms); Location = TextHelper.DeStreamString(ms); Description = TextHelper.DeStreamString(ms); // Sensors Length byte[] lengthBytes = new byte[sizeof(Int32)]; ms.Read(lengthBytes, 0, sizeof(Int32)); int length = BitConverter.ToInt32(lengthBytes, 0); byte[] sensorsBytes = new byte[length]; ms.Read(sensorsBytes, 0, length); Sensors = MessageHelper.DeserializeSensorDescriptionsData(sensorsBytes); // Length ms.Read(lengthBytes, 0, sizeof(Int32)); length = BitConverter.ToInt32(lengthBytes, 0); PictureBytes = new byte[length]; ms.Read(PictureBytes, 0, length); } }
private static void ReturnTumbNail(HttpContext context, string thumbNailProductIDQuery) { int productID; if (!string.IsNullOrWhiteSpace(thumbNailProductIDQuery) && int.TryParse(thumbNailProductIDQuery, out productID)) { using (var db = new AvensiaWebshopEntities()) { var imageQuery = db.Product.FirstOrDefault(p => p.ProductID == productID); if (imageQuery == null) { Return404(context); return; } context.Response.ContentType = "image/gif"; Stream strm = new MemoryStream(imageQuery.ThumbNailPhoto); byte[] buffer = new byte[4096]; int byteSeq = strm.Read(buffer, 0, 4096); while (byteSeq > 0) { context.Response.OutputStream.Write(buffer, 0, byteSeq); byteSeq = strm.Read(buffer, 0, 4096); } } } }
public string DoDecryptAES(string _encString, string _userPass) { // 複合化する対象となる16進数文字列をバイト型の配列に格納。 byte[] _aftData = HexString2Byte(_encString); // 複合化で使用するAesCryptoServiceProviderオブジェクトの作成。 // AES(Rjindael)の場合 BlockSize = 128bit, KeySize = 128bit, 192bit, 256bit のどれか。 AesCryptoServiceProvider dec = new AesCryptoServiceProvider(); dec.BlockSize = 128; dec.KeySize = 128; dec.Mode = CipherMode.CBC; dec.Padding = PaddingMode.PKCS7; // 秘密鍵の設定。パスワードを有効なキーサイズに調整。キーサイズは128bit。 byte[] _bytePassWordKey = Encoding.UTF8.GetBytes(_userPass); byte[] _byteKey = new byte[16]; byte[] _byteIV = new byte[16]; for (int i = 0; i < 16; i++) { if (i < _bytePassWordKey.Length) { _byteKey[i] = _bytePassWordKey[i]; } else { _byteKey[i] = 0; } } dec.Key = _byteKey; // 初期化ベクトルの設定。暗号化されたデータの先頭16byteを読み取り初期ベクトルを抜き出す。 MemoryStream msForIV = new MemoryStream(_aftData); msForIV.Read(_byteIV, 0, 16); dec.IV = _byteIV; // 複号化で使用するAES複号オブジェクトの作成。 ICryptoTransform decrypt = dec.CreateDecryptor(); // 暗号化データを読み込み複合化する。 MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write); byte[] buffer = new byte[1024]; int length; while ((length = msForIV.Read(buffer, 0, buffer.Length)) > 0) { cs.Write(buffer, 0, length); } cs.Close(); string _tmpReturnString = Encoding.UTF8.GetString(ms.ToArray()); msForIV.Close(); ms.Close(); decrypt.Dispose(); return _tmpReturnString; }
public static string DeStreamString(MemoryStream ms, Encoding encoding) { byte[] stringLengthBytes = new byte[sizeof(int)]; ms.Read(stringLengthBytes, 0, sizeof(int)); int stringLength = BitConverter.ToInt32(stringLengthBytes, 0); byte[] stringBytes = new byte[stringLength]; ms.Read(stringBytes, 0, stringLength); string stringToReturn = encoding.GetString(stringBytes, 0, stringLength); return stringToReturn; }
public NdfBinary Read(byte[] data) { var ndf = new NdfBinary(); using (var ms = new MemoryStream(data)) { ndf.Header = ReadHeader(ms); if (ndf.Header.IsCompressedBody) { using (var uncompStream = new MemoryStream()) { ms.Seek(0, SeekOrigin.Begin); var headBuffer = new byte[ndf.Header.HeaderSize]; ms.Read(headBuffer, 0, headBuffer.Length); uncompStream.Write(headBuffer, 0, headBuffer.Length); ms.Seek((long)ndf.Header.HeaderSize, SeekOrigin.Begin); var buffer = new byte[4]; ms.Read(buffer, 0, buffer.Length); uint compressedblocklen = BitConverter.ToUInt32(buffer, 0); var contentBuffer = new byte[(ulong)(data.Length) - ndf.Header.HeaderSize]; ms.Read(contentBuffer, 0, contentBuffer.Length); var da = Compressor.Decomp(contentBuffer); uncompStream.Write(da, 0, da.Length); data = uncompStream.ToArray(); } } } using (var ms = new MemoryStream(data)) { ndf.Footer = ReadFooter(ms, ndf.Header); ndf.Classes = ReadClasses(ms, ndf); ReadProperties(ms, ndf); ndf.Strings = ReadStrings(ms, ndf); ndf.Trans = ReadTrans(ms, ndf); ndf.TopObjects = new HashSet<uint>(ReadUIntList(ms, ndf, "TOPO")); ndf.Import = ReadUIntList(ms, ndf, "IMPR"); ndf.Export = ReadUIntList(ms, ndf, "EXPR"); ndf.Instances = ReadObjects(ms, ndf); } return ndf; }
public TgvFile ReadDDS(byte[] input) { int contentSize = input.Length - Marshal.SizeOf(typeof(DDS.DDS.Header)) - Marshal.SizeOf((typeof(uint))); var file = new TgvFile(); using (var ms = new MemoryStream(input)) { var buffer = new byte[4]; ms.Read(buffer, 0, buffer.Length); if (BitConverter.ToUInt32(buffer, 0) != DDS.DDS.MagicHeader) throw new ArgumentException("Wrong DDS magic"); buffer = new byte[Marshal.SizeOf(typeof(DDS.DDS.Header))]; ms.Read(buffer, 0, buffer.Length); var header = Utils.ByteArrayToStructure<DDS.DDS.Header>(buffer); int mipSize = contentSize; if (header.MipMapCount == 0) header.MipMapCount = 1; else mipSize -= contentSize / header.MipMapCount; for (ushort i = 0; i < header.MipMapCount; i++) { buffer = new byte[mipSize]; ms.Read(buffer, 0, buffer.Length); var mip = new TgvMipMap { Content = buffer }; file.MipMaps.Add(mip); mipSize /= 4; } file.Height = header.Height; file.ImageHeight = header.Height; file.Width = header.Width; file.ImageWidth = header.Width; file.MipMapCount = (ushort)header.MipMapCount; DDSHelper.ConversionFlags conversionFlags; file.Format = DDSHelper.GetDXGIFormat(ref header.PixelFormat, out conversionFlags); } return file; }
public ImageAnnotation(byte[] data) { using(MemoryStream ms = new MemoryStream(data)) { base.ReadBaseData(ms); this.Comment = TextHelper.DeStreamString(ms); byte[] imageLengthBytes = new byte[sizeof(Int32)]; ms.Read(imageLengthBytes, 0, sizeof(Int32)); int imageLength = BitConverter.ToInt32(imageLengthBytes, 0); ImageData = new byte[imageLength]; ms.Read(ImageData, 0, imageLength); } }
/// <summary> /// Extracts thumbnails from metadata and saves them to thumb directory /// </summary> /// <param name="directory">The directory which will be scanned</param> public static void ExtractThumbnails(string[] files) { SetProcess ("-q -q -previewImage -b -@ -", ExifArgument.Thumbnails); exiftool.Start (); byte[] data = Encoding.UTF8.GetBytes (String.Join ("\r\n", files)); exiftool.StandardInput.BaseStream.Write (data, 0, data.Length); exiftool.StandardInput.BaseStream.Close (); using(MemoryStream str = new MemoryStream()) { exiftool.StandardOutput.BaseStream.CopyTo (str); str.Position = 0; List<long> idx = new List<long>(); byte[] tmp = new byte[2]; for (long ct = 0; ct < str.Length; ct++) { str.Position = ct; str.Read (tmp, 0, 2); if (BitConverter.IsLittleEndian) Array.Reverse (tmp); if (BitConverter.ToUInt16 (tmp, 0) == JpgMarker) idx.Add (ct); } if (idx.Count != ProjectManager.CurrentProject.Frames.Count) throw new Exception("Not all images have a thumbnail"); BitmapEx tmpBmp = null; byte[] buffer; long length; for (int i = 0; i < idx.Count; i++) { if (ProjectManager.CurrentProject.MainWorker.CancellationPending) break; if (i + 1 < idx.Count) length = idx[i + 1] - idx[i]; else length = str.Length - idx[i]; buffer = new byte[length]; str.Position = idx[i]; str.Read (buffer, 0, (int)length); using(MemoryStream str2 = new MemoryStream(buffer)) { tmpBmp = new BitmapEx(str2).ScaleW (300); ProjectManager.CurrentProject.AddThumb (tmpBmp); //Normal Thumb ProjectManager.CurrentProject.AddThumb (tmpBmp); //Edit Thumb ProjectManager.CurrentProject.ReportWorkProgress (i, ProgressType.LoadThumbnails); } } if (tmpBmp != null) tmpBmp.Dispose (); buffer = null; } exiftool.WaitForExit(); exiftool.Dispose(); }
internal Status(byte[] message) { _keyValues = new Dictionary<string, string>(); _players = new List<string>(); var buffer = new byte[256]; Stream stream = new MemoryStream(message); stream.Read(buffer, 0, 5);// Read Type + SessionID stream.Read(buffer, 0, 11); // Padding: 11 bytes constant var constant1 = new byte[] { 0x73, 0x70, 0x6C, 0x69, 0x74, 0x6E, 0x75, 0x6D, 0x00, 0x80, 0x00 }; for (int i = 0; i < constant1.Length; i++) Debug.Assert(constant1[i] == buffer[i], "Byte mismatch at " + i + " Val :" + buffer[i]); var sb = new StringBuilder(); string lastKey = string.Empty; int currentByte; while ((currentByte = stream.ReadByte()) != -1) { if (currentByte == 0x00) { if (!string.IsNullOrEmpty(lastKey)) { _keyValues.Add(lastKey, sb.ToString()); lastKey = string.Empty; } else { lastKey = sb.ToString(); if (string.IsNullOrEmpty(lastKey)) break; } sb.Clear(); } else sb.Append((char)currentByte); } stream.Read(buffer, 0, 10); // Padding: 10 bytes constant var constant2 = new byte[] { 0x01, 0x70, 0x6C, 0x61, 0x79, 0x65, 0x72, 0x5F, 0x00, 0x00 }; for (int i = 0; i < constant2.Length; i++) Debug.Assert(constant2[i] == buffer[i], "Byte mismatch at " + i + " Val :" + buffer[i]); while ((currentByte = stream.ReadByte()) != -1) { if (currentByte == 0x00) { var player = sb.ToString(); if (string.IsNullOrEmpty(player)) break; _players.Add(player); sb.Clear(); } else sb.Append((char)currentByte); } }
public new static SecretKey Parse(Packet input) { SecretKey sk = (SecretKey)input; sk = (SecretKey)PublicKey.Parse(input); MemoryStream ms = new MemoryStream(sk.RawData); ms.Position = sk.TempPosition; // String to key usage ? byte s2kUsage = (byte)ms.ReadByte(); if (s2kUsage == 255 || s2kUsage == 254) { // We'll be using String to key...but with which algorithm ? sk.SymmetricKeyAlgorithm = (SymmetricKeyAlgorithm)ms.ReadByte(); // And which type of S2K ? sk.StringToKeySpecifierType = (StringToKeySpecifierType)ms.ReadByte(); sk.InitialVector = new byte[Constants.GetCipherBlockSize(sk.SymmetricKeyAlgorithm)]; ms.Read(sk.InitialVector, 0, sk.InitialVector.Length); } else if (s2kUsage == 0) { } else { sk.SymmetricKeyAlgorithm = (SymmetricKeyAlgorithm)s2kUsage; sk.InitialVector = new byte[Constants.GetCipherBlockSize(sk.SymmetricKeyAlgorithm)]; ms.Read(sk.InitialVector, 0, sk.InitialVector.Length); } // MPIs int mpiMaxCount = Constants.GetTotalMPICount(sk.PublicKeyAlgorithm); while (ms.Position < ms.Length && sk.MPIs.Count < mpiMaxCount) { byte first = (byte)ms.ReadByte(); byte second = (byte)ms.ReadByte(); short length = (short)((Converter.ToShort(new byte[2] { first, second }) + 7) / 8); byte[] mpi = new byte[(int)length]; ms.Read(mpi, 0, length); sk.MPIs.Add(mpi); } sk.CheckSum = new byte[2]; ms.Read(sk.CheckSum, 0, 2); return sk; }
public override void ParseRecord(ref MemoryStream ms) { // Bit map is the data length minus the IpAddress (4 bytes) and the Protocol (1 byte), 5 bytes total. int bitMapLen = this.DnsHeader.DataLength - 4 - 1; byte[] ipAddr = new byte[4]; byte[] BitMap = new byte[bitMapLen]; ms.Read(ipAddr, 0, 4); // _ipAddress = new IPAddress(Tools.ToUInt32(ipAddr, 0)); _ipAddress = new IPAddress((uint)IPAddress.NetworkToHostOrder(BitConverter.ToUInt32(ipAddr, 0))); _protocolType = (ProtocolType)ms.ReadByte(); ms.Read(BitMap, 0, BitMap.Length); _ports = GetKnownServices(BitMap); _answer = _protocolType + ": " + Tools.GetServByPort(_ports, _protocolType); }
public void Decode(MemoryStream ms) { int len = 0; byte[] data = null; len = this.ReadHeader(ms); data = new byte[len]; ms.Read(data, 0, len); this._screen = new MemoryStream(data); len = this.ReadHeader(ms); data = new byte[len]; ms.Read(data, 0, len); this._log = new MemoryStream(data); }
public static void SendMessage(IntPtr hWnd, string message) { BinaryFormatter b = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); b.Serialize(stream, message); stream.Flush(); // Now move the data into a pointer so we can send // it using WM_COPYDATA: // Get the length of the data: int dataSize = (int)stream.Length; if (dataSize > 0) { byte[] data = new byte[dataSize]; stream.Seek(0, SeekOrigin.Begin); stream.Read(data, 0, dataSize); IntPtr ptrData = Marshal.AllocCoTaskMem(dataSize); Marshal.Copy(data, 0, ptrData, dataSize); COPYDATASTRUCT cds = new COPYDATASTRUCT(); cds.cbData = dataSize; cds.dwData = IntPtr.Zero; cds.lpData = ptrData; int res = SendMessage(hWnd, WM_COPYDATA, 0, ref cds); // Clear up the data: Marshal.FreeCoTaskMem(ptrData); } stream.Close(); }
public static void SendFileInfo() { // Получаем тип и расширение файла fileDet.FILETYPE = fs.Name.Substring((int)fs.Name.Length - 3, 3); // Получаем длину файла fileDet.FILESIZE = fs.Length; XmlSerializer fileSerializer = new XmlSerializer(typeof(FileDetails)); MemoryStream stream = new MemoryStream(); // Сериализуем объект fileSerializer.Serialize(stream, fileDet); // Считываем поток в байты stream.Position = 0; Byte[] bytes = new Byte[stream.Length]; stream.Read(bytes, 0, Convert.ToInt32(stream.Length)); Console.WriteLine("Отправка деталей файла..."); // Отправляем информацию о файле sender.Send(bytes, bytes.Length, endPoint); stream.Close(); }
public void GetTest() { var accessToken = AccessTokenContainer.GetToken(_appId); UploadTest();//上传 using (MemoryStream ms = new MemoryStream()) { Media.Get(accessToken, mediaId, ms); Assert.IsTrue(ms.Length > 0); //保存到文件 var fileName = string.Format(@"E:\testpic_{0}.jpg", DateTime.Now.Ticks); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { ms.Position = 0; byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) != 0) { fs.Write(buffer, 0, bytesRead); } fs.Flush(); } Assert.IsTrue(File.Exists(fileName)); } }
/// <summary> /// Returns the parameters array formatted for multi-part/form data /// </summary> /// <returns></returns> public byte[] GetPostDataWithMultipart(string boundary) { var ms = new MemoryStream(); foreach (var p in Params) { if (p.Type == PostDataParamType.File) { var header = string.Format("\r\n--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{1}\";\r\nContent-Type: application/octet-stream\r\n\r\n", boundary, p.FilePath); ms.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header)); ms.Write((byte[])p.Value, 0, ((byte[])p.Value).Length); } else { var postData = string.Format("\r\n--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", boundary, p.Name, p.Value); ms.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); } } var footer = "\r\n--" + boundary + "--\r\n"; ms.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); ms.Position = 0; var tempBuffer = new byte[ms.Length]; ms.Read(tempBuffer, 0, tempBuffer.Length); ms.Close(); return tempBuffer; }
public static byte[] ConverterImagemParaByteArray() { try { using (var stream = new System.IO.MemoryStream()) { //webCamPictureBox.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Png); stream.Seek(0, System.IO.SeekOrigin.Begin); byte[] bArray = new byte[stream.Length]; stream.Read(bArray, 0, System.Convert.ToInt32(stream.Length)); return(bArray); } } catch { throw new Exception("NÃO FOI POSSÍVEL CONVERTER O ARQUIVO EM BYTES."); } }
private static byte[] GetMultipartMixedFormData(string boundary, byte[] postQueryData = null, byte[] postData = null, bool isOctet = false) { var encoding = Encoding.UTF8; Stream formDataStream = new System.IO.MemoryStream(); if (postQueryData != null && postQueryData.Length > 0) { // adds url query to the body // https://docs.microsoft.com/en-us/linkedin/shared/api-guide/concepts/query-tunneling string queryHeader = $"--{boundary}\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n"; formDataStream.Write(encoding.GetBytes(queryHeader), 0, encoding.GetByteCount(queryHeader)); formDataStream.Write(postQueryData, 0, postQueryData.Length); string queryBoundary = $"\r\n--{boundary}\r\n"; formDataStream.Write(encoding.GetBytes(queryBoundary), 0, encoding.GetByteCount(queryBoundary)); } if (postData != null && postData.Length > 0) { // adds post data to the body string postHeader = $"--{boundary}\r\nContent-Type: application/json\r\n\r\n"; if (isOctet) { // adds asset data to the body postHeader = $"--{boundary}\r\nContent-Type: application/octet-stream\r\n\r\n"; } formDataStream.Write(encoding.GetBytes(postHeader), 0, encoding.GetByteCount(postHeader)); // Write the file data directly to the Stream, rather than serializing it to a string. formDataStream.Write(postData, 0, postData.Length); string postBoundary = $"\r\n--{boundary}--\r\n"; formDataStream.Write(encoding.GetBytes(postBoundary), 0, encoding.GetByteCount(postBoundary)); } // Dump the Stream into a byte[] formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Close(); return(formData); }
public JsonResult UploadBG(int WarehouseID) { try { HttpPostedFileBase file = Request.Files[0] as HttpPostedFileBase; int fileSizeInBytes = file.ContentLength; MemoryStream target = new MemoryStream(); file.InputStream.CopyTo(target); Byte[] bytes = target.ToArray(); System.IO.Stream stream = new System.IO.MemoryStream(); Int64 data64 = stream.Read(bytes, 0, (Int32)stream.Length); stream.Close(); String img64 = Convert.ToBase64String(bytes, 0, bytes.Length); Warehouse warehouse = db.Warehouses.Find(WarehouseID); warehouse.BackgroundPicture = img64; warehouse.ImageUpdate = DateTime.Now; db.Entry(warehouse).State = EntityState.Modified; db.SaveChanges(); var w = (from a in db.Warehouses where a.PvID == warehouse.PvID select a).ToList(); foreach (var a in w) { a.BackgroundPicture = img64; a.ImageUpdate = DateTime.Now; db.SaveChanges(); } return(Json("success")); } catch (Exception ex) { return(Json("error")); } }
//图片转为base64编码的字符串 protected string ImgToBase64String(string Imagefilename) { try { System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Imagefilename); System.IO.MemoryStream ms = new System.IO.MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); return(Convert.ToBase64String(arr)); } catch (Exception ex) { return(null); } }
/// <summary> /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file) /// </summary> /// <param name="ds">DataSet containing the data to be written to the Excel.</param> /// <param name="filename">The filename (without a path) to call the new Excel file.</param> /// <param name="Response">HttpResponse of the current page.</param> /// <returns>Either a MemoryStream, or NULL if something goes wrong.</returns> public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response) { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(); using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true)) { WriteExcelFile(ds, document); } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; // NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have // manually added System.Web to this project's References. Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); // Feb2015: Needed to replace "Response.End();" with the following 3 lines, to make sure the Excel was fully written to the Response System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.SuppressContent = true; System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); return(true); } catch (Exception ex) { Trace.WriteLine("Failed, exception thrown: " + ex.Message); return(false); } }
private void SaveUpload(string dbConnectionString, byte sid) { if (Request.Files.Count > 0 && Request.Files[0].FileName != string.Empty && "image/gif,image/jpeg,image/png,image/tiff,image/pjpeg,image/x-png".IndexOf(Request.Files[0].ContentType) >= 0) { byte[] dc; System.Drawing.Image oBMP = System.Drawing.Image.FromStream(Request.Files[0].InputStream); int nHeight = 150; if (Request.QueryString["hgt"] != null && !string.IsNullOrEmpty(Request.QueryString["hgt"].ToString())) { nHeight = int.Parse(Request.QueryString["hgt"].ToString()); } int nWidth = int.Parse((Math.Round(decimal.Parse(oBMP.Width.ToString()) * (nHeight / decimal.Parse(oBMP.Height.ToString())))).ToString()); Bitmap nBMP = new Bitmap(oBMP, nWidth, nHeight); using (System.IO.MemoryStream sm = new System.IO.MemoryStream()) { nBMP.Save(sm, System.Drawing.Imaging.ImageFormat.Jpeg); sm.Position = 0; dc = new byte[sm.Length + 1]; sm.Read(dc, 0, dc.Length); sm.Close(); } oBMP.Dispose(); nBMP.Dispose(); new AdminSystem().UpdDbImg(Request.QueryString["key"], Request.QueryString["tbl"], Request.QueryString["knm"], Request.QueryString["col"].ToString(), dc, dbConnectionString, base.AppPwd(sid)); Response.Buffer = true; Response.ClearHeaders(); Response.ClearContent(); string imgEmbedded = "data:application/base64;base64," + Convert.ToBase64String(dc); string json = "{\"imgUrl\":\"" + imgEmbedded + "\"}"; Response.Clear(); Response.ContentType = "application/json; charset=utf-8"; Response.Write(json); Response.End(); } else if (Request.QueryString["del"] != null) { //delete image new AdminSystem().UpdDbImg(Request.QueryString["key"], Request.QueryString["tbl"], Request.QueryString["knm"], Request.QueryString["col"].ToString(), null, dbConnectionString, base.AppPwd(sid)); Response.Buffer = true; Response.ClearHeaders(); Response.ClearContent(); string json = "{\"imgUrl\":\"" + "images/DefaultImg.png" + "\"}"; Response.Clear(); Response.ContentType = "application/json; charset=utf-8"; Response.Write(json); Response.End(); } }
/// <summary> /// Build Multipart Formdata from files and regions. /// </summary> /// <param name="filePath">File path.</param> /// <param name="regions">Regions</param> /// <param name="boundary">Boundary.</param> /// <returns></returns> private static byte[] GetMultipartFormData(string filePath, string regions, string boundary) { Stream formDataStream = new System.IO.MemoryStream(); if (!string.IsNullOrWhiteSpace(filePath)) { // Add just the first part of this param, since we will write the file data directly to the Stream string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n", boundary, "upload", filePath, "application/octet-stream"); formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header)); Byte[] file = File.ReadAllBytes(filePath); // Write the file data directly to the Stream, rather than serializing it to a string. formDataStream.Write(file, 0, file.Length); } if (!string.IsNullOrWhiteSpace(regions)) { formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n")); string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", boundary, "regions", regions); formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); } // Add the end of the request. Start with a newline string footer = "\r\n--" + boundary + "--\r\n"; formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); // Dump the Stream into a byte[] formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Close(); return(formData); }
/// <summary> /// 压缩字符串后并使用 Base64 编码,字符编码为 UTF-8 /// </summary> /// <param name="str"></param> /// <returns>压缩后的字符串</returns> public static string Zip(this string str) { byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { zip.Write(buffer, 0, buffer.Length); } ms.Position = 0; System.IO.MemoryStream outStream = new System.IO.MemoryStream(); byte[] compressed = new byte[ms.Length]; ms.Read(compressed, 0, compressed.Length); byte[] gzBuffer = new byte[compressed.Length + 4]; System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4); return(Convert.ToBase64String(gzBuffer)); }
public static byte[] Encrypt(this SystemEnvironment environment) { byte[] byteArray; System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); System.IO.MemoryStream memStream = new System.IO.MemoryStream(); serializer.Serialize(memStream, environment); // Set the position to the beginning of the stream. memStream.Seek(0, SeekOrigin.Begin); // Read the first 20 bytes from the stream. byteArray = new byte[memStream.Length]; memStream.Read(byteArray, 0, (int)memStream.Length); memStream.Close(); //加密 return(AESHelper.AesEncrypt(byteArray, AESHelper.AESKEY)); //return byteArray; }
/// <summary> /// Creates a copy of the stream, with removed Utf8 BOM, if any /// </summary> /// <param name="ms">The stream to fix</param> /// <returns>A stream with no Utf8 BOM</returns> internal static System.IO.MemoryStream RemoveUTF8BOM(System.IO.MemoryStream ms) { //Skip UTF file header, since the MapGuide XmlParser is broken ms.Position = 0; byte[] utfheader = new byte[3]; if (ms.Read(utfheader, 0, utfheader.Length) == utfheader.Length) { if (utfheader[0] == 0xEF && utfheader[1] == 0xBB && utfheader[2] == 0xBF) { ms.Position = 3; System.IO.MemoryStream mxs = new System.IO.MemoryStream(); Utils.CopyStream(ms, mxs, false); mxs.Position = 0; return(mxs); } } ms.Position = 0; return(ms); }
/// <summary> /// Will save the workbook to the output stream. Typically will be used to write directly to the response. /// </summary> public static void WriteToStream(this E.Workbook workbook, Stream outputStream) { var stream = new System.IO.MemoryStream(); workbook.Save(stream, E.SaveFormat.Xlsx); using (stream) { stream.Position = 0; byte[] buffer = new byte[0x1000]; while (true) { int count = stream.Read(buffer, 0, 0x1000); if (count == 0) { break; } outputStream.Write(buffer, 0, count); } } }
private byte[] GetMultipartFormData(IDictionary <string, object> postParameters, string boundary) { System.Text.Encoding encoding = System.Text.Encoding.ASCII; Stream formDataStream = new System.IO.MemoryStream(); bool needsCLRF = false; foreach (var param in postParameters) { if (needsCLRF) { formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n")); } needsCLRF = true; if (param.Value is FileParameter) { FileParameter fileToUpload = (FileParameter)param.Value; string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\";" + "filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n", boundary, param.Key, fileToUpload.FileName ?? param.Key, fileToUpload.ContentType ?? "application/octet-stream"); formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header)); formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length); } else { string postData = string.Format("--{0}\r\nContent-Disposition: form-data;" + "name=\"{1}\"\r\n\r\n{2}", boundary, param.Key, param.Value); formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData)); } } string footer = "\r\n--" + boundary + "--\r\n"; formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer)); formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Close(); return(formData); }
private static byte[] GetMultipartFormData(Dictionary <string, object> postParameters, string boundary) { Stream formDataStream = new System.IO.MemoryStream(); foreach (var param in postParameters) { if (param.Value is MultiPartFileParameter) { MultiPartFileParameter fileToUpload = (MultiPartFileParameter)param.Value; // Add just the first part of this param, since we will write the file data directly to the Stream string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n", boundary, param.Key, fileToUpload.FileName ?? param.Key, fileToUpload.ContentType ?? "application/octet-stream"); formDataStream.Write(encoding.GetBytes(header), 0, header.Length); // Write the file data directly to the Stream, rather than serializing it to a string. formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length); // Thanks to feedback from commenters, add a CRLF to allow multiple files to be uploaded formDataStream.Write(encoding.GetBytes("\r\n"), 0, 2); } else { string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", boundary, param.Key, param.Value); formDataStream.Write(encoding.GetBytes(postData), 0, postData.Length); } } // Add the end of the request string footer = "\r\n--" + boundary + "--\r\n"; formDataStream.Write(encoding.GetBytes(footer), 0, footer.Length); // Dump the Stream into a byte[] formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Close(); return(formData); }
internal void Write(System.IO.Stream s) { byte[] bytes = new byte[4096]; int n; // write the header: WriteHeader(s, bytes); // write the actual file data: _UnderlyingMemoryStream.Position = 0; while ((n = _UnderlyingMemoryStream.Read(bytes, 0, bytes.Length)) != 0) { s.Write(bytes, 0, n); } //_CompressedStream.Close(); //_CompressedStream= null; _UnderlyingMemoryStream.Close(); _UnderlyingMemoryStream = null; }
public static bool Save(this object data, string filepath) { if (data != null) { try { var ms = new System.IO.MemoryStream(); var formatter = new BinaryFormatter(); formatter.Serialize(ms, data); ms.Position = 0; byte[] datas = new byte[ms.Length]; ms.Read(datas, 0, datas.Length); ms.Close(); File.WriteAllBytes(filepath, datas); return(true); } catch { } } return(false); }
public string DecryptString(byte[] bytes) { //var bytes = Convert.FromBase64String(encryptedValue); var aes = new AesCryptoServiceProvider(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.KeySize = 256; using (var memStream = new System.IO.MemoryStream(bytes)) { var iv = new byte[16]; memStream.Read(iv, 0, 16); using (var cryptStream = new CryptoStream(memStream, aes.CreateDecryptor(this.key, iv), CryptoStreamMode.Read)) { using (var reader = new System.IO.StreamReader(cryptStream)) { return(reader.ReadToEnd()); } } } }
private static byte[] ConverterFotoParaByteArray(Image imagem) { using (var stream = new System.IO.MemoryStream()) { Bitmap b = new Bitmap(imagem); try { Bitmap c = b.Clone(new Rectangle(0, 0, b.Width, b.Height), PixelFormat.Format32bppRgb); c.Save(stream, ImageFormat.Jpeg); //imagem.Save(stream, ImageFormat.Png); stream.Seek(0, System.IO.SeekOrigin.Begin); byte[] bArray = new byte[stream.Length]; stream.Read(bArray, 0, System.Convert.ToInt32(stream.Length)); return(bArray); } finally { b.Dispose(); } } }
public byte[] ObjectTobyteArray(object obj, bool bCompress) { using (System.IO.Stream streamWrite = new System.IO.MemoryStream()) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryWrite = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); //Serialize the object binaryWrite.Serialize(streamWrite, obj); streamWrite.Seek(0, System.IO.SeekOrigin.Begin); //Serialized object into byte array byte[] data = new byte[streamWrite.Length]; streamWrite.Read(data, 0, (int)streamWrite.Length); if (!bCompress) { return(data); } using (System.IO.Stream zipStream = new System.IO.MemoryStream()) { using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream( zipStream, System.IO.Compression.CompressionMode.Compress, true)) { //Compress the data zip.Write(data, 0, data.Length); } zipStream.Seek(0, System.IO.SeekOrigin.Begin); byte[] compressed = new byte[zipStream.Length + 4];//Extra 4 bytes for size //Read the compressed data to array zipStream.Read(compressed, 4, compressed.Length - 4); //Save the uncompressed data length in first 4 bytes, used for decompression System.Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, compressed, 0, 4); return(compressed); } } }
//把manifest对象转为字节流 public static byte[] GetBytesFromManifest(ManifestInfo manifestInfo) { try { System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms); bw.Write(manifestInfo.version); bw.Write(manifestInfo.assetDic.Count); foreach (var kv in manifestInfo.assetDic) { bw.Write(kv.Value.SubPath); bw.Write(kv.Value.Length); bw.Write(kv.Value.CreateDate); bw.Write(kv.Value.md5); bw.Write(kv.Value.Suffix); bw.Write(kv.Value.FilePathList.Count); for (int i = 0, count = kv.Value.FilePathList.Count; i < count; i++) { bw.Write(kv.Value.FilePathList[i]); } } ms.Position = 0; int len = (int)ms.Length;//manifest文件不能超2GB byte[] bytes = new byte[len]; ms.Read(bytes, 0, len); bw.Close(); ms.Close(); ms.Dispose(); //return bytes.Compress(); return(bytes); } catch (Exception e) { Debugger.LogError("GetBytesFromManifest:" + e); } finally { } return(null); }
private static Action <Stream> GenerateRequestStreamWriterForFile(Dictionary <string, string> param, string filename, string boundary) { Stream memStream = new System.IO.MemoryStream(); byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; foreach (KeyValuePair <string, string> s in param) { string formitem = string.Format(formdataTemplate, s.Key, s.Value); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); memStream.Write(formitembytes, 0, formitembytes.Length); } memStream.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"_file\"; filename=\"_files\"\r\n Content-Type: application/octet-stream\r\n\r\n"; string header = string.Format(headerTemplate, "file1", filename); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); ReadFileIntoMemoryStream(memStream, filename); memStream.Write(boundarybytes, 0, boundarybytes.Length); #warning Do I need to set this ContentLength header myself? //req.ContentLength = memStream.Length; Action <Stream> requestStreamWriter = (requestStream) => { memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); }; return(requestStreamWriter); }
private byte[] GenerateThumbnail(System.Drawing.Image image, string size) { // create the actual thumbnail image //System.Drawing.Image thumbnailImage = image.GetThumbnailImage(64, 64, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero); System.Drawing.Image thumbnailImage; //Modif. para tolerar distintos tamaños de imagen. if (size == null) { thumbnailImage = image; //thumbnailImage = image.GetThumbnailImage(64, 64, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero); } else { if (image.Size.Width > int.Parse(size.Split('x')[0]) || image.Size.Height > int.Parse(size.Split('x')[1])) { thumbnailImage = ResizeImage(image, int.Parse(size.Split('x')[0]), int.Parse(size.Split('x')[1])); } // thumbnailImage = image.GetThumbnailImage(int.Parse(size.Split('x')[0]), int.Parse(size.Split('x')[1]), new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero); else { thumbnailImage = image; } } // make a memory stream to work with the image bytes System.IO.MemoryStream imageStream = new System.IO.MemoryStream(); // put the image into the memory stream thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Png); // make byte array the same size as the image byte[] imageContent = new Byte[imageStream.Length]; // rewind the memory stream imageStream.Position = 0; // load the byte array with the image imageStream.Read(imageContent, 0, (int)imageStream.Length); return(imageContent); }
/// <summary> /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file) /// </summary> /// <param name="ds">DataSet containing the data to be written to the Excel.</param> /// <param name="filename">The filename (without a path) to call the new Excel file.</param> /// <param name="Response">HttpResponse of the current page.</param> /// <returns>Either a MemoryStream, or NULL if something goes wrong.</returns> public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response) { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(); using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true)) { WriteExcelFile(ds, document, filename); } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; // NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have // manually added System.Web to this project's References. Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/vnd.ms-excel"; byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); Response.End(); return(true); } catch (Exception ex) { System.IO.File.WriteAllText(@"D:\DSPBlackRock\errormessage.txt", "Failed, exception thrown: " + ex.Message); return(false); } }
public byte[][] GetLogsData() { int log_count = ffxiv.ReadInt32(LogCountPtr);// System.Diagnostics.Debug.WriteLine("cnt:"+ log_count.ToString("D4")); int log_countr = log_count % 1000; if (log_countr == 0) { log_countr = 1000; } int log_index = ffxiv.ReadInt32(LogIndexPtr); int log_ent = ffxiv.ReadInt32(LogEntPtr); int log_current = ffxiv.ReadInt32(LogCurrentPtr); byte[] indexdata = ffxiv.ReadBytes(log_index, 1000 * 0x04); System.IO.MemoryStream ms = new System.IO.MemoryStream(indexdata); System.IO.BinaryReader br = new System.IO.BinaryReader(ms); ms.Position = (log_countr - 1) * 0x04; int logdata_size = br.ReadInt32(); ms.Position = 0; byte[] logdata = ffxiv.ReadBytes(log_ent, logdata_size); System.IO.MemoryStream ms2 = new System.IO.MemoryStream(logdata); int last = 0; List <byte[]> res = new List <byte[]>(); for (int i = 0; i < log_countr; i++) { int index = br.ReadInt32(); byte[] dat = new byte[index - last]; ms2.Read(dat, 0, index - last); res.Add(dat); last = index; } return(res.ToArray()); }
static public byte[] Encode(byte[] Data, System.Security.Cryptography.ICryptoTransform Encoder) { byte[] Outer; int rdlen = 0; using (System.IO.MemoryStream memStream = new System.IO.MemoryStream()) { byte[] bin = new byte[128]; int len; System.IO.MemoryStream InputStr = new System.IO.MemoryStream(); InputStr.Write(Data, 0, Data.Length); InputStr.Position = 0; System.Security.Cryptography.CryptoStream CryptStream = new System.Security.Cryptography.CryptoStream(memStream, Encoder, System.Security.Cryptography.CryptoStreamMode.Write); while (rdlen < Data.Length) { len = InputStr.Read(bin, 0, 128); CryptStream.Write(bin, 0, len); rdlen = rdlen + len; } CryptStream.FlushFinalBlock(); Outer = memStream.ToArray(); CryptStream.Close(); } return(Outer); }
private static byte[] GetMultipartFormData(Dictionary <string, object> postParameters, string boundary) { Stream formDataStream = new System.IO.MemoryStream(); bool needsCLRF = false; Encoding encoding = Encoding.UTF8; foreach (var param in postParameters) { // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. // Skip it on the first parameter, add it to subsequent parameters. if (needsCLRF) { formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n")); } needsCLRF = true; //string postData = string.Format("multipart/form-data;{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", // boundary, // param.Key, // param.Value); string postData = "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"__RequestVerificationToken\"\r\n\r\nGJKWN0U0ndGyC5fAKEdhhosJMhpjLmtfvNIieri7YR8Q37_BUn-lmEg6ucZPrWPefAcxG1-5TPMtYPZsa6fFIigJBBICLcfUlMrufrpIV6U1\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"; formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData)); } // Add the end of the request. Start with a newline string footer = "\r\n--" + boundary + "--\r\n"; formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer)); // Dump the Stream into a byte[] formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Close(); return(formData); }
public string IconToBase64(Icon icon) { string str = string.Empty; string result; if (icon == null) { result = str; } else { Bitmap bitmap = null; System.IO.MemoryStream ms = null; try { ms = new System.IO.MemoryStream(); bitmap = icon.ToBitmap(); bitmap.Save(ms, ImageFormat.Png); byte[] array = new byte[ms.Length]; ms.Position = 0L; ms.Read(array, 0, (int)ms.Length); str = System.Convert.ToBase64String(array); } finally { if (ms != null) { ms.Dispose(); } if (bitmap != null) { bitmap.Dispose(); } } result = str; } return(result); }
public string SendHttpFile(string url, Dictionary <string, Stream> files) { string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); this.ContentType = "multipart/form-data; charset=" + this.EncoderRequest.BodyName + "; boundary=" + boundary; string headerTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; Stream memStream = new System.IO.MemoryStream(); foreach (KeyValuePair <string, Stream> file in files) { Stream fileStream = file.Value; String fileName = file.Key; String fileType = GetContentTypeForFile(file.Key); MemoryStream ms = new MemoryStream(); StreamCopyTo(fileStream, ms); byte[] rez = ms.ToArray(); string header = string.Format(headerTemplate, "userfile", fileName, fileType); byte[] headerbytes = this.EncoderRequest.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); memStream.Write(rez, 0, rez.Length); } byte[] boundarybytes = this.EncoderRequest.GetBytes("\r\n--" + boundary); memStream.Write(boundarybytes, 0, boundarybytes.Length); memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); return(SendPost(url, tempBuffer)); }
public string GetQRCode(string strCodetext) { string strImage = string.Empty; if (!string.IsNullOrEmpty(strCodetext)) { QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; qrCodeEncoder.QRCodeScale = 4; qrCodeEncoder.QRCodeVersion = 8; qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H; Image qrImage = qrCodeEncoder.Encode(strCodetext); System.IO.MemoryStream MStream = new System.IO.MemoryStream(); qrImage.Save(MStream, System.Drawing.Imaging.ImageFormat.Png); byte[] arr = new byte[MStream.Length]; MStream.Position = 0; MStream.Read(arr, 0, (int)MStream.Length); MStream.Close(); MStream.Dispose(); strImage = Convert.ToBase64String(arr); } return(strImage); }
public JsonResult UploadImage() { try { HttpPostedFileBase file = Request.Files[0] as HttpPostedFileBase; int fileSizeInBytes = file.ContentLength; MemoryStream target = new MemoryStream(); file.InputStream.CopyTo(target); Byte[] bytes = target.ToArray(); System.IO.Stream stream = new System.IO.MemoryStream(); Int64 data64 = stream.Read(bytes, 0, (Int32)stream.Length); stream.Close(); String img64 = Convert.ToBase64String(bytes, 0, bytes.Length); return(Json(img64)); } catch (Exception ex) { return(Json("error")); } }
private static byte[] GetMultipartFormData(Dictionary <string, object> postParameters, string boundary) { string realBoundary = "--" + boundary; Stream formDataStream = new System.IO.MemoryStream(); formDataStream.Write(System.Text.Encoding.UTF8.GetBytes(realBoundary), 0, realBoundary.Length); foreach (var param in postParameters) { if (param.Value is byte[]) { /*byte[] fileData = ImageLib.CreateTumbnailImageFromByteArray(param.Value as byte[], Properties.Settings.Default.ImageWidth); * * // Add just the first part of this param, since we will write the file data directly to the Stream * string header = string.Format("\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{0}.png\"; \r\nContent-Type: application/octet-stream\r\n\r\n", param.Key); * formDataStream.Write(System.Text.Encoding.UTF8.GetBytes(header), 0, header.Length); * formDataStream.Write(fileData, 0, fileData.Length); * * formDataStream.Write(encoding.GetBytes("\r\n"), 0, "\r\n".Length); * formDataStream.Write(System.Text.Encoding.UTF8.GetBytes(realBoundary), 0, realBoundary.Length);*/ } else { string postData = string.Format("\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", param.Key, param.Value); byte[] encodedData = encoding.GetBytes(postData); formDataStream.Write(encodedData, 0, encodedData.Length); formDataStream.Write(System.Text.Encoding.UTF8.GetBytes(realBoundary), 0, realBoundary.Length); } } // Dump the Stream into a byte[] formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Close(); return(formData); }