• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Binary.BinaryFormatter类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Runtime.Serialization.Formatters.Binary.BinaryFormatter的典型用法代码示例。如果您正苦于以下问题:C# System.Runtime.Serialization.Formatters.Binary.BinaryFormatter类的具体用法?C# System.Runtime.Serialization.Formatters.Binary.BinaryFormatter怎么用?C# System.Runtime.Serialization.Formatters.Binary.BinaryFormatter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



System.Runtime.Serialization.Formatters.Binary.BinaryFormatter类属于命名空间,在下文中一共展示了System.Runtime.Serialization.Formatters.Binary.BinaryFormatter类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: LoadQuestions

 public void LoadQuestions(String fileName)
 {
     Cursor.Current = Cursors.WaitCursor;
     try
     {
         using (System.IO.Stream stream = System.IO.File.Open(fileName, System.IO.FileMode.Open))
         {
             var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             m_questions = (List<Question>)bformatter.Deserialize(stream);
         }
         using (System.IO.Stream stream = System.IO.File.Open(fileName+"p", System.IO.FileMode.Open))
         {
             Passage p = new Passage();
             var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             m_passage = (Passage)bformatter.Deserialize(stream);
         }
     }
     catch (Exception e)
     {
         Cursor.Current = Cursors.Default;
         MessageBox.Show("failed to load the file \"" + fileName + "\"\n\r" + e.Message, "Question Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     m_currentPage = 0;
     m_totalPages = m_questions.Count / m_questionsPerPage;
     this.RefreshQuestions();
     Cursor.Current = Cursors.Default;
 }
开发者ID:FrozenHelium,项目名称:ioe-model-entrance,代码行数:27,代码来源:QuestionEditor.cs


示例2: SerializeBinary

 ///  <summary>  
 ///  序列化为二进制字节数组  
 ///  </summary>  
 ///  <param  name="request">要序列化的对象 </param>  
 ///  <returns>字节数组 </returns>  
 public static byte[] SerializeBinary(object request)
 {
     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, request);
     return memStream.GetBuffer();
 }
开发者ID:nxlibing,项目名称:managesystem,代码行数:12,代码来源:SerializeBinaryHelper.cs


示例3: MapFormatter

 public MapFormatter()
 {
   serial = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
   serial.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
   serial.TypeFormat = System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesAlways;
   serial.FilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
 }
开发者ID:MarcoDorantes,项目名称:spike,代码行数:7,代码来源:Program.cs


示例4: Read

 public LocationCacheRecord Read(string key)
 {
     byte[] buffer = cache.Read(key);
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     LocationCacheRecord lcr = (LocationCacheRecord)formatter.Deserialize(new System.IO.MemoryStream(buffer));
     return lcr;
 }
开发者ID:usmanghani,项目名称:Misc,代码行数:7,代码来源:LocationCache.cs


示例5: MainWindow

        public MainWindow()
        {
            InitializeComponent();
            //if (System.IO.Directory.Exists(cardPath) == false)
            //{
            //    System.IO.Directory.CreateDirectory(cardPath);
            //}
            if (System.IO.File.Exists(cardPath + "cardList") == false)
            {
                DownloadAllCardSet();
            }
            else
            {
                try
                {
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter reader = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    System.IO.FileStream file = System.IO.File.OpenRead(cardPath + "cardList");
                    card.cardList = (List<card>)reader.Deserialize(file);
                    file.Close();
                }
                catch (Exception)
                {
                    MessageBox.Show("Your card database seems to be corrupted, we will redownload it");
                    DownloadAllCardSet();
                }

            }
            if (System.IO.File.Exists(cardPath + "cardCollection") == true)
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter reader = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                System.IO.FileStream file = System.IO.File.OpenRead(cardPath + "cardCollection");
                card.MyCollection = (List<card>)reader.Deserialize(file);
                file.Close();
            }
        }
开发者ID:Folkstorm,项目名称:My-Heartstone-cards,代码行数:35,代码来源:MainWindow.xaml.cs


示例6: ByteArrayToObject

 /// <summary>
 /// 扩展方法:将二进制byte[]数组反序列化为对象-通过系统提供的二进制流来完成反序列化
 /// </summary>
 /// <param name="SerializedObj">待反序列化的byte[]数组</param>
 /// <param name="ThrowException">是否抛出异常</param>
 /// <returns>返回结果</returns>
 public static object ByteArrayToObject(this byte[] SerializedObj, bool ThrowException)
 {
     if (SerializedObj == null)
     {
         return null;
     }
     else
     {
         try
         {
             System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             System.IO.MemoryStream stream = new System.IO.MemoryStream(SerializedObj);
             object obj = formatter.Deserialize(stream);
             return obj;
         }
         catch (System.Exception ex)
         {
             if (ThrowException)
             {
                 throw ex;
             }
             else
             {
                 return null;
             }
         }
     }
 }
开发者ID:JBTech,项目名称:Dot.Utility,代码行数:34,代码来源:ObjectToByteArrayExtension.cs


示例7: GetStock

        public Stock GetStock(StockName stockName, DateTime startDate, DateTime endDate)
        {
            string dir = String.Format(@"..\..\StockData\Yahoo");
            string filename = String.Format("{0}.stock", stockName);
            var fullPath = Path.Combine(dir, filename);

            List<IStockEntry> rates;
            if (!File.Exists(fullPath))
            {
                rates = GetStockFromRemote(stockName, startDate, endDate);
                Directory.CreateDirectory(dir);
                using (Stream stream = File.Open(fullPath, FileMode.Create))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    bformatter.Serialize(stream, rates);
                }

            }
            else
            {
                using (Stream stream = File.Open(fullPath, FileMode.Open))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    rates = (List<IStockEntry>) bformatter.Deserialize(stream);
                }
            }
            var stock = new Stock(stockName, rates);
            return stock;
        }
开发者ID:ilan84,项目名称:ZulZula,代码行数:29,代码来源:YahooDataProvider.cs


示例8: handler

        ///<summary>
        ///Forwards incoming clientdata to PacketHandler.
        ///</summary>
        public void handler()
        {
            clientStream = new SslStream(tcpClient.GetStream(), true);
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            Kettler_X7_Lib.Objects.Packet pack = null;

            X509Certificate serverCertificate = serverControl.getCertificate();

            try
            {
                clientStream.AuthenticateAsServer(serverCertificate,false, SslProtocols.Tls, false);
            }
            catch (Exception)
            {
                Console.WriteLine("Authentication failed");
                disconnect();
            }

            for (; ; )
            {
                try
                {
                    pack = formatter.Deserialize(clientStream) as Kettler_X7_Lib.Objects.Packet;
                    PacketHandler.getPacket(serverControl, this, pack);
                }
                catch
                {
                    disconnect();
                }

                Thread.Sleep(10);
            }
        }
开发者ID:rvnijnatten,项目名称:IP2,代码行数:36,代码来源:Client.cs


示例9: Application_AcquireRequestState

        //void global_asax_AcquireRequestState(object sender, EventArgs e)
        void Application_AcquireRequestState(object sender, EventArgs e)
        {
            // Code that runs when a new session is started
            // get the security cookie
            HttpCookie cookie = Request.Cookies.Get(FormsAuthentication.FormsCookieName);

            if (cookie != null)
            {
                // we got the cookie, so decrypt the value
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

                if (ticket.Expired)
                {
                    // the ticket has expired - force user to login
                    FormsAuthentication.SignOut();
                    //Response.Redirect("~/Security/Login.aspx");
                }
                else
                {
                    // ticket is valid, set HttpContext user value
                    System.IO.MemoryStream buffer = new System.IO.MemoryStream(Convert.FromBase64String(ticket.UserData));
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    HttpContext.Current.User = (System.Security.Principal.IPrincipal)formatter.Deserialize(buffer);
                }
            }
        }
开发者ID:johnval990,项目名称:ISOA,代码行数:27,代码来源:Global.asax.cs


示例10: Save

        /// <summary>
        /// Sauvegarde tous les joueurs.
        /// </summary>
        /// <param name="joueurs">La liste de joueurs a sauvegarder</param>
        public static void Save(List<Joueur> joueurs)
        {
            try
            {
                using (Stream stream = File.Open(PATH_TO_DAT_FILE, FileMode.Create))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                    if (joueurs.Any())
                    {
                        bformatter.Serialize(stream, joueurs);
                    }
                }
            }
            catch (ArgumentException)
            {
                MessageBox.Show("Le fichier est invalide.");
            }
            catch (DirectoryNotFoundException)
            {
                MessageBox.Show("Répertoire introuvable");
            }
            catch (FileNotFoundException)
            {
                MessageBox.Show("Le fichier n'existe pas.");
            }
            catch (IOException)
            {
                MessageBox.Show("Problème lors de la lecture du fichier.");
            }
            catch (System.Runtime.Serialization.SerializationException e)
            {
                MessageBox.Show(e.Message);
            }
        }
开发者ID:chef-marmotte,项目名称:jeu-blackjack,代码行数:39,代码来源:JoueurParser.cs


示例11: TestSerializeSchemaPropertyValueCollection

		public void TestSerializeSchemaPropertyValueCollection()
		{
			System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
			System.IO.MemoryStream ms = new System.IO.MemoryStream();
			SchemaPropertyValueCollection obj1 = new SchemaPropertyValueCollection();

			SCGroup group = SCObjectGenerator.PrepareGroupObject();

			foreach (string key in group.Properties.GetAllKeys())
			{
				obj1.Add(group.Properties[key]);
			}

			bf.Serialize(ms, obj1);
			ms.Seek(0, System.IO.SeekOrigin.Begin);

			var obj2 = (SchemaPropertyValueCollection)bf.Deserialize(ms);

			Assert.AreEqual(obj1.Count, obj2.Count);

			var keys1 = obj1.GetAllKeys();

			foreach (var key in keys1)
			{
				Assert.IsTrue(obj2.ContainsKey(key));
				Assert.AreEqual(obj1[key].StringValue, obj2[key].StringValue);
			}
		}
开发者ID:jerryshi2007,项目名称:AK47Source,代码行数:28,代码来源:SerializableTest.cs


示例12: Load

        private const string PATH_TO_DAT_FILE = "./joueurs.dat"; //Répertoire courrant.

        #endregion Fields

        #region Methods

        /// <summary>
        /// Charge un fichier contenant tous les joueurs.
        /// </summary>
        /// <returns>La liste de joueurs s'il y en a, sinon null.</returns>
        public static List<Joueur> Load()
        {
            List<Joueur> joueurs = null;

            if (File.Exists(PATH_TO_DAT_FILE))
            {
                try
                {
                    using (Stream stream = File.Open(PATH_TO_DAT_FILE, FileMode.Open))
                    {
                        stream.Position = 0;
                        var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        joueurs = (List<Joueur>)bformatter.Deserialize(stream);
                    }
                }
                catch (ArgumentException)
                {
                    MessageBox.Show("Le fichier est invalide.");
                }
                catch (DirectoryNotFoundException)
                {
                    MessageBox.Show("Répertoire introuvable");
                }
                catch (FileNotFoundException)
                {
                    MessageBox.Show("Le fichier n'existe pas.");
                }
                catch (IOException)
                {
                    MessageBox.Show("Problème lors de la lecture du fichier.");
                }
            }

            return joueurs;
        }
开发者ID:chef-marmotte,项目名称:jeu-blackjack,代码行数:45,代码来源:JoueurParser.cs


示例13: Compress

        public static byte[] Compress(System.Runtime.Serialization.ISerializable obj)
        {

            //    infile.Length];
            IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            formatter.Serialize(ms, obj);
            byte[] buffer = ms.ToArray();
            //Stream stream = new MemoryStream();

            //    FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
            //MyObject obj = (MyObject)formatter.Deserialize(stream);
            //stream.Close();



            // Use the newly created memory stream for the compressed data.
            MemoryStream msOutput = new MemoryStream();
            GZipStream compressedzipStream = new GZipStream(msOutput, CompressionMode.Compress, true);

            compressedzipStream.Write(buffer, 0, buffer.Length);
            // Close the stream.
            compressedzipStream.Close();
            return msOutput.ToArray();

        }
开发者ID:ramilexe,项目名称:tsdfamilia,代码行数:26,代码来源:CompressClass.cs


示例14: SettingManager

        public SettingManager()
        {
            _cookieFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            _imageHashSerializer = new System.Xml.Serialization.XmlSerializer(typeof(HashSet<string>));

            //設定ファイル読み込み
            EmailAddress = GPlusImageDownloader.Properties.Settings.Default.EmailAddress;
            Password = GPlusImageDownloader.Properties.Settings.Default.Password;
            ImageSaveDirectory = new System.IO.DirectoryInfo(
                string.IsNullOrEmpty(GPlusImageDownloader.Properties.Settings.Default.ImageSaveDirectory)
                ? Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + "\\testFolder"
                : GPlusImageDownloader.Properties.Settings.Default.ImageSaveDirectory);
            Cookies = DeserializeCookie();
            ImageHashList = DeserializeHashes();

            if (!ImageSaveDirectory.Exists)
                try
                {
                    ImageSaveDirectory.Create();
                    ImageSaveDirectory.Refresh();
                }
                catch (System.IO.IOException)
                { IsErrorNotFoundImageSaveDirectory = !ImageSaveDirectory.Exists; }
            else
                IsErrorNotFoundImageSaveDirectory = false;
        }
开发者ID:namoshika,项目名称:GPlusAutoImageDownloader,代码行数:26,代码来源:SettingManager.cs


示例15: Update

 /// <summary>
 /// Update a business object.
 /// </summary>
 /// <param name="request">The request parameter object.</param>
 public byte[] Update(byte[] req)
 {
   var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
   Csla.Server.Hosts.WcfBfChannel.UpdateRequest request;
   using (var buffer = new System.IO.MemoryStream(req))
   {
     request = (Csla.Server.Hosts.WcfBfChannel.UpdateRequest)formatter.Deserialize(buffer);
   }
   Csla.Server.DataPortal portal = new Csla.Server.DataPortal();
   object result;
   try
   {
     result = portal.Update(request.Object, request.Context);
   }
   catch (Exception ex)
   {
     result = ex;
   }
   var response = new WcfResponse(result);
   using (var buffer = new System.IO.MemoryStream())
   {
     formatter.Serialize(buffer, response);
     return buffer.ToArray();
   }
 }
开发者ID:BiYiTuan,项目名称:csla,代码行数:29,代码来源:WcfBfPortal.cs


示例16: TestBooleanQuerySerialization

        public void TestBooleanQuerySerialization()
        {
            Lucene.Net.Search.BooleanQuery lucQuery = new Lucene.Net.Search.BooleanQuery();

            lucQuery.Add(new Lucene.Net.Search.TermQuery(new Lucene.Net.Index.Term("field", "x")), Occur.MUST);

            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            bf.Serialize(ms, lucQuery);
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            Lucene.Net.Search.BooleanQuery lucQuery2 = (Lucene.Net.Search.BooleanQuery)bf.Deserialize(ms);
            ms.Close();

            Assert.AreEqual(lucQuery, lucQuery2, "Error in serialization");

            Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(dir, true);

            int hitCount = searcher.Search(lucQuery, 20).TotalHits;

            searcher.Close();
            searcher = new Lucene.Net.Search.IndexSearcher(dir, true);

            int hitCount2 = searcher.Search(lucQuery2, 20).TotalHits;

            Assert.AreEqual(hitCount, hitCount2, "Error in serialization - different hit counts");
        }
开发者ID:Cefa68000,项目名称:lucenenet,代码行数:26,代码来源:TestSerialization.cs


示例17: ObjectToByteArray

 /// <summary>
 /// 扩展方法:将对象序列化为二进制byte[]数组-通过系统提供的二进制流来完成序列化
 /// </summary>
 /// <param name="Obj">待序列化的对象</param>
 /// <param name="ThrowException">是否抛出异常</param>
 /// <returns>返回结果</returns>
 public static byte[] ObjectToByteArray(this object Obj, bool ThrowException)
 {
     if (Obj == null)
     {
         return null;
     }
     else
     {
         try
         {
             System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             System.IO.MemoryStream stream = new System.IO.MemoryStream();
             formatter.Serialize(stream, Obj);
             return stream.ToArray();
         }
         catch (System.Exception ex)
         {
             if (ThrowException)
             {
                 throw ex;
             }
             else
             {
                 return null;
             }
         }
     }
 }
开发者ID:JBTech,项目名称:Dot.Utility,代码行数:34,代码来源:ObjectToByteArrayExtension.cs


示例18: RecreateBinFiles

        public void RecreateBinFiles()
        {
            DataTable testOutput;

            using (
                var connection =
                    new SqlConnection("Server=localhost;Database=AdventureWorks2012;Trusted_Connection=True;"))
            {
                var qryText = new StringBuilder();
                qryText.AppendLine(QRY);
                testOutput = new DataTable();
                using (var command = connection.CreateCommand())
                {
                    command.Connection.Open();
                    command.CommandType = CommandType.Text;
                    command.CommandText = qryText.ToString();

                    using (var da = new SqlDataAdapter { SelectCommand = command })
                        da.Fill(testOutput);
                    command.Connection.Close();
                }
            }

            var binSer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            using (var ms = new MemoryStream())
            {
                binSer.Serialize(ms, testOutput);
                using (var binWtr = new BinaryWriter(File.Open(@"C:\Projects\31g\trunk\Code\NoFuture.Tests\Sql\DataTable.Person.bin", FileMode.Create)))
                    binWtr.Write(ms.GetBuffer());
            }
        }
开发者ID:nofuture-git,项目名称:31g,代码行数:32,代码来源:TestExportTo.cs


示例19: BinaryStreamFromObject

 /// <summary>
 /// Uses the System formatters to save the MapXtreme objects in the session state as a binary blob.
 /// </summary>
 /// <param name="ser">A serializable object.</param>
 /// <remarks>If you simply send it to the Session state it will automatically extract itself the next time the user accesses the site. This allows you to deserialize certain objects when you want them. This method takes an object and saves it's binary stream.</remarks>
 /// <returns>A byte array to hold binary format version of object you passed in.</returns>
 public static byte[] BinaryStreamFromObject(object ser)
 {
     System.IO.MemoryStream memStr = new System.IO.MemoryStream();
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     formatter.Serialize(memStr, ser);
     return memStr.GetBuffer();
 }
开发者ID:rupeshkumar399,项目名称:seemapcell,代码行数:13,代码来源:ManualSerializer.cs


示例20: LoadFields

 public static void LoadFields()
 {
     IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     Stream stream = new FileStream("FieldList.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
     FieldList = (List<Field>)formatter.Deserialize(stream);
     stream.Close();
 }
开发者ID:OrigamiSamurai,项目名称:HeroBarn,代码行数:7,代码来源:ControlEngine.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Serialization.SerializationInfo类代码示例发布时间:2022-05-24
下一篇:
C# Serialization.DataContractSerializer类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap