/// <summary> /// 将一个对象序列化为字节数组 /// </summary> /// <param name="data">要序列化的对象</param> /// <returns>序列化好的字节数组</returns> public static byte[] ToBytes(Object data) { MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, data); return ms.ToArray(); }
public Task Invoke(IDictionary<string, object> environment) { if (!environment.Get<string>(OwinConstants.RequestMethodKey).EqualsIgnoreCase("GET")) { return _inner(environment); } var originalOutput = environment.Get<Stream>(OwinConstants.ResponseBodyKey); var recordedStream = new MemoryStream(); environment.Set(OwinConstants.ResponseBodyKey, recordedStream); return _inner(environment).ContinueWith(t => { recordedStream.Position = 0; environment[OwinConstants.ResponseBodyKey] = originalOutput; var response = new OwinHttpResponse(environment); if (IsGetHtmlRequest(environment) && response.StatusCode < 500) { injectContent(environment, recordedStream, response); } else { response.StreamContents(recordedStream); } }); }
public Image<Gray, byte> byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image i = Image.FromStream(ms); Bitmap b = new Bitmap(i); return new Image<Gray, byte>(b); }
public void TestIncompleteRewind() { MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); bw.Write(1); bw.Write(2); bw.Write(3); bw.Write(4); bw.Write(5); bw.Write(6); bw.Write(7); bw.Flush(); ms.Position = 0; RewindableStream stream = new RewindableStream(ms); stream.StartRecording(); BinaryReader br = new BinaryReader(stream); Assert.AreEqual(br.ReadInt32(), 1); Assert.AreEqual(br.ReadInt32(), 2); Assert.AreEqual(br.ReadInt32(), 3); Assert.AreEqual(br.ReadInt32(), 4); stream.Rewind(true); Assert.AreEqual(br.ReadInt32(), 1); Assert.AreEqual(br.ReadInt32(), 2); stream.StartRecording(); Assert.AreEqual(br.ReadInt32(), 3); Assert.AreEqual(br.ReadInt32(), 4); Assert.AreEqual(br.ReadInt32(), 5); stream.Rewind(true); Assert.AreEqual(br.ReadInt32(), 3); Assert.AreEqual(br.ReadInt32(), 4); Assert.AreEqual(br.ReadInt32(), 5); Assert.AreEqual(br.ReadInt32(), 6); Assert.AreEqual(br.ReadInt32(), 7); }
async Task<bool> UploadDB() { try { ServiceReference1.IService1 s = new ServiceReference1.Service1Client(); Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("SQLITEV2.sqlite"); byte[] result; using (Stream stream = await sampleFile.OpenStreamForReadAsync()) { using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); result = memoryStream.ToArray(); } } await s.UploadFileAsync(result); return true; } catch (Exception) { return false; throw; } }
public static string Decrypt(string sourceData) { // set key and initialization vector values byte[] key = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] iv = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; try { // convert data to byte array byte[] encryptedDataBytes = Convert.FromBase64String(sourceData); // get source memory stream and fill it MemoryStream tempStream = new MemoryStream(encryptedDataBytes, 0, encryptedDataBytes.Length); // get decryptor and decryption stream DESCryptoServiceProvider decryptor = new DESCryptoServiceProvider(); CryptoStream decryptionStream = new CryptoStream(tempStream, decryptor.CreateDecryptor(key, iv), CryptoStreamMode.Read); // decrypt data StreamReader allDataReader = new StreamReader(decryptionStream); return allDataReader.ReadToEnd(); } catch { throw new StringEncryptorException( "Unable to decrypt data."); } }
/// <summary> /// Save the current <see cref="SessionState"/>. Any <see cref="Frame"/> instances /// registered with <see cref="RegisterFrame"/> will also preserve their current /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity /// to save its state. /// </summary> /// <returns>An asynchronous task that reflects when session state has been saved.</returns> public static async Task SaveAsync() { try { // Save the navigation state for all registered frames foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame)) { SaveFrameNavigationState(frame); } } // Serialize the session state synchronously to avoid asynchronous access to shared // state MemoryStream sessionData = new MemoryStream(); DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes); serializer.WriteObject(sessionData, _sessionState); // Get an output stream for the SessionState file and write the state asynchronously StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting); using (Stream fileStream = await file.OpenStreamForWriteAsync()) { sessionData.Seek(0, SeekOrigin.Begin); await sessionData.CopyToAsync(fileStream); } } catch (Exception e) { throw new SuspensionManagerException(e); } }
public Dictionary<string, object> Read(byte [] data, string rsaPrivKey, Dictionary<string, Type> objTypeMap, Func<byte[], byte[]> xmlFilter = null) { using (var ms = new MemoryStream(data)) { return DecryptFileList(Util.Compression.UnZip(ms), rsaPrivKey, objTypeMap, xmlFilter); } }
public static string Encode(string str, string key) { DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8)); provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8)); byte[] bytes = Encoding.UTF8.GetBytes(str); MemoryStream stream = new MemoryStream(); CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write); stream2.Write(bytes, 0, bytes.Length); stream2.FlushFinalBlock(); StringBuilder builder = new StringBuilder(); foreach (byte num in stream.ToArray()) { builder.AppendFormat("{0:X2}", num); } stream.Close(); return builder.ToString(); }
internal static byte[] getMAIN(byte[] ramsav) { byte[] main; uint[] offsets; uint[] lens; uint[] magics; uint[] skips; uint[] instances; uint val = BitConverter.ToUInt32(ramsav, 0); uint spos = 0; if (ramsav.Length == 0x80000) // ORAS { offsets = new uint[] { 0x00005400, 0x00005800, 0x00006400, 0x00006600, 0x00006800, 0x00006A00, 0x00006C00, 0x00006E00, 0x00007000, 0x00007200, 0x00007400, 0x00009600, 0x00009800, 0x00009E00, 0x0000A400, 0x0000F400, 0x00014400, 0x00019400, 0x00019600, 0x00019E00, 0x0001A400, 0x0001B600, 0x0001BE00, 0x0001C000, 0x0001C200, 0x0001C800, 0x0001CA00, 0x0001CE00, 0x0001D600, 0x0001D800, 0x0001DA00, 0x0001DC00, 0x0001DE00, 0x0001E000, 0x0001E800, 0x0001EE00, 0x0001F200, 0x00020E00, 0x00021000, 0x00021400, 0x00021800, 0x00022000, 0x00023C00, 0x00024000, 0x00024800, 0x00024C00, 0x00025600, 0x00025A00, 0x00026200, 0x00027000, 0x00027200, 0x00027400, 0x00028200, 0x00028A00, 0x00028E00, 0x00030A00, 0x00038400, 0x0006D000, 0x0007B200 }; lens = new uint[] { 0x000002C8, 0x00000B90, 0x0000002C, 0x00000038, 0x00000150, 0x00000004, 0x00000008, 0x000001C0, 0x000000BE, 0x00000024, 0x00002100, 0x00000130, 0x00000440, 0x00000574, 0x00004E28, 0x00004E28, 0x00004E28, 0x00000170, 0x0000061C, 0x00000504, 0x000011CC, 0x00000644, 0x00000104, 0x00000004, 0x00000420, 0x00000064, 0x000003F0, 0x0000070C, 0x00000180, 0x00000004, 0x0000000C, 0x00000048, 0x00000054, 0x00000644, 0x000005C8, 0x000002F8, 0x00001B40, 0x000001F4, 0x000003E0, 0x00000216, 0x00000640, 0x00001A90, 0x00000400, 0x00000618, 0x0000025C, 0x00000834, 0x00000318, 0x000007D0, 0x00000C48, 0x00000078, 0x00000200, 0x00000C84, 0x00000628, 0x00000400, 0x00007AD0, 0x000078B0, 0x00034AD0, 0x0000E058, 0x00000200 }; skips = new uint[] { 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000004, 0x00000004, 0x00000004, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000004, 0x00000000, 0x00000004, 0x00000004 }; magics = new uint[] { 0x005E0BB8, 0x005E09C4, 0x005E0904, 0x005E0AA4, 0x005E0BF8, 0x005E05CC, 0x005E0B04, 0x005E0A44, 0x005E0AC4, 0x005E05AC, 0x005E064C, 0x005E0944, 0x005E0924, 0x005E0B78, 0x005E0884, 0x005E0884, 0x005E0884, 0x005E0AE4, 0x005E068C, 0x005DF40C, 0x005E0C18, 0x005E072C, 0x005E05EC, 0x005E0964, 0x005E06AC, 0x005E06EC, 0x005E062C, 0x005E0BD8, 0x005E0A64, 0x005E0B98, 0x005E07CC, 0x005E0A24, 0x005E058C, 0x005E04EC, 0x005E056C, 0x005E082C, 0x005E0984, 0x005E070C, 0x005E0B58, 0x005E054C, 0x005E050C, 0x005E080C, 0x005E076C, 0x005E07AC, 0x005E09E4, 0x005E08A4, 0x005E078C, 0x005E074C, 0x005E060C, 0x005E06CC, UNKNOWNVAL, 0x005E0864, 0x005E07EC, 0x005E0A04, 0x005E052C, 0x005E08C4, 0x005E04CC, 0x005E066C, 0x005E09A4 }; instances = new uint[] { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }; } else { offsets = new uint[] { 0x00005400, 0x00005800, 0x00006400, 0x00006600, 0x00006800, 0x00006A00, 0x00006C00, 0x00006E00, 0x00007000, 0x00007200, 0x00007400, 0x00009600, 0x00009800, 0x00009E00, 0x0000A400, 0x0000F400, 0x00014400, 0x00019400, 0x00019600, 0x00019E00, 0x0001A400, 0x0001AC00, 0x0001B400, 0x0001B600, 0x0001B800, 0x0001BE00, 0x0001C000, 0x0001C400, 0x0001CC00, 0x0001CE00, 0x0001D000, 0x0001D200, 0x0001D400, 0x0001D600, 0x0001DE00, 0x0001E400, 0x0001E800, 0x00020400, 0x00020600, 0x00020800, 0x00020C00, 0x00021000, 0x00022C00, 0x00023000, 0x00023800, 0x00023C00, 0x00024600, 0x00024A00, 0x00025200, 0x00026000, 0x00026200, 0x00026400, 0x00027200, 0x00027A00, 0x0005C600, 0x0006A800 }; lens = new uint[] { 0x000002C8, 0x00000B88, 0x0000002C, 0x00000038, 0x00000150, 0x00000004, 0x00000008, 0x000001C0, 0x000000BE, 0x00000024, 0x00002100, 0x00000140, 0x00000440, 0x00000574, 0x00004E28, 0x00004E28, 0x00004E28, 0x00000170, 0x0000061C, 0x00000504, 0x000006A0, 0x00000644, 0x00000104, 0x00000004, 0x00000420, 0x00000064, 0x000003F0, 0x0000070C, 0x00000180, 0x00000004, 0x0000000C, 0x00000048, 0x00000054, 0x00000644, 0x000005C8, 0x000002F8, 0x00001B40, 0x000001F4, 0x000001F0, 0x00000216, 0x00000390, 0x00001A90, 0x00000308, 0x00000618, 0x0000025C, 0x00000834, 0x00000318, 0x000007D0, 0x00000C48, 0x00000078, 0x00000200, 0x00000C84, 0x00000628, 0x00034AD0, 0x0000E058, 0x00000200 }; skips = new uint[] { 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000004, 0x00000004, 0x00000004, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000004 }; magics = new uint[] { 0x0059AE94, 0x0059ACC0, 0x0059AC00, 0x0059AD80, 0x0059AED4, 0x0059A8E8, 0x0059ADE0, 0x0059AD20, 0x0059ADA0, 0x0059A8C8, 0x0059A968, 0x0059AC40, 0x0059AC20, 0x0059AE54, 0x0059ABA0, 0x0059ABA0, 0x0059ABA0, 0x0059ADC0, 0x0059A9A8, 0x00599734, 0x0059AEF4, 0x0059AA48, 0x0059A908, 0x0059AC60, 0x0059A9C8, 0x0059AA08, 0x0059A948, 0x0059AEB4, 0x0059AD40, 0x0059AE74, 0x0059AAE8, 0x0059AD00, 0x0059A8A8, 0x0059A800, 0x0059A888, 0x0059AB70, 0x0059AC80, 0x0059AA28, 0x0059AE34, 0x0059A868, 0x0059A820, 0x0059AB28, 0x0059AA88, 0x0059AAC8, 0x0059ACE0, 0x0059ABC0, 0x0059AAA8, 0x0059AA68, 0x0059A928, 0x0059A9E8, 0x0059AD60, 0x0059AB80, 0x0059AB08, 0x0059A7E0, 0x0059A988, 0x0059ACA0 }; instances = new uint[] { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }; switch (val) { case 0x0059E418: magics = new uint[] { 0x0059E418, 0x0059E244, 0x0059E184, 0x0059E304, 0x0059E458, 0x0059DE6C, 0x0059E364, 0x0059E2A4, 0x0059E324, 0x0059DE4C, 0x0059DEEC, 0x0059E1C4, 0x0059E1A4, 0x0059E3D8, 0x0059E124, 0x0059E124, 0x0059E124, 0x0059E344, 0x0059DF2C, 0x0059CCB8, 0x0059E478, 0x0059DFCC, 0x0059DE8C, 0x0059E1E4, 0x0059DF4C, 0x0059DF8C, 0x0059DECC, 0x0059E438, 0x0059E2C4, 0x0059E3F8, 0x0059E06C, 0x0059E284, 0x0059DE2C, 0x0059DD84, 0x0059DE0C, 0x0059E0CC, 0x0059E204, 0x0059DFAC, 0x0059E3B8, 0x0059DDEC, 0x0059DDA4, 0x0059E0AC, 0x0059E00C, 0x0059E04C, 0x0059E264, 0x0059E144, 0x0059E02C, 0x0059DFEC, 0x0059DEAC, 0x0059DF6C, 0x0059E2E4, 0x0059E104, 0x0059E08C, 0x0059DD64, 0x0059DF0C, 0x0059E224 }; break; case 0x0059E408: magics = new uint[] { 0x0059E408, 0x0059E234, 0x0059E174, 0x0059E2F4, 0x0059E448, 0x0059DE5C, 0x0059E354, 0x0059E294, 0x0059E314, 0x0059DE3C, 0x0059DEDC, 0x0059E1B4, 0x0059E194, 0x0059E3C8, 0x0059E114, 0x0059E114, 0x0059E114, 0x0059E334, 0x0059DF1C, 0x0059CCA8, 0x0059E468, 0x0059DFBC, 0x0059DE7C, 0x0059E1D4, 0x0059DF3C, 0x0059DF7C, 0x0059DEBC, 0x0059E428, 0x0059E2B4, 0x0059E3E8, 0x0059E05C, 0x0059E274, 0x0059DE1C, 0x0059DD74, 0x0059DDFC, 0x0059E0BC, 0x0059E1F4, 0x0059DF9C, 0x0059E3A8, 0x0059DDDC, 0x0059DD94, 0x0059E09C, 0x0059DFFC, 0x0059E03C, 0x0059E254, 0x0059E134, 0x0059E01C, 0x0059DFDC, 0x0059DE9C, 0x0059DF5C, 0x0059E2D4, 0x0059E0F4, 0x0059E07C, 0x0059DD54, 0x0059DEFC, 0x0059E214 }; break; case 0x0059BEC4: magics = new uint[] { 0x0059BEC4, 0x0059BCF0, 0x0059BC30, 0x0059BDB0, 0x0059BF04, 0x0059B918, 0x0059BE10, 0x0059BD50, 0x0059BDD0, 0x0059B8F8, 0x0059B998, 0x0059BC70, 0x0059BC50, 0x0059BE84, 0x0059BBD0, 0x0059BBD0, 0x0059BBD0, 0x0059BDF0, 0x0059B9D8, 0x0059A764, 0x0059BF24, 0x0059BA78, 0x0059B938, 0x0059BC90, 0x0059B9F8, 0x0059BA38, 0x0059B978, 0x0059BEE4, 0x0059BD70, 0x0059BEA4, 0x0059BB18, 0x0059BD30, 0x0059B8D8, 0x0059B830, 0x0059B8B8, 0x0059BBA0, 0x0059BCB0, 0x0059BA58, 0x0059BE64, 0x0059B898, 0x0059B850, 0x0059BB58, 0x0059BAB8, 0x0059BAF8, 0x0059BD10, 0x0059BBF0, 0x0059BAD8, 0x0059BA98, 0x0059B958, 0x0059BA18, 0x0059BD90, 0x0059BBB0, 0x0059BB38, 0x0059B810, 0x0059B9B8, 0x0059BCD0 }; break; } } using (MemoryStream ms = new MemoryStream()) { for (int i = 0; i < lens.Length; i++) { int ofs = FindIndex(ramsav, magics[i], instances[i], spos); ms.Seek(offsets[i] - 0x5400, SeekOrigin.Begin); spos += lens[i]; if (ofs > 0) { new MemoryStream(ramsav.Skip(ofs + (int)skips[i]).Take((int)lens[i]).ToArray()).CopyTo(ms); spos += 4; } else new MemoryStream(new byte[(int)lens[i]]).CopyTo(ms); } if (ms.Length % 0x200 != 0) new MemoryStream(new byte[0x200 - ms.Length % 0x200]).CopyTo(ms); // Pad out to 0x200 main = ms.ToArray(); } return main; }
public void AllFieldsEmptyTest() { using( var stream = new MemoryStream() ) using( var reader = new StreamReader( stream ) ) using( var writer = new StreamWriter( stream ) ) using( var parser = new CsvParser( reader ) ) { writer.WriteLine( ";;;;" ); writer.WriteLine( ";;;;" ); writer.Flush(); stream.Position = 0; parser.Configuration.Delimiter = ";;"; parser.Configuration.HasHeaderRecord = false; var row = parser.Read(); Assert.IsNotNull( row ); Assert.AreEqual( 3, row.Length ); Assert.AreEqual( "", row[0] ); Assert.AreEqual( "", row[1] ); Assert.AreEqual( "", row[2] ); row = parser.Read(); Assert.IsNotNull( row ); Assert.AreEqual( 3, row.Length ); Assert.AreEqual( "", row[0] ); Assert.AreEqual( "", row[1] ); Assert.AreEqual( "", row[2] ); row = parser.Read(); Assert.IsNull( row ); } }
private byte[] GetBytesFromString(string value) { var bytes = Encoding.UTF8.GetBytes(value); var outputMemStream = new MemoryStream(); if (bytes.Length > 7950) { using (var memStream = new MemoryStream(bytes, false)) { using (outputMemStream) { memStream.Seek(0, SeekOrigin.Begin); using (var zip = new GZipStream(outputMemStream, CompressionLevel.Fastest)) { memStream.CopyTo(zip); } } } return outputMemStream.ToArray(); } else { return bytes; } }
public static MessageBase Deserialize(byte[] data) { using (MemoryStream stream = new MemoryStream(data)) using (BinaryReader reader = new BinaryReader(stream)) { // Ignore initial key reader.ReadByte(); byte payloadLength = reader.ReadByte(); byte packageSequence = reader.ReadByte(); byte systemId = reader.ReadByte(); byte componentId = reader.ReadByte(); byte messageId = reader.ReadByte(); // Create instance based on message id MessageBase message = null; Type messageType; if (_messageTypes.TryGetValue(messageId, out messageType)) { message = (MessageBase)Activator.CreateInstance(messageType); message._fields = new object[message._fieldTypes.Length]; for (int i = 0; i < message._fieldTypes.Length; ++i) { message.ReadField(reader, i); } // TODO: Verify CRC byte LSBCRC = reader.ReadByte(); byte MSBCRC = reader.ReadByte(); } return message; } }
/// <summary> /// 加密方法 /// </summary> /// <param name="pToEncrypt">需要加密字符串</param> /// <param name="sKey">密钥</param> /// <returns>加密后的字符串</returns> public static string Encrypt(string pToEncrypt, string sKey) { try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); //把字符串放到byte数组中 //原来使用的UTF8编码,我改成Unicode编码了,不行 byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt); //建立加密对象的密钥和偏移量 //使得输入密码必须输入英文文本 des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } ret.ToString(); return ret.ToString(); } catch (Exception ex) { } return ""; }
/// <summary> /// 解密方法 /// </summary> /// <param name="pToDecrypt">需要解密的字符串</param> /// <param name="sKey">密匙</param> /// <returns>解密后的字符串</returns> public static string Decrypt(string pToDecrypt, string sKey) { try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[pToDecrypt.Length / 2]; for (int x = 0; x < pToDecrypt.Length / 2; x++) { int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } //建立加密对象的密钥和偏移量,此值重要,不能修改 des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象 StringBuilder ret = new StringBuilder(); return System.Text.Encoding.Default.GetString(ms.ToArray()); } catch (Exception ex) { } return ""; }
/// <summary> /// Den aktuellen <see cref="SessionState"/> speichern. Alle <see cref="Frame"/>-Instanzen, /// die bei <see cref="RegisterFrame"/> registriert wurden, behalten ebenfalls ihren aktuellen /// Navigationsstapel bei, wodurch deren aktive <see cref="Page"/> eine Gelegenheit /// zum Speichern des zugehörigen Zustands erhält. /// </summary> /// <returns>Eine asynchrone Aufgabe, die das Speichern des Sitzungszustands wiedergibt.</returns> public static async Task SaveAsync() { try { // Navigationszustand für alle registrierten Rahmen speichern foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame)) { SaveFrameNavigationState(frame); } } // Sitzungszustand synchron serialisieren, um einen asynchronen Zugriff auf den freigegebenen // Zustand MemoryStream sessionData = new MemoryStream(); DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes); serializer.WriteObject(sessionData, _sessionState); // Einen Ausgabedatenstrom für die SessionState-Datei abrufen und den Zustand asynchron schreiben StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting); using (Stream fileStream = await file.OpenStreamForWriteAsync()) { sessionData.Seek(0, SeekOrigin.Begin); await sessionData.CopyToAsync(fileStream); } } catch (Exception e) { throw new SuspensionManagerException(e); } }
public async Task FileReadStreamBasicTestAsync() { byte[] buffer = GetRandomBuffer(5 * 1024 * 1024); CloudFileShare share = GetRandomShareReference(); try { await share.CreateAsync(); CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1"); using (MemoryStream wholeFile = new MemoryStream(buffer)) { await file.UploadFromStreamAsync(wholeFile.AsInputStream()); } using (MemoryStream wholeFile = new MemoryStream(buffer)) { IRandomAccessStreamWithContentType readStream = await file.OpenReadAsync(); using (Stream fileStream = readStream.AsStreamForRead()) { TestHelper.AssertStreamsAreEqual(wholeFile, fileStream); } } } finally { share.DeleteIfExistsAsync().AsTask().Wait(); } }
public byte[] ToBytes() { var memoryStream = new MemoryStream(); const bool rsv1 = false; const bool rsv2 = false; const bool rsv3 = false; var bt = (IsFinal ? 1 : 0) * 0x80; bt += (rsv1 ? 0x40 : 0x0); bt += (rsv2 ? 0x20 : 0x0); bt += (rsv3 ? 0x10 : 0x0); bt += (byte)FrameType; memoryStream.WriteByte((byte)bt); byte[] payloadLengthBytes = GetLengthBytes(); memoryStream.Write(payloadLengthBytes, 0, payloadLengthBytes.Length); byte[] payload = Payload; if (IsMasked) { byte[] keyBytes = BitConverter.GetBytes(MaskKey); if (BitConverter.IsLittleEndian) Array.Reverse(keyBytes); memoryStream.Write(keyBytes, 0, keyBytes.Length); payload = TransformBytes(Payload, MaskKey); } memoryStream.Write(payload, 0, Payload.Length); return memoryStream.ToArray(); }
public object Deserialize(byte[] buffer) { using (MemoryStream stream = new MemoryStream(buffer)) { return ProtoBuf.Serializer.Deserialize<Protobuf.ManagementResponse>(stream); } }
public WebRequestSpy() { SpyHeaders = new Dictionary<string, string>(); SpyResponse = new WebResponseSpy(); SpyRequestStream = new MemoryStream(); }
public static byte[] decodeBinary(Bitmap bmp) { byte[] bytes = null; try { int wSize = bmp.Width, hSize = bmp.Height; MemoryStream stream = new MemoryStream(); for (int w = 0; w < wSize; w++) { for (int h = 0; h < hSize; h++) { Color color = bmp.GetPixel(w, h); if (color.R == 0 && color.G == 0 && color.B == 0) stream.WriteByte(color.A); else break; } } bytes = stream.ToArray(); stream = null; } catch (Exception e) { bytes = null; } return bytes; }
public static Stream GenerateSolidColorBitmap(Color color, int width = 1024, int height = 1024) { Stream stream = new MemoryStream(); GenerateSolidColorBitmap(stream, color, width, height); stream.Seek(0, SeekOrigin.Begin); return stream; }
public Stream Get(string key) { var stream = new MemoryStream(); var blob = container.GetBlockBlobReference(Path.Combine(BasePath, key)); DownloadBlobInParallel(blob, stream); return stream; }
/// <summary> /// Default constructor. /// </summary> /// <param name="msg">Mime message which to parse.</param> public MimeParser(byte[] msg) { m_MsgStream = new MemoryStream(msg); m_Headers = ParseHeaders(m_MsgStream); m_BoundaryID = ParseHeaderFiledSubField("Content-Type:","boundary",m_Headers); }
public static Stream ToStream(this Image image) { var stream = new System.IO.MemoryStream(); image.Save(stream, ImageFormat.Png); stream.Position = 0; return stream; }
//add near end of Terraria.IO.WorldFile.loadWorld before setting failure and success internal static void ReadModFile(string path, bool isCloudSave) { path = Path.ChangeExtension(path, ".twld"); if (!FileUtilities.Exists(path, isCloudSave)) { return; } byte[] buffer = FileUtilities.ReadAllBytes(path, isCloudSave); using (MemoryStream stream = new MemoryStream(buffer)) { using (BinaryReader reader = new BinaryReader(stream)) { byte limit = reader.ReadByte(); if (limit == 0) { return; } byte[] flags = reader.ReadBytes(limit); if (flags.Length < numByteFlags) { Array.Resize(ref flags, numByteFlags); } ReadModWorld(flags, reader); } } }
private byte[] CropImageFile(Image imageFile, int targetW, int targetH, int targetX, int targetY) { var imgMemoryStream = new MemoryStream(); Image imgPhoto = imageFile; var bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb); bmPhoto.SetResolution(72, 72); Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; grPhoto.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; try { grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), targetX, targetY, targetW, targetH, GraphicsUnit.Pixel); bmPhoto.Save(imgMemoryStream, ImageFormat.Jpeg); } catch (Exception e) { throw e; } return imgMemoryStream.GetBuffer(); }
public void GivenXdocumentWhenReadThenDlvsAreMapped() { _memStream = new MemoryStream(); using (var xmlWriter = XmlWriter.Create(_memStream, new XmlWriterSettings { Encoding = new UTF8Encoding(false) })) { xmlWriter.WriteStartElement("TIM"); xmlWriter.WriteStartElement("DLV"); xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement("DLV"); xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement("DLV"); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.Flush(); xmlWriter.Close(); } var xpathDoc = CreateXDoc(); var dlvs = new List<DLV> { new DLV(), new DLV(), new DLV() }; _dlvReaderMock.Setup(x => x.Read(It.Is<XPathNodeIterator>( y => y.Count == 3))).Returns(dlvs); var result = _timReader.Read(xpathDoc).First(); Assert.AreSame(dlvs[0], result.Items[0]); Assert.AreSame(dlvs[1], result.Items[1]); Assert.AreSame(dlvs[2], result.Items[2]); }
public static string Decode(string str, string key) { DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8)); provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8)); byte[] buffer = new byte[str.Length / 2]; for (int i = 0; i < (str.Length / 2); i++) { int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10); buffer[i] = (byte)num2; } MemoryStream stream = new MemoryStream(); CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write); stream2.Write(buffer, 0, buffer.Length); stream2.FlushFinalBlock(); stream.Close(); return Encoding.GetEncoding("UTF-8").GetString(stream.ToArray()); }
public Frame(int type, int channel) { m_type = type; m_channel = channel; m_payload = null; m_accumulator = new MemoryStream(); }
public Metahash(Dictionary <string, string> values, Options options) { m_values = values; using (var ms = new System.IO.MemoryStream()) using (var w = new StreamWriter(ms, Encoding.UTF8)) using (var filehasher = System.Security.Cryptography.HashAlgorithm.Create(options.FileHashAlgorithm)) { if (filehasher == null) { throw new Duplicati.Library.Interface.UserInformationException(Strings.Common.InvalidHashAlgorithm(options.FileHashAlgorithm)); } w.Write(JsonConvert.SerializeObject(values)); w.Flush(); m_blob = ms.ToArray(); ms.Position = 0; m_filehash = Convert.ToBase64String(filehasher.ComputeHash(ms)); } }
/// <summary> /// Serializes current PORX_MT000004UK02PertinentInformation object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return(streamReader.ReadToEnd()); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } }
/// <summary> /// 流转化为字节数组 /// </summary> /// <param name="theStream">流</param> /// <returns>字节数组</returns> public byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream) { int bi; MemoryStream tempStream = new System.IO.MemoryStream(); try { while ((bi = theStream.ReadByte()) != -1) { tempStream.WriteByte(((byte)bi)); } return(tempStream.ToArray()); } catch { return(new byte[0]); } finally { tempStream.Close(); } }
private void zapiszPlikWord2(string nazwaPlikuWord, string plikJpg) { var newFile2 = sciezka + nazwaPlikuWord + ".docx"; using (var fs = new FileStream(newFile2, FileMode.Create, FileAccess.Write)) { //var wDoc = new XWPFDocument(); //var bytes = File.ReadAllBytes(sciezkaplikuJpg + plikJpg+".jpeg"); //wDoc.AddPictureData(bytes, (int)NPOI.SS.UserModel.PictureType.JPEG); XWPFDocument doc = new XWPFDocument(); var p0 = doc.CreateParagraph(); p0.Alignment = ParagraphAlignment.CENTER; XWPFRun r0 = p0.CreateRun(); var bytes = File.ReadAllBytes(sciezkaplikuJpg + plikJpg + ".jpeg"); Stream stream = new System.IO.MemoryStream(bytes); r0.AddPicture(stream, (int)NPOI.SS.UserModel.PictureType.JPEG, "image1", Units.ToEMU(700), Units.ToEMU(800)); doc.Write(fs); } }
public static byte[] CreatePDF(string htmlContent, string cssPath) { using (MemoryStream stream = new System.IO.MemoryStream()) { Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); HtmlPipelineContext htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssResolver.AddCssFile(cssPath, true); IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, writer))); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser parser = new XMLParser(worker); parser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(htmlContent))); pdfDoc.Close(); return(stream.GetBuffer()); } }
static byte[] Decompress(byte[] gzip) { using (System.IO.Compression.GZipStream stream = new System.IO.Compression.GZipStream(new System.IO.MemoryStream(gzip), System.IO.Compression.CompressionMode.Decompress)) { const int size = 4096; byte[] buffer = new byte[size]; using (System.IO.MemoryStream memory = new System.IO.MemoryStream()) { int count = 0; do { count = stream.Read(buffer, 0, size); if (count > 0) { memory.Write(buffer, 0, count); } }while (count > 0); return(memory.ToArray()); } } }
private void button3_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); if (dlg.ShowDialog() == DialogResult.OK) { pictureBox1.Image = Image.FromFile(dlg.FileName); } db = new Database(); System.Drawing.Image scanpic = pictureBox1.Image; // byte array System.IO.MemoryStream imageStream; byte[] imageBytes; imageStream = new System.IO.MemoryStream(); scanpic.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg); imageBytes = imageStream.ToArray(); // VARBINARY(MAX) db.AddPictures(imageBytes, 77); }
//加密: public static string Encrypting(string strSource) { //把字符串放到byte数组中 byte[] bytIn = System.Text.Encoding.Default.GetBytes(strSource); //建立加密对象的密钥和偏移量 byte[] iv = { 102, 16, 93, 156, 78, 4, 218, 32 }; //定义偏移量 byte[] key = { 55, 103, 246, 79, 36, 99, 167, 3 }; //定义密钥 //实例DES加密类 DESCryptoServiceProvider mobjCryptoService = new DESCryptoServiceProvider(); mobjCryptoService.Key = iv; mobjCryptoService.IV = key; ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor(); //实例MemoryStream流加密密文件 System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write); cs.Write(bytIn, 0, bytIn.Length); cs.FlushFinalBlock(); return(System.Convert.ToBase64String(ms.ToArray())); }
public IActionResult Download() { IList <Anexo> sourceFiles = AnexoRepository.anexos; // ... // the output bytes of the zip byte[] fileBytes = null; // create a working memory stream using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { // create a zip using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true)) { // interate through the source files foreach (var f in sourceFiles) { // add the item name to the zip System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(f.Name); // add the item bytes to the zip entry by opening the original file and copying the bytes using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(f.file)) { using (System.IO.Stream entryStream = zipItem.Open()) { originalFileMemoryStream.CopyTo(entryStream); } } } } fileBytes = memoryStream.ToArray(); } // download the constructed zip Response.Headers.Add("Content-Disposition", "attachment; filename=download.zip"); // .("Content-Disposition", "attachment; filename=download.zip"); return(File(fileBytes, "application/zip")); }
private void dgwcategorias_SelectionChanged(object sender, EventArgs e) { //sirve para que se cargen en los textbox if (dgwcategorias.SelectedRows.Count > 0) { DataRowView drv = (DataRowView)dgwcategorias.SelectedRows[0].DataBoundItem; txtcodigocategoria.Text = drv["Codigo_Cat"].ToString(); txtnombrecategoria.Text = drv["Nombre_Cat"].ToString(); txtdescripcion.Text = drv["Descripcion_Cat"].ToString(); dtpfecharegistro.Text = drv["Fecha"].ToString(); Id_Cat = drv["Id_Cat"].ToString(); byte[] imagenBuffer = (byte[])this.dgwcategorias.CurrentRow.Cells["Imagen"].Value; // Se crea un MemoryStream a partir de ese buffer System.IO.MemoryStream ms = new System.IO.MemoryStream(imagenBuffer); // Se utiliza el MemoryStream para extraer la imagen this.pxImagen.Image = Image.FromStream(ms); this.pxImagen.SizeMode = PictureBoxSizeMode.StretchImage; habilitarCampos(false); } }
static void Main(string[] args) { // Convert Image class to PDF file SautinSoft.PdfVision v = new SautinSoft.PdfVision(); //v.Serial = "XXXXXXXXXXXXXXX"; //specify converting options v.PageStyle.PageSize.Auto(); //v.PageStyle.PageMarginLeft.Inch(1); //v.ImageStyle.Heightmm(150); //v.ImageStyle.WidthInch(10); // Create object of Image class from file System.Drawing.Image image = Image.FromFile(@"..\..\image-jpeg.jpg"); FileInfo outFile = new FileInfo(@"Result.pdf"); byte[] imgBytes = null; using (MemoryStream ms = new System.IO.MemoryStream()) { image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); imgBytes = ms.ToArray(); } // Convert image stream to PDF file int ret = v.ConvertImageStreamToPDFFile(imgBytes, outFile.FullName); if (ret == 0) { // Open the resulting PDF document in a default PDF Viewer. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile.FullName) { UseShellExecute = true }); } }
public System.IO.Stream DoResampler(DriverModels.EngineInput Args) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); if (!_isLegalPlugin) { return(ms); } try { string tmpFile = System.IO.Path.GetTempFileName(); string ArgParam = $"\"{Args.inputWaveFile}\" \"{tmpFile}\" {Args.NoteString} {Args.Velocity} \"{Args.StrFlags}\" {Args.Offset} {Args.RequiredLength} {Args.Consonant} {Args.Cutoff} {Args.Volume} {Args.Modulation} !{Args.Tempo} {Base64.Base64EncodeInt12(Args.pitchBend)}"; var p = Process.Start(new ProcessStartInfo(ExePath, ArgParam) { UseShellExecute = false, CreateNoWindow = true }); p.WaitForExit(); if (p != null) { p.Close(); p.Dispose(); p = null; } if (System.IO.File.Exists(tmpFile)) { byte[] Dat = System.IO.File.ReadAllBytes(tmpFile); ms = new MemoryStream(Dat); try { System.IO.File.Delete(tmpFile); } catch {; } } } catch (Exception) {; } return(ms); }
private void tbl_inventory_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.AddedItems.Count == 0) { return; } prod_image.Source = null; DataRowView SelectedItem = tbl_inventory.SelectedItem as DataRowView; prod_id.Text = SelectedItem.Row["prod_id"].ToString(); prod_brand.Text = SelectedItem.Row["prod_brand"].ToString(); prod_model.Text = SelectedItem.Row["prod_model"].ToString(); prod_yearModel.Text = SelectedItem.Row["prod_yearModel"].ToString(); prod_capital.Text = SelectedItem.Row["prod_capital"].ToString(); prod_size.Text = SelectedItem.Row["prod_size"].ToString(); prod_quantity.Text = SelectedItem.Row["prod_quantity"].ToString(); prod_price.Text = SelectedItem.Row["prod_price"].ToString(); byte[] data = (byte[])SelectedItem.Row["prod_image"]; // 0 is okay if you only selecting one column //And use: if (data != null && data.Length > 0) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data)) { var imageSource = new BitmapImage(); imageSource.BeginInit(); imageSource.StreamSource = ms; imageSource.CacheOption = BitmapCacheOption.OnLoad; imageSource.EndInit(); prod_image.Source = imageSource; } } else { return; } }
/// <summary> /// Serializes current urlset object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize(System.Text.Encoding encoding) { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings(); xmlWriterSettings.Encoding = encoding; xmlWriterSettings.OmitXmlDeclaration = true; System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", "http://www.sitemaps.org/schemas/sitemap/0.9"); ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance"); Serializer.Serialize(xmlWriter, this, ns); //xmlWriterSettings.OmitXmlDeclaration = true; //System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings); //XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ////ns.Add("image", "http://www.sitemaps.org/schemas/sitemap-image/1.1"); ////ns.Add("video", "http://www.sitemaps.org/schemas/sitemap-video/1.1"); ////ns.Add("mobile", "http://www.google.com/schemas/sitemap-mobile/1.0"); ////ns.Add("news", "http://www.google.com/schemas/sitemap-news/0.9"); //ns.Add("", "http://www.sitemaps.org/schemas/sitemap/0.9"); //Serializer.Serialize(xmlWriter, this, ns); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return(streamReader.ReadToEnd()); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } }
public string Encrypting(string Source, string Key) { byte[] bytIn = System.Text.ASCIIEncoding.ASCII.GetBytes(Source); // create a MemoryStream so that the process can be done without I/O files System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] bytKey = GetLegalKey(Key); // set the private key mobjCryptoService.Key = bytKey; mobjCryptoService.IV = bytKey; // create an Encryptor from the Provider Service instance ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor(); // create Crypto Stream that transforms a stream using the encryption CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write); // write out encrypted content into MemoryStream cs.Write(bytIn, 0, bytIn.Length); cs.FlushFinalBlock(); // get the output and trim the '\0' bytes byte[] bytOut = ms.GetBuffer(); int i = 0; for (i = 0; i < bytOut.Length; i++) { if (bytOut[i] == 0) { break; } } // convert into Base64 so that the result can be used in xml return(ByteArrayToUrlString(bytOut));//System.Convert.ToBase64String(bytOut, 0, i); }
private void ExportExcel(string orderIds) { XSSFWorkbook book = new XSSFWorkbook(); //HSSFWorkbook book = new HSSFWorkbook(); OrderOperation op = new OrderOperation(); string[] orderId_strs = orderIds.Split(','); //int row_count = 0; for (int i = 0; i < orderId_strs.Length; i++) { ISheet sheet = book.CreateSheet("Packing List " + (i + 1)); sheet.PrintSetup.Scale = 85; Guid orderId = new Guid(orderId_strs[i]); ExportCrmOrder crmOrder = op.getOrderInfoById(orderId); this.CreateDetailRow(0, book, sheet, crmOrder); sheet.ProtectSheet("password_123"); } string excelName = "Packing List"; System.IO.MemoryStream ms = new System.IO.MemoryStream(); book.Write(ms); HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + excelName + "(" + DateTime.Now.ToString("yyyyMMdd") + ")" + ".xlsx")); HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().Length.ToString()); HttpContext.Current.Response.BinaryWrite(ms.ToArray()); book = null; ms.Close(); ms.Dispose(); System.Web.HttpContext.Current.Response.End(); }
private void SendImage_button_Click(object sender, RoutedEventArgs e) { try { string path = ""; OpenFileDialog ofd = new OpenFileDialog(); ofd.DefaultExt = ".jpg"; ofd.Filter = "JPG-file (.jpg)|*.jpg"; if (ofd.ShowDialog() == true) { path = ofd.FileName; } if (path != "") { s.SendImage(path); byte[] img = System.IO.File.ReadAllBytes(path); using (var ms = new System.IO.MemoryStream(img)) { var image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; // here image.StreamSource = ms; image.DecodePixelHeight = 150; image.DecodePixelWidth = 150; image.EndInit(); Image imger = new Image(); imger.Source = image; listMessage.Items.Add(DateTime.Now + " Me: Sent Image"); listMessage.Items.Add(imger); } } } catch (ArgumentException aex) { MessageBox.Show("Something went wrong while trying to send the image"); } }
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); }
private void btnGuardarCambios_Click(object sender, EventArgs e) { if (txtnombres.Text != "") { try { SqlConnection con = new SqlConnection(); con.ConnectionString = Conexion.ConexionDB.conexion; con.Open(); SqlCommand cmd = new SqlCommand(); cmd = new SqlCommand("editar_usuario", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@idUsuario", lblIDUsuario.Text); cmd.Parameters.AddWithValue("@nombre", txtnombres.Text); cmd.Parameters.AddWithValue("@login", txtusuario.Text); cmd.Parameters.AddWithValue("@password", txtcontraseña.Text); System.IO.MemoryStream ms = new System.IO.MemoryStream(); picIcono.Image.Save(ms, picIcono.Image.RawFormat); cmd.Parameters.AddWithValue("@icono", ms.GetBuffer()); cmd.Parameters.AddWithValue("@nombre_icono", lbnumeroIcono.Text); cmd.Parameters.AddWithValue("@Rol", cmbtipoUsuario.Text); cmd.ExecuteNonQuery(); con.Close(); mostrar(); panel5.Visible = false; } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
/// <summary> /// 进行DES加密。 /// </summary> /// <param name="pToEncrypt">要加密的字符串。</param> /// <param name="sKey">密钥,且必须为8位。</param> /// <returns>以Base64格式返回的加密字符串。</returns> public static string EncryptDES(string pToEncrypt, string sKey) { using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt); if (sKey.Length < 8) { sKey = sKey.PadRight(8); } des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Convert.ToBase64String(ms.ToArray()); ms.Close(); return(str); } }
/// <summary> /// TripleDES加密 /// </summary> public static string TripleDESEncrypting(string strSource) { try { byte[] bytIn = Encoding.Default.GetBytes(strSource); byte[] key = { 42, 16, 93, 156, 78, 4, 218, 32, 15, 167, 44, 80, 26, 20, 155, 112, 2, 94, 11, 204, 119, 35, 184, 197 }; //定义密钥 byte[] IV = { 55, 103, 246, 79, 36, 99, 167, 3 }; //定义偏移量 TripleDESCryptoServiceProvider TripleDES = new TripleDESCryptoServiceProvider(); TripleDES.IV = IV; TripleDES.Key = key; ICryptoTransform encrypto = TripleDES.CreateEncryptor(); System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write); cs.Write(bytIn, 0, bytIn.Length); cs.FlushFinalBlock(); byte[] bytOut = ms.ToArray(); return(System.Convert.ToBase64String(bytOut)); } catch (Exception ex) { throw new Exception("加密时候出现错误!错误提示:\n" + ex.Message); } }
/// <summary> /// 解密数据 /// </summary> /// <param name="Text"></param> /// <param name="sKey"></param> /// <returns></returns> public static string Decrypt(string Text, string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); int len; len = Text.Length / 2; byte[] inputByteArray = new byte[len]; int x, i; for (x = 0; x < len; x++) { i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); inputByteArray[x] = (byte)i; } des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return(Encoding.Default.GetString(ms.ToArray())); }
public static void WriteExternalFiles(ResFile resFile, TreeNode EditorRoot) { resFile.ExternalFiles.Clear(); if (EditorRoot.Nodes.ContainsKey("EXT")) { foreach (TreeNode node in EditorRoot.Nodes["EXT"].Nodes) { ExternalFile ext = new ExternalFile(); if (node is BNTX) { var mem = new System.IO.MemoryStream(); ((BNTX)node).Save(mem); ext.Data = mem.ToArray(); } else { ext.Data = ((ExternalFileData)node).Data; } resFile.ExternalFiles.Add(node.Text, ext); } } }
public string shadow_decrypt(string encyptedText) { fish = new Twofish(); fish.Mode = CipherMode.ECB; ms = new System.IO.MemoryStream(); //form.log("we were sent the IM with " + encyptedText); byte[] encyptedBytes = Utils.StringToBytes(encyptedText); ICryptoTransform decode = new FromBase64Transform(); //create DES Decryptor from our des instance ICryptoTransform decrypt = fish.CreateDecryptor(form.getKey(), encyptedBytes); System.IO.MemoryStream msD = new System.IO.MemoryStream(); CryptoStream cryptostreamDecode = new CryptoStream(new CryptoStream(msD, decrypt, CryptoStreamMode.Write), decode, CryptoStreamMode.Write); cryptostreamDecode.Write(encyptedBytes, 0, encyptedBytes.Length); cryptostreamDecode.Close(); byte[] bytOutD = msD.ToArray(); // we should now have our plain text back form.log("We decrypted " + encyptedText + " to " + Utils.BytesToString(bytOutD), Color.Red); return("" + this.indicator + "" + Utils.BytesToString(bytOutD)); }
public ActionResult export() { var tsql = Request.getValue("tsql"); using (var db = local.getDataObject()) { try { var dt = db.getDataSet(tsql); if (dt.Tables.Count == 0) { return(Content("Không có dữ liệu")); } using (var ms = new System.IO.MemoryStream()) { dt.WriteXml(ms, System.Data.XmlWriteMode.WriteSchema); ms.Position = 0; return(File(ms.ToArray(), "application/octet-stream", "tsql.xml")); } } catch (Exception ex) { return(Content(ex.Message)); } } }
public ActionResult RetrieveFile(int id) { // DownloadModel download = new DownloadModel(); // FileStream stream = null; byte[] songBytes; //UploadModel myfile = new UploadModel(); var data = getAudioFile(id); if (data.Count > 0) { songBytes = data[0].AudioFile; System.IO.MemoryStream oMemoryStream = new System.IO.MemoryStream(songBytes); FileStreamResult fsresult = new FileStreamResult(oMemoryStream, "audio/mp3"); return(fsresult); } else { return(null); } // return View(); }
/// <summary> /// 在儲存前,把資料填入儲存欄位中 /// </summary> public void Encode() { this.ExamRecordID = (this.ExamRecord == null ? "" : this.ExamRecord.ID); this.PrintSubjectListString = ""; foreach (var item in this.PrintSubjectList) { this.PrintSubjectListString += (this.PrintSubjectListString == "" ? "" : "^^^") + item; } this.RefenceExamRecordID = (this.RefenceExamRecord == null ? "" : this.RefenceExamRecord.ID); this.TagRank1SubjectListString = ""; foreach (var item in this.TagRank1SubjectList) { this.TagRank1SubjectListString += (this.TagRank1SubjectListString == "" ? "" : "^^^") + item; } this.TagRank2SubjectListString = ""; foreach (var item in this.TagRank2SubjectList) { this.TagRank2SubjectListString += (this.TagRank2SubjectListString == "" ? "" : "^^^") + item; } System.IO.MemoryStream stream = new System.IO.MemoryStream(); this.Template.Save(stream, Aspose.Words.SaveFormat.Doc); this.TemplateStream = Convert.ToBase64String(stream.ToArray()); }
public void EnableHiDefProfile() { EmbeddedResource hidefprofile = null; hidefprofilestream = new System.IO.MemoryStream(); System.IO.StreamWriter sw = new System.IO.StreamWriter(hidefprofilestream); sw.Write("Windows.v4.0.HiDef"); sw.Flush(); hidefprofilestream.Seek(0, System.IO.SeekOrigin.Begin); hidefprofile = new EmbeddedResource("Microsoft.Xna.Framework.RuntimeProfile", ManifestResourceAttributes.Private, hidefprofilestream); for (int i = 0; i < terraria.MainModule.Resources.Count; i++) { if (terraria.MainModule.Resources[i].Name == "Microsoft.Xna.Framework.RuntimeProfile") { terraria.MainModule.Resources[i] = hidefprofile; } } }
public void StopWalking(Vector2d stopPos) { if (!IsAlive) { return; } myNextWalkDirection = WalkDirection.Still; OriginX = stopPos.X; OriginY = stopPos.Y; if (IsServer) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); stream.Write(BitConverter.GetBytes(OriginX), 0, sizeof(Double)); stream.Write(BitConverter.GetBytes(OriginY), 0, sizeof(Double)); SendStateUpdate("StopWalking", stream); stream.Close(); myLastWalkStateSent = Map.TimeTicks; } }
//public void ExportPDF([Bind(Include = "id")] long id) //{ // List<CobrosExportPDFVM> list = _repo.GetCobros(id); // iTextSharp.text.Document document = new iTextSharp.text.Document(); // document.Open(); // iTextSharp.text.Font fontTitle = FontFactory.GetFont(FontFactory.COURIER_BOLD, 25); // iTextSharp.text.Font font9 = FontFactory.GetFont(FontFactory.TIMES, 9); // iTextSharp.text.Font tituloTabla = FontFactory.GetFont(FontFactory.TIMES_BOLD, 9); // //Cabecera // Paragraph title = new Paragraph(20, "Cobros", fontTitle); // title.Alignment = Element.ALIGN_CENTER; // document.Add(title); // document.Add(new Paragraph(23, "Nro Recibo: ")); // document.Add(new Paragraph(24, "Cliente: ", font9)); // document.Add(new Paragraph(25, "Nro Factura: ", font9)); // document.Add(new Paragraph(26, "Fecha Factura: ", font9)); // document.Add(new Paragraph(27, "Monto: ", font9)); // document.Add(new Paragraph(28, "Cobro Parcial: ", font9)); // document.Add(new Paragraph(29, "Subtotal Recibo: ", font9)); // document.Add(new Paragraph(30, "Total: ", font9)); // document.Add(new Chunk("\n")); // //Detalle // DataTable dt = CreateDetalleDataTable(); // foreach (var item in list) // { // DataRow row = dt.NewRow(); // row["NroRecibo"] = item.nroRecibo; // row["Cliente"] = item.cliente; // row["NroFactura"] = item.nroFactura; // row["FechaFactura"] = item.fechaFactura; // row["Monto"] = item.monto; // row["CobroParcial"] = item.cobroParcial; // row["SubtotalRecibo"] = item.subtotalRecibo; // row["Total"] = item.total; // dt.Rows.Add(row); // } // PdfPTable table = new PdfPTable(dt.Columns.Count); // float[] widths = new float[dt.Columns.Count]; // for (int i = 0; i < dt.Columns.Count; i++) // widths[i] = 4f; // table.SetWidths(widths); // table.WidthPercentage = 100; // table.HorizontalAlignment = Element.ALIGN_CENTER; // foreach (DataColumn c in dt.Columns) // { // PdfPCell cell = new PdfPCell(); // Paragraph p = new Paragraph(c.ColumnName, tituloTabla); // p.Alignment = Element.ALIGN_CENTER; // cell.AddElement(p); // table.AddCell(cell); // } // foreach (DataRow r in dt.Rows) // { // if (dt.Rows.Count > 0) // { // for (int h = 0; h < dt.Columns.Count; h++) // { // PdfPCell cell = new PdfPCell(); // Paragraph p = new Paragraph(r[h].ToString(), font9); // p.Alignment = Element.ALIGN_CENTER; // cell.AddElement(p); // table.AddCell(cell); // } // } // } // document.Add(table); // document.Close(); // Response.ContentType = "application/pdf"; // Response.AddHeader("content-disposition", "attachment;filename=Cobros.pdf"); // HttpContext.Response.Write(document); // Response.Flush(); // Response.End(); //} public ActionResult ExportPDF([Bind(Include = "nroFactura")] string nroFactura) { CobroVMIndex model = new CobroVMIndex { nroFactura = nroFactura }; IEnumerable <ListCobros> list = _repo.CobrosList(nroFactura); model.list = list; var HTMLViewStr = RenderViewToString(ControllerContext, "~/Views/Cobro/ExportPDF.cshtml", model); using (MemoryStream stream = new System.IO.MemoryStream()) { StringReader sr = new StringReader(HTMLViewStr); iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 100f, 0f); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr); pdfDoc.Close(); return(File(stream.ToArray(), "application/pdf", "Cobros.pdf")); } }