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

C# Binary.BinaryFormatter类代码示例

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

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



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


示例16: Constructor_InitializesSerializer

        public void Constructor_InitializesSerializer()
        {
            serializer = new BinaryFormatter();

            Assert.IsTrue(serverStream.IsConnected);
            Assert.IsTrue(clientStream.IsConnected);
        }
开发者ID:jango2015,项目名称:VS-Macros,代码行数:7,代码来源:PipeTests.cs


示例17: Save

        public void Save(TelemetryLap lap, string fileName)
        {
            try
            {

                if (lap == null)
                    return;

                if (File.Exists(fileName))
                    File.Delete(fileName);

                using (Stream stream = File.Open(fileName, FileMode.Create))
                {
                    var binFormatter = new BinaryFormatter();
                    binFormatter.Serialize(stream, lap);
                    stream.Close();
                }
            } catch (Exception ex)
            {
                #if DEBUG
                logger.Error("Count not save binary telemetry lap", ex);
            #endif
                throw ex;
            }
        }
开发者ID:tpastor,项目名称:F1_201x_TelemetrySystem,代码行数:25,代码来源:BinaryTelemetryLapRepository.cs


示例18: Run

        public int Run()
        {
            try
            {
                Stream codeStream = LocateCode();
                var formatter = new BinaryFormatter();
                var reader = new ScriptEngine.Compiler.ModulePersistor(formatter);
                var moduleHandle = reader.Read(codeStream);
                var engine = new HostedScriptEngine();
                var src = new BinaryCodeSource(moduleHandle);

                var process = engine.CreateProcess(this, moduleHandle, src);
                return process.Start();
                
            }
            catch (ScriptInterruptionException e)
            {
                return e.ExitCode;
            }
            catch (Exception e)
            {
                this.ShowExceptionInfo(e);
                return 1;
            }

        }
开发者ID:Shemetov,项目名称:OneScript,代码行数:26,代码来源:StandaloneProcess.cs


示例19: saveToFile

 public static void saveToFile(Mesh mesh, string _filename)
 {
     Stream stream = File.Open(_filename, FileMode.Create);
     BinaryFormatter bFormatter = new BinaryFormatter();
     bFormatter.Serialize(stream, mesh);
     stream.Close();
 }
开发者ID:sinushawa,项目名称:ROD,代码行数:7,代码来源:Mesh.cs


示例20: ManufacturersForm

        public ManufacturersForm(GXManufacturerCollection manufacturers, string selectedManufacturer)
        {
            InitializeComponent();
            NameCH.Width = -2;
            UpdateValues();
            InactivityModeTB.Enabled = StartProtocolTB.Enabled = NameTB.Enabled = ManufacturerIdTB.Enabled = UseLNCB.Enabled = UseIEC47CB.Enabled = false;
            ManufacturersOriginal = manufacturers;

            //Create clone from original items.
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, manufacturers);
            ms.Position = 0;
            Manufacturers = (GXManufacturerCollection)bf.Deserialize(ms);
            ms.Close();
            bool bSelected = false;
            foreach (GXManufacturer it in Manufacturers)
            {
                if (!it.Removed)
                {
                    ListViewItem item = AddManufacturer(it);
                    if (it.Identification == selectedManufacturer)
                    {
                        bSelected = item.Selected = true;
                    }
                }
            }
            //Select first item
            if (ManufacturersList.Items.Count != 0 && !bSelected)
            {
                ManufacturersList.Items[0].Selected = true;
            }
        }
开发者ID:Gurux,项目名称:GXDLMSDirector,代码行数:33,代码来源:ManufacturersForm.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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