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


C# MemoryStream.Close方法代码示例

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


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

示例1: Decrypt

        public static string Decrypt(string cipherText, string passPhrase)
        {
            // Get the complete stream of bytes that represent:
            // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
            // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
            var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
            // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

            var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations);
            var keyBytes = password.GetBytes(Keysize / 8);
            using (var symmetricKey = new RijndaelManaged())
            {
                symmetricKey.BlockSize = 256;
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
                using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream(cipherTextBytes))
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            var plainTextBytes = new byte[cipherTextBytes.Length];
                            var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                            memoryStream.Close();
                            cryptoStream.Close();
                            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                        }
                    }
                }
            }
        }
开发者ID:oozcitak,项目名称:RebarPos,代码行数:35,代码来源:Crypto.cs

示例2: Encrypt

 public static string Encrypt(string plainText, string passPhrase)
 {
     // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
     // so that the same Salt and IV values can be used when decrypting.
     var saltStringBytes = Generate256BitsOfRandomEntropy();
     var ivStringBytes = Generate256BitsOfRandomEntropy();
     var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations);
     var keyBytes = password.GetBytes(Keysize / 8);
     using (var symmetricKey = new RijndaelManaged())
     {
         symmetricKey.BlockSize = 256;
         symmetricKey.Mode = CipherMode.CBC;
         symmetricKey.Padding = PaddingMode.PKCS7;
         using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
         {
             using (var memoryStream = new MemoryStream())
             {
                 using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                 {
                     cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                     cryptoStream.FlushFinalBlock();
                     // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                     var cipherTextBytes = saltStringBytes;
                     cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                     cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                     memoryStream.Close();
                     cryptoStream.Close();
                     return Convert.ToBase64String(cipherTextBytes);
                 }
             }
         }
     }
 }
开发者ID:oozcitak,项目名称:RebarPos,代码行数:34,代码来源:Crypto.cs

示例3: AESDecryptWithoutVector

        /// <summary>
        /// AES解密(无向量)
        /// </summary>
        /// <param name="encryptedBytes">被加密的明文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public static string AESDecryptWithoutVector(String Data, String Key)
        {
            Byte[] encryptedBytes = Convert.FromBase64String(Data);
            Byte[] bKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);

            MemoryStream mStream = new MemoryStream(encryptedBytes);
            //mStream.Write( encryptedBytes, 0, encryptedBytes.Length );
            //mStream.Seek( 0, SeekOrigin.Begin );
            RijndaelManaged aes = new RijndaelManaged();
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            aes.KeySize = 128;
            aes.Key = bKey;
            //aes.IV = _iV;
            CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
            try
            {
                byte[] tmp = new byte[encryptedBytes.Length + 32];
                int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
                byte[] ret = new byte[len];
                Array.Copy(tmp, 0, ret, 0, len);
                return Encoding.UTF8.GetString(ret);
            }
            finally
            {
                cryptoStream.Close();
                mStream.Close();
                aes.Clear();
            }
        }
开发者ID:keymorrislane,项目名称:SEMC_SQL-for-Excel,代码行数:37,代码来源:AESModel.cs

示例4: Decrypt

 public string Decrypt(string strEncryptedText)
 {
     if (strEncryptedText == null || strEncryptedText.Equals(""))
         return strEncryptedText;
     string strDecryptedText = null;
     RijndaelManaged rijndael = new RijndaelManaged();
     ICryptoTransform decryptor = rijndael.CreateDecryptor(Key, IV);
     byte[] byteEncryptedText = Convert.FromBase64String(strEncryptedText);
     MemoryStream memStream = new MemoryStream(byteEncryptedText);
     CryptoStream decryptStream = null;
     try
     {
         decryptStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read);
         byte[] byteDecryptedText = new byte[byteEncryptedText.Length];
         int decryptedByteCount = decryptStream.Read(byteDecryptedText, 0, byteDecryptedText.Length);
         strDecryptedText = Encoding.UTF8.GetString(byteDecryptedText, 0, decryptedByteCount);
     }
     finally
     {
         if (rijndael != null) rijndael.Clear();
         if (decryptor != null) decryptor.Dispose();
         if (memStream != null) memStream.Close();
         if (decryptStream != null) decryptStream.Close();
     }
     if (UseSalt)
         strDecryptedText = strDecryptedText.Substring(8);
     return strDecryptedText;
 }
开发者ID:ssaporta,项目名称:reports,代码行数:28,代码来源:Crypto.cs

示例5: DecryptString

 protected static string DecryptString(string InputText, string Password)
 {
     try
     {
         RijndaelManaged RijndaelCipher = new RijndaelManaged();
         byte[] EncryptedData = Convert.FromBase64String(InputText);
         byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
         PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
         // Create a decryptor from the existing SecretKey bytes.
         ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
         MemoryStream memoryStream = new MemoryStream(EncryptedData);
         // Create a CryptoStream. (always use Read mode for decryption).
         CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
         // Since at this point we don't know what the size of decrypted data
         // will be, allocate the buffer long enough to hold EncryptedData;
         // DecryptedData is never longer than EncryptedData.
         byte[] PlainText = new byte[EncryptedData.Length];
         // Start decrypting.
         int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
         memoryStream.Close();
         cryptoStream.Close();
         // Convert decrypted data into a string.
         string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
         // Return decrypted string.
         return DecryptedData;
     }
     catch (Exception exception)
     {
         return (exception.Message);
     }
 }
开发者ID:balajivit1,项目名称:Sourcecode,代码行数:31,代码来源:ViewAdminRequests.cs

示例6: Encode

        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();
        }
开发者ID:MrNor,项目名称:WxMp,代码行数:31,代码来源:CryptHelper.cs

示例7: CompressBuffer

 /// <summary>
 /// Compresses an array of bytes and stores the result in a new array of bytes.
 /// </summary>
 /// <param name="uncompressed">The uncompressed buffer.</param>
 /// <param name="compressed">An array of bytes where the compressed input will be stored.</param>
 /// <remarks>
 /// The compressed input is passed back to the calling method as an <b>out</b>
 /// parameter. That means that the calling method doesn't need to initialize the
 /// compressed buffer.  
 /// </remarks>
 /// <exception cref="ArgumentNullException">
 /// Thrown if the uncompressed input buffer is empty or null.
 /// </exception>
 /// <exception cref="CWZipException">
 /// Thrown if a problem is encountered during the compression process.
 /// </exception>
 public static void CompressBuffer(byte[] uncompressed, out byte[] compressed)
 {
     if ((uncompressed == null) || (uncompressed.Length == 0))
     {
         throw new ArgumentNullException("uncompressed", "The uncompressed input buffer cannot be null or empty.");
     }
     MemoryStream ms = null;
     compressed = null;
     try
     {
         ms = new MemoryStream();
         ZipOutputStream zip = new ZipOutputStream(ms);
         zip.SetLevel(compressionLevel);
         ZipEntry entry = new ZipEntry("1");
         zip.PutNextEntry(entry);
         zip.Write(uncompressed, 0, uncompressed.Length);
         zip.Finish();
         ms.Position = 0;
         compressed = ms.ToArray();
         ms.Close();
     }
     catch (Exception e)
     {
         if (ms != null)
         {
             ms.Close();
         }
         throw new CWZipException(e.Message);
     }
     finally
     {
         ms = null;
         GC.Collect();
     }
 }
开发者ID:modernist,项目名称:CrawlWave,代码行数:51,代码来源:CompressionUtils.cs

示例8: SaveSettingsFile

        public static bool SaveSettingsFile(PluginSettingsBase settings, Type type, string filename)
        {
            MemoryStream ms = null;
            FileStream fs = null;
            XmlSerializer xs = null;
            try
            {
                ms = new MemoryStream();
                fs = new FileStream(filename, FileMode.Create, FileAccess.Write);

                xs = new XmlSerializer(type);
                xs.Serialize(ms, settings);
                ms.Seek(0, SeekOrigin.Begin);
                fs.Write(ms.ToArray(), 0, (int)ms.Length);
                ms.Close();
                fs.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                if (ms != null) ms.Close();
                if (fs != null) fs.Close();
            }
        }
开发者ID:dbremner,项目名称:blurip,代码行数:28,代码来源:PluginBase.cs

示例9: getName

        /// <summary>
        ///     Gets the name of the first model on a CGFX file.
        ///     Returns null if the file doesn't contain any model.
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string getName(MemoryStream data)
        {
            BinaryReader input = new BinaryReader(data);

            cgfxHeader header = new cgfxHeader();
            header.magic = IOUtils.readString(input, 0, 4);
            header.endian = input.ReadUInt16();
            header.length = input.ReadUInt16();
            header.revision = input.ReadUInt32();
            header.fileLength = input.ReadUInt32();
            header.entries = input.ReadUInt32();

            data.Seek(header.length + 8, SeekOrigin.Begin);
            List<dictEntry> models = getDictionary(input);

            if (models.Count > 0)
            {
                data.Seek(models[0].dataOffset + 0xc, SeekOrigin.Begin);
                string name = IOUtils.readString(input, getRelativeOffset(input));
                data.Close();
                return name;
            }
            else
            {
                data.Close();
                return null;
            }
        }
开发者ID:Quibilia,项目名称:Ohana3DS-Transfigured,代码行数:34,代码来源:CGFX.cs

示例10: LoadDataInToWorkSheet

        protected static void LoadDataInToWorkSheet(MemoryStream stream, ExcelFile sheet, DataFileFormat fileFormat)
        {
            if (fileFormat == DataFileFormat.excel)
            {
                sheet.LoadXls(stream);
                stream.Close();
                return;
            }

            File.WriteAllBytes(@"C:\Test.csv", stream.ToArray());
            sheet.LoadCsv(stream, CsvType.CommaDelimited);
            stream.Close();
        }
开发者ID:RJacksonm1,项目名称:JustGiving.Api.Sdk,代码行数:13,代码来源:ApiTestFixture.cs

示例11: WriteTagContainer

		private void WriteTagContainer(TagContainer tagContainer)
		{
			Stream dataStream = null;
			Stream tagStream = null;
			try
			{
				dataStream = new MemoryStream(m_AudioData);
				tagStream = new MemoryStream(64000);

				// Write the content to a byte stream.
				m_Controller.Write(tagContainer, dataStream, tagStream);
			}
			finally
			{
				if (dataStream != null)
				{
					dataStream.Close();
					dataStream.Dispose();
				}

				if (tagStream != null)
				{
					tagStream.Close();
					tagStream.Dispose();
				}
			}
		}
开发者ID:saitodisse,项目名称:id3tag.net,代码行数:27,代码来源:ValidatorTest.cs

示例12: logon

		public Constants.LoginStatus logon(User user)
		{
			Constants.LoginStatus retval = Constants.LoginStatus.STATUS_SERVERNOTREACHED;
			byte[] message = new byte[Constants.WRITEBUFFSIZE];
			byte[] reply;
			MemoryStream stream = new MemoryStream(message);

			try
			{
				//Serialize data in memory so you can send them as a continuous stream
				BinaryFormatter serializer = new BinaryFormatter();
				
				NetLib.insertEntropyHeader(serializer, stream);

				serializer.Serialize(stream, Constants.MessageTypes.MSG_LOGIN);
				serializer.Serialize(stream, user.ringsInfo[0].ring.ringID);
				serializer.Serialize(stream, user.ringsInfo[0].userName);
				serializer.Serialize(stream, user.ringsInfo[0].password);
				serializer.Serialize(stream, user.node.syncCommunicationPoint);
				reply = NetLib.communicate(Constants.SERVER2,message, true);
				stream.Close();
				stream = new MemoryStream(reply);
				NetLib.bypassEntropyHeader(serializer, stream);
				Constants.MessageTypes replyMsg = (Constants.MessageTypes)serializer.Deserialize(stream);

				switch(replyMsg)
				{
					case Constants.MessageTypes.MSG_OK:
						ulong sessionID = (ulong)serializer.Deserialize(stream);
						uint numRings = (uint)serializer.Deserialize(stream);
						uint ringID;
						Ring ring;
						for(uint ringCounter = 0; ringCounter < numRings; ringCounter++)
						{
							LordInfo lordInfo = (LordInfo)serializer.Deserialize(stream);
							ring = RingInfo.findRingByID(user.ringsInfo, lordInfo.ringID);
							ring.lords = lordInfo.lords;
						}
						
						user.loggedIn = true;
						retval = Constants.LoginStatus.STATUS_LOGGEDIN;
						break;
					case Constants.MessageTypes.MSG_NOTAMEMBER:
						retval = Constants.LoginStatus.STATUS_NOTAMEMBER;
						break;
					case Constants.MessageTypes.MSG_ALREADYSIGNEDIN:
						retval = Constants.LoginStatus.STATUS_ALREADYSIGNEDIN;
						break;
					default:
						break;
				}
			}
			catch (Exception e)
			{
				
				int x = 2;
			}

			return retval;
		}
开发者ID:beghbali,项目名称:ResourceRingEntropyNetwork,代码行数:60,代码来源:ServerProxy.cs

示例13: Run

        public static void Run()
        {
            // ExStart:ConvertPageRegionToDOM         
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            // Open document
            Document document = new Document( dataDir + "AddImage.pdf");
            // Get rectangle of particular page region
            Aspose.Pdf.Rectangle pageRect = new Aspose.Pdf.Rectangle(20, 671, 693, 1125);
            // Set CropBox value as per rectangle of desired page region
            document.Pages[1].CropBox = pageRect;
            // Save cropped document into stream
            MemoryStream ms = new MemoryStream();
            document.Save(ms);
            // Open cropped PDF document and convert to image
            document = new Document(ms);
            // Create Resolution object
            Resolution resolution = new Resolution(300);
            // Create PNG device with specified attributes
            PngDevice pngDevice = new PngDevice(resolution);
            dataDir = dataDir + "ConvertPageRegionToDOM_out.png";
            // Convert a particular page and save the image to stream
            pngDevice.Process(document.Pages[1], dataDir);
            ms.Close();
            // ExEnd:ConvertPageRegionToDOM   
            Console.WriteLine("\nPage region converted to DOM successfully.\nFile saved at " + dataDir); 
        }
开发者ID:aspose-pdf,项目名称:Aspose.Pdf-for-.NET,代码行数:28,代码来源:ConvertPageRegionToDOM.cs

示例14: Run

        public static void Run()
        {
            // ExStart:ConvertMemoryStreamImageToPdf
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_TechnicalArticles();

            // Instantiate Pdf instance by calling its empty constructor
            Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();
            // Add a section into the pdf document
            Aspose.Pdf.Generator.Section sec = pdf1.Sections.Add();

            // Create a FileStream object to read the imag file
            FileStream fs = File.OpenRead(dataDir + "aspose-logo.jpg");
            // Read the image into Byte array
            byte[] data = new byte[fs.Length];
            fs.Read(data, 0, data.Length);

            // Create a MemoryStream object from image Byte array
            MemoryStream ms = new MemoryStream(data);
            // Create an image object in the section 
            Aspose.Pdf.Generator.Image imageht = new Aspose.Pdf.Generator.Image(sec);
            // Set the type of image using ImageFileType enumeration
            imageht.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Jpeg;

            // Specify the image source as MemoryStream
            imageht.ImageInfo.ImageStream = ms;
            // Add image object into the Paragraphs collection of the section
            sec.Paragraphs.Add(imageht);

            // Save the Pdf
            pdf1.Save(dataDir + "ConvertMemoryStreamImageToPdf_out.pdf");
            // Close the MemoryStream Object
            ms.Close();
            // ExEnd:ConvertMemoryStreamImageToPdf           
        }
开发者ID:aspose-pdf,项目名称:Aspose.Pdf-for-.NET,代码行数:35,代码来源:ConvertMemoryStreamImageToPdf.cs

示例15: CreateImage

 public override byte[] CreateImage(out string validataCode)
 {
     Bitmap bitmap;
     string formatString = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
     GetRandom(formatString, this.ValidataCodeLength, out validataCode);
     MemoryStream stream = new MemoryStream();
     AnimatedGifEncoder encoder = new AnimatedGifEncoder();
     encoder.Start();
     encoder.SetDelay(1);
     encoder.SetRepeat(0);
     for (int i = 0; i < 3; i++)
     {
         this.SplitCode(validataCode);
         this.ImageBmp(out bitmap, validataCode);
         bitmap.Save(stream, ImageFormat.Png);
         encoder.AddFrame(Image.FromStream(stream));
         stream = new MemoryStream();
         bitmap.Dispose();
     }
     encoder.OutPut(ref stream);
     bitmap = null;
     stream.Close();
     stream.Dispose();
     return stream.GetBuffer();
 }
开发者ID:shenjl,项目名称:DayDayUpReal,代码行数:25,代码来源:ValidateCode_Style3.cs


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