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


C# Binary.BinaryFormatter类代码示例

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


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

示例1: ToBytes

 /// <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();
 }
开发者ID:burstinair,项目名称:burst.net,代码行数:12,代码来源:NetUtil.cs

示例2: Show

        protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider provider)
        {
            using (Form form1 = new Form())
            {
                form1.Text = "FormCollection Visualizer";
                form1.StartPosition = FormStartPosition.WindowsDefaultLocation;
                form1.SizeGripStyle = SizeGripStyle.Auto;
                form1.ShowInTaskbar = false;
                form1.ShowIcon = false;

                DataTable dt;

                using (Stream stream = provider.GetData())
                {
                    BinaryFormatter bformatter = new BinaryFormatter();

                    dt = (DataTable)bformatter.Deserialize(stream);

                    stream.Close();
                }

                DataGridView gridView = new DataGridView();
                gridView.Dock = DockStyle.Fill;

                form1.Controls.Add(gridView);

                gridView.DataSource = dt;

                windowService.ShowDialog(form1);
            }
        }
开发者ID:piotrosz,项目名称:DebugVisualizersCollection,代码行数:31,代码来源:FormCollectionVisualizer.cs

示例3: LoadState

        /// <summary>
        /// Opens a bin-file and converts it to a SaveFile that gets returned.
        /// </summary>
        public SaveFile LoadState()
        {

            SaveFile tmpFile = new SaveFile();

            Stream fileStreamer;
            BinaryFormatter bf;

            try
            {
                using(fileStreamer = File.Open("state.bin", FileMode.Open))
                {
                    bf = new BinaryFormatter();
                    var tmpState = bf.Deserialize(fileStreamer);
                    tmpFile = (SaveFile)tmpState;

                    return tmpFile;
                }
            }

            catch
            {
                return tmpFile;
            }       
        }
开发者ID:korsback,项目名称:calculator,代码行数:28,代码来源:SaveLoad.cs

示例4: SerializeToStream

 public static MemoryStream SerializeToStream(object o)
 {
     MemoryStream stream = new MemoryStream();
     IFormatter formatter = new BinaryFormatter();
     formatter.Serialize(stream, o);
     return stream;
 }
开发者ID:Rophuine,项目名称:ExtendedEnum,代码行数:7,代码来源:SerializationTests.cs

示例5: TestVFSException

        public void TestVFSException()
        {
            var e1 = new VFSException();
            Assert.IsTrue(e1.Message.Contains("VFSException"));

            var e2 = new VFSException("a");
            Assert.AreEqual("a", e2.Message);

            var e3 = new VFSException("a", new Exception("x"));
            Assert.AreEqual("a", e3.Message);
            Assert.AreEqual("x", e3.InnerException.Message);

            using (var ms = new MemoryStream())
            {
                var serializer = new BinaryFormatter();
                serializer.Serialize(ms, e3);
                ms.Seek(0, SeekOrigin.Begin);

                var e4 = serializer.Deserialize(ms) as VFSException;

                Assert.IsNotNull(e4);
                Assert.AreEqual("a", e4.Message);
                Assert.AreEqual("x", e4.InnerException.Message);
            }
        }
开发者ID:RainsSoft,项目名称:VFSPrototype,代码行数:25,代码来源:ExceptionsTest.cs

示例6: CreateCrashDump

        /// <summary>
        /// Creates the crash dump.
        /// </summary>
        public static void CreateCrashDump()
        {
            if (!Directory.Exists("Dumps"))
                Directory.CreateDirectory("Dumps");

            Log.Info("Creating crash dump...");

            try
            {
                using (var fs =
                    File.Open(
                        Path.Combine(Environment.CurrentDirectory, "Dumps",
                                     string.Format("{0}.acd", DateTime.Now.ToString("yyyy_MM_dd_HH_mm"))),
                        FileMode.Create))
                {

                    var formatter = new BinaryFormatter();

                    var bot = AlarisBot.Instance;

                    formatter.Serialize(fs, bot);

                }
            }
            catch(Exception x)
            {
                Log.Fatal("Failed to write crash dump. ({0})", x);
                return;
            }

            Log.Info("Crash dump created.");
        }
开发者ID:Jakosa,项目名称:alaris,代码行数:35,代码来源:CrashDumper.cs

示例7: TestRoundTripElementSerialisation

        public void TestRoundTripElementSerialisation()
        {
            // Use a BinaryFormatter or SoapFormatter.
            IFormatter formatter = new BinaryFormatter();
            //IFormatter formatter = new SoapFormatter();

            // Create an instance of the type and serialize it.
            var elementId = new SerializableId
            {
                IntID = 42,
                StringID = "{BE507CAC-7F23-43D6-A2B4-13F6AF09046F}"
            };

            //Serialise to a test memory stream
            var m = new MemoryStream();
            formatter.Serialize(m, elementId);
            m.Flush();

            //Reset the stream
            m.Seek(0, SeekOrigin.Begin);

            //Readback
            var readback = (SerializableId)formatter.Deserialize(m);

            Assert.IsTrue(readback.IntID == 42);
            Assert.IsTrue(readback.StringID.Equals("{BE507CAC-7F23-43D6-A2B4-13F6AF09046F}"));
        }
开发者ID:TheChosen0ne,项目名称:Dynamo,代码行数:27,代码来源:RevitServicesTests.cs

示例8: 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

示例9: Save

 public void Save(string path)
 {
     BinaryFormatter binaryFormatter = new BinaryFormatter();
     FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
     binaryFormatter.Serialize(fileStream, this);
     fileStream.Close();
 }
开发者ID:swoopyy,项目名称:Turing-to-post,代码行数:7,代码来源:SaveClass.cs

示例10: talk

 public bool talk()
 {
     try
     {
         if (null != sendPro)
         {
             TcpClient client = new TcpClient();
             client.Connect(IPAddress.Parse(ClientInfo.confMap.value(strClientConfKey.ServerIP)),
                 int.Parse(ClientInfo.confMap.value(strClientConfKey.ServerPort)));
             NetworkStream ns = client.GetStream();
             IFormatter formatter = new BinaryFormatter();
             formatter.Serialize(ns, sendPro);
             reseivePro = (Protocol)formatter.Deserialize(ns);
             client.Close();
         }
         else
         {
             return false;
         }
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
开发者ID:budlion,项目名称:DSTPRJ,代码行数:26,代码来源:NsTalk.cs

示例11: LoadFromFile

 public void LoadFromFile(string aPath)
 {
     using (Stream stream = File.Open(aPath, FileMode.Open))
     {
         Clear();
         BinaryFormatter bin = new BinaryFormatter();
         Configuration deserialized = bin.Deserialize(stream) as Configuration;
         foreach (var prof in deserialized.Professors)
         {
             Professors.Add(prof);
         }
         foreach (var room in deserialized.Rooms)
         {
             Rooms.Add(room);
         }
         foreach (var group in deserialized.Groups)
         {
             Groups.Add(group);
         }
         foreach (var course in deserialized.Courses)
         {
             Courses.Add(course);
         }
         foreach (var constraint in deserialized.Constraints)
         {
             Constraints.Add(constraint);
         }
         foreach (var classcont in deserialized.Classes)
         {
             Classes.Add(classcont.Key, classcont.Value);
         }
     }
 }
开发者ID:mitelinko,项目名称:Maxim-s---Mitko-s-project-for-TP,代码行数:33,代码来源:Configuration.cs

示例12: SetValue

        private bool SetValue(object currentValue, out object newValue)
        {
            DTE dte = this.GetService<DTE>(true);
            IDictionaryService dictionaryService = (IDictionaryService)ServiceHelper.GetService(this, typeof(IDictionaryService));

            try
            {
                if (!string.IsNullOrEmpty(RecipeArgument))
                {

                    string argumentvalue = dictionaryService.GetValue(RecipeArgument).ToString();
                    Version v = new Version(argumentvalue);
                    if (v != null)
                    {
                        byte[] bytes;
                        long length = 0;
                        MemoryStream ws = new MemoryStream();
                        BinaryFormatter sf = new BinaryFormatter();
                        sf.Serialize(ws, v);
                        length = ws.Length;
                        bytes = ws.GetBuffer();
                        newValue = Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None);
                        return true;
                    }
                }
            }
            catch { }
            //string projectId = currentProject.

            newValue = "";
            return false;
        }
开发者ID:sunday-out,项目名称:SharePoint-Software-Factory,代码行数:32,代码来源:SerializedVersionProvider.cs

示例13: OnSaveData

        public override void OnSaveData()
        {
            LoggerUtilities.Log("Saving road names");

            BinaryFormatter binaryFormatter = new BinaryFormatter();
            MemoryStream memoryStream = new MemoryStream();

            try
            {
                RoadContainer[] roadNames = RoadNameManager.Instance().Save();

                if (roadNames != null)
                {
                    binaryFormatter.Serialize(memoryStream, roadNames);
                    serializableDataManager.SaveData(dataKey, memoryStream.ToArray());
                    LoggerUtilities.Log("Road names have been saved!");
                }
                else
                {
                    LoggerUtilities.LogWarning("Couldn't save road names, as the array is null!");
                }
            }
            catch (Exception ex)
            {
                LoggerUtilities.LogException(ex);
            }
            finally
            {
                memoryStream.Close();
            }
        }
开发者ID:tony56a,项目名称:RoadNamer,代码行数:31,代码来源:RoadNamerSerialiser.cs

示例14: Save

 /// <summary>
 /// Save the specified object.
 /// </summary>
 /// <param name="filename">The filename to save to.</param>
 /// <param name="obj">The object to save.</param>
 public static void Save(string filename, object obj)
 {
     Stream s = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None);
     var b = new BinaryFormatter();
     b.Serialize(s, obj);
     s.Close();
 }
开发者ID:johannsutherland,项目名称:encog-dotnet-core,代码行数:12,代码来源:SerializeObject.cs

示例15: Encode

 /// <summary>
 /// Encode value into a stream
 /// </summary>
 /// <param name="value">Value to encode</param>
 /// <param name="destination">Stream to write the serialized object to.</param>
 public void Encode(object value, Stream destination)
 {
     if (value == null) throw new ArgumentNullException("value");
     if (destination == null) throw new ArgumentNullException("destination");
     var formatter = new BinaryFormatter();
     formatter.Serialize(destination, value);
 }
开发者ID:2594636985,项目名称:griffin.networking,代码行数:12,代码来源:BinaryFormatterCodec.cs


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