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


C# BinaryFormatter.Serialize方法代码示例

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


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

示例1: Main

        static void Main(string[] args)
        {
            Insect i = new Insect("Meadow Brow", 12);
            Stream sw = File.Create("Insects.bin");
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(sw, i);
            sw.Close();

            ArrayList box = new ArrayList();
            box.Add(new Insect("Marsh Fritillarry", 34));
            box.Add(new Insect("Speckled Wood", 56));
            box.Add(new Insect("Milkweed", 78));

            sw = File.Open("Insects.bin", FileMode.Append);
            bf.Serialize(sw, box);
            sw.Close();

            Stream sr = File.OpenRead("Insects.bin");
            Insect j = (Insect)bf.Deserialize(sr);
            Console.WriteLine(j);

            ArrayList bag = (ArrayList)bf.Deserialize(sr);
            sr.Close();

            foreach (Insect k in bag)
            {
                Console.WriteLine(k);
            }

            Console.ReadLine();
        }
开发者ID:GGammu,项目名称:InsideCSharp,代码行数:31,代码来源:Program.cs

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

示例3: StreamQueryInfo

        /// <summary>
        /// This method is called from the QueryVisualizer to copy the following data to the stream:
        /// 1. The query expression as string
        /// 2. SQL query text(s) / parameters
        /// 3. Connection string
        /// </summary>
        /// <param name="query"> The query exression to visualize </param>
        /// <param name="outgoingData"> The stream used for marshalling to the visualizer </param>
        /// 
        public static void StreamQueryInfo(DataContext dataContext, IQueryable query, Stream outgoingData)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            if (dataContext == null) {
                formatter.Serialize(outgoingData, "None");
                formatter.Serialize(outgoingData, "No datacontext provided.");
                return;
            }
            Expression expr = query.Expression;
            if (expr == null) {
                formatter.Serialize(outgoingData, "None");
                formatter.Serialize(outgoingData, "Expression of the query is empty.");
                return;
            }
            formatter.Serialize(outgoingData, expr.ToString());

            try {
                SqlQueryInfo qi = new SqlQueryInfo(GetFullQueryInfo(dataContext, query));
                qi.serialize(outgoingData);
            } catch (Exception ex) {
                outgoingData.Position = 0;
                formatter.Serialize(outgoingData, "None");
                formatter.Serialize(outgoingData, string.Format(CultureInfo.CurrentUICulture, "Exception while serializing the query:\r\n{0}", ex.Message));
                return;
            }

            IDbConnection conn = dataContext.Connection;
            string connectionString = conn.ConnectionString;
            //Need to check for |DataDirectory| token in the connection string and replace with absolute path to allow
            if (connectionString.Contains("|DataDirectory|")) {
                connectionString = conn.ConnectionString.Replace(@"|DataDirectory|\", AppDomain.CurrentDomain.BaseDirectory);
            }
            //the Linq To Sql Query Visualizer to use the same connection string.
            formatter.Serialize(outgoingData, connectionString);
        }
开发者ID:jamesmaxwell,项目名称:DesignPatternDemo,代码行数:44,代码来源:LinqToSqlQueryVisualizer.cs

示例4: InitGroupTable

 public Dictionary<GroupRow, int> InitGroupTable()
 {
     _groupsCollection.Clear();
     foreach (var faculty in EnumDecoder.StringToFaculties)
     {
         try
         {
             Configuration config = (App.Current as App).config;
             using (TcpClient eClient = new TcpClient(config.IP.ToString(), config.Port))
             {
                 using (NetworkStream writerStream = eClient.GetStream())
                 {
                     MSG message = new MSG();
                     message.stat = STATUS.GET_GROUP_BY_FACULTY;
                     BinaryFormatter formatter = new BinaryFormatter();
                     formatter.Serialize(writerStream, message); 
                     formatter.Serialize(writerStream, faculty.Value);
                     bool fl = (bool)formatter.Deserialize(writerStream);
                     if (fl)
                     {
                         foreach (var group in (Dictionary<string, int>)formatter.Deserialize(writerStream))
                         {
                             _groupsCollection.Add(new GroupRow(group.Key, faculty.Key), group.Value);
                         }
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message, "Помилка", MessageBoxButton.OK, MessageBoxImage.Error);
         }
     }
     return _groupsCollection;
 }
开发者ID:senioroman4uk,项目名称:courseWork,代码行数:35,代码来源:GroupControlPage.xaml.cs

示例5: sendAndReceiveHello

        public void sendAndReceiveHello(Peer neighbor, Ring ring)
        {
            byte[] message = new byte[Constants.WRITEBUFFSIZE];
            byte[] reply = new byte[Constants.READBUFFSIZE];
            MemoryStream stream;

            try
            {
                User user = User.getInstance();
                BinaryFormatter serializer = new BinaryFormatter();
                stream = new MemoryStream(message);

                NetLib.insertEntropyHeader(serializer, stream);

                RingInfo ringInfo = user.findRingInfo(ring.ringID);
                serializer.Serialize(stream, Constants.MessageTypes.MSG_HELLO);
                serializer.Serialize(stream, ring.ringID);
                serializer.Serialize(stream, ringInfo.token);
                serializer.Serialize(stream, new Peer(user.node, user.publicUserInfo, ringInfo.IE));

                reply = NetLib.communicate(neighbor.node.syncCommunicationPoint, message, true);

                Debug.Assert(reply != null, "Neighbor did not reply to Hello");

                BinaryFormatter deserializer = new BinaryFormatter();
                stream = new MemoryStream(reply);
                NetLib.bypassEntropyHeader(deserializer, stream);
                Constants.MessageTypes replyMsg = (Constants.MessageTypes)deserializer.Deserialize(stream);
                switch(replyMsg)
                {
                    case Constants.MessageTypes.MSG_HELLO:
                        uint ringID = (uint)deserializer.Deserialize(stream);
                        if(ringID != ring.ringID)
                            return;

                        ulong token = (ulong)deserializer.Deserialize(stream);
                        Peer peer = (Peer)deserializer.Deserialize(stream);

                        IPEndPoint neighborIPEndPoint = peer.node.syncCommunicationPoint;
                        if(!neighborIPEndPoint.Address.Equals(neighbor.node.syncCommunicationPoint.Address))
                            //REVISIT: alert security system
                            return;

                        neighbor.node.syncCommunicationPoint = neighborIPEndPoint;
                        neighbor.node.asyncCommunicationPoint = peer.node.asyncCommunicationPoint;
                        neighbor.IE = peer.IE;
                        break;
                    case Constants.MessageTypes.MSG_DISCONNECT:
                        neighbor.IE = null;
                        break;
                    default:
                        neighbor.IE = null;
                        break;
                }
            }
            catch (Exception e)
            {
                int x = 2;
            }
        }
开发者ID:beghbali,项目名称:ResourceRingEntropyNetwork,代码行数:60,代码来源:NeighborProxy.cs

示例6: Main

        public static void Main()
        {
            //Tworzenie Obiektów do serializacji
               Klasa ob = new Klasa ("ob1", 1);
               Klasa ob2 = new Klasa ("ob2", 5);

               Console.WriteLine ("Przed serializacją");
               ob.print ();
               ob2.print ();

               BinaryFormatter Formater = new BinaryFormatter();
               FileStream str = new FileStream ("Serial.bin", FileMode.Create, FileAccess.Write);

               //Serializowanie do strumienia
               Formater.Serialize (str, ob);
               Formater.Serialize (str, ob2);
               str.Close ();

               //Deserializacja
               str = new FileStream ("Serial.bin", FileMode.Open, FileAccess.Read);
               Klasa w = (Klasa)Formater.Deserialize (str);
               Klasa w2 = (Klasa)Formater.Deserialize (str);

               Console.WriteLine ("Po serializacji");
               w.print ();
               w2.print ();
               Console.ReadKey ();
        }
开发者ID:CodersCommunity,项目名称:csharp-materialy,代码行数:28,代码来源:SerializacjaDopliku.cs

示例7: logoff

        public void logoff(User user)
        {
            byte[] message = new byte[Constants.WRITEBUFFSIZE];
            MemoryStream stream = null;

            if(!loggedIn)
                return;
            try
            {
                //Serialize data in memory so you can send them as a continuous stream
                BinaryFormatter serializer = new BinaryFormatter();
                stream = new MemoryStream(message);
                serializer.Serialize(stream, Constants.MessageTypes.MSG_LOGOFF);
                serializer.Serialize(stream, this.loginCallbackTable.getSessionID());
                serializer.Serialize(stream, user.publicUserInfo);
                serializer.Serialize(stream, user.privateUserInfo);
                serializer.Serialize(stream, user.node);
                NetLib.communicate(Constants.SERVER,message, false);
                stream.Close();
            }
            catch
            {
                return;
            }
            finally
            {
                loggedIn = false;
            }
        }
开发者ID:beghbali,项目名称:ResourceRingEntropyNetwork,代码行数:29,代码来源:Login.cs

示例8: RegisterButton_Click

        private void RegisterButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (PasswordBox.Password != PasswordRepeatBox.Password)
                    throw new Exception("Паролі не співпадають");
                Instructor instructor = new Instructor(LoginBox.Text, PasswordBox.Password, FirstNameBox.Text, LastNameBox.Text,
                    SecondNameBox.Text);
                Configuration config = (App.Current as App).config;
                using (TcpClient eClient = new TcpClient(config.IP.ToString(), config.Port))
                {
                    using (NetworkStream writerStream = eClient.GetStream())
                    {
                        MSG message = new MSG();
                        message.stat = STATUS.ADD_INSTRUCTOR;
                        BinaryFormatter formatter = new BinaryFormatter();
                        formatter.Serialize(writerStream, message);
                        formatter.Serialize(writerStream, instructor);
                        bool fl = (bool)formatter.Deserialize(writerStream);
                        if (!fl)
                            MessageBox.Show("Помилка додавання облікового запису");
                        else
                        {
                            NavigationService nav = NavigationService.GetNavigationService(this);
                            nav.Navigate(new System.Uri("StartPage.xaml", UriKind.RelativeOrAbsolute));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
开发者ID:senioroman4uk,项目名称:courseWork,代码行数:35,代码来源:RegisterPage.xaml.cs

示例9: Store

        public int Store(string fileName)
        {
            int errors = 0;
            Stream str = null;
            try
            {
                str = File.Open(fileName, FileMode.Create, FileAccess.Write);
                BinaryFormatter formatter = new BinaryFormatter();


                formatter.Serialize(str, _package.Header);

                foreach (var item in _package.Content)
                {
                    _package.Header.SetPosition(item.Key, str.Position);
                    formatter.Serialize(str, item.Value);
                }
                str.Seek(0, SeekOrigin.Begin);
                //rewrite header with real positions
                formatter.Serialize(str, _package.Header);
                str.Close();
            }
            catch (Exception e)
            {
                throw new Exception("Error writing Xbim file", e);
            }
            finally
            {
                if (str != null) str.Close();
            }
            return errors;
        }
开发者ID:Artoymyp,项目名称:XbimEssentials,代码行数:32,代码来源:XbimOutputStream.cs

示例10: ReReadFiles

        private void ReReadFiles()
        {
            FilesGrid.Items.Clear();
            try
            {
                Configuration config = (App.Current as App).config;
                using (TcpClient eClient = new TcpClient(config.IP.ToString(), config.Port))
                {
                    using (NetworkStream writerStream = eClient.GetStream())
                    {
                        MSG message = new MSG();
                        message.stat = STATUS.GET_FILES;
                        BinaryFormatter formatter = new BinaryFormatter();
                        formatter.Serialize(writerStream, message);
                        formatter.Serialize(writerStream, _eventId);
                        formatter.Serialize(writerStream, false);
                        _files = (Dictionary<string, string>)formatter.Deserialize(writerStream);
                        foreach (var file in _files)
                        {
                            FilesGrid.Items.Add(new FileRow(file.Key, "Викладач"));
                        }
                    }
                }

            }
            catch (Exception)
            {
                MessageBox.Show("Помилка додавання файлу");
            }
        }
开发者ID:senioroman4uk,项目名称:courseWork,代码行数:30,代码来源:FileControlWindow.xaml.cs

示例11: Post

 public async Task Post(string endpoint, object data, NameValueCollection headers)
 {
     if (endpoint == "accounts/login")
     {
         var cacheFileName = Path.Combine(_cacheDir, "accountslogin_");
         if (!File.Exists(cacheFileName))
         {
             await _decorated.Post(endpoint, data, headers);
             using (var stream = File.OpenWrite(cacheFileName))
             {
                 var formatter = new BinaryFormatter();
                 formatter.Serialize(stream, Cookies);
                 formatter.Serialize(stream, headers);
             }
         }
         else if (headers != null)
         {
             foreach (string key in _headers)
             {
                 headers[key] = _headers[key];
             }
         }
     }
     else
     {
         Debug.WriteLine("Skip POST to " + endpoint);
     }
 }
开发者ID:NathanBaulch,项目名称:FitBot,代码行数:28,代码来源:CachedWebRequestDecorator.cs

示例12: receiveAndSendHello

        public void receiveAndSendHello(RingInfo ringInfo, Peer peer, Neighbor neighbor, 
            BinaryWriter writer)
        {
            if(!peer.node.syncCommunicationPoint.Address.Equals(neighbor.peer.node.syncCommunicationPoint.Address))
                //REVISIT: alert security system
                return;

            neighbor.peer.node.syncCommunicationPoint = peer.node.syncCommunicationPoint;
            neighbor.peer.node.asyncCommunicationPoint = peer.node.asyncCommunicationPoint;
            neighbor.peer.IE = peer.IE;

            byte[] message = new byte[Constants.WRITEBUFFSIZE];
            MemoryStream stream;

            try
            {
                User user = User.getInstance();
                BinaryFormatter serializer = new BinaryFormatter();
                stream = new MemoryStream(message);

                NetLib.insertEntropyHeader(serializer, stream);

                serializer.Serialize(stream, Constants.MessageTypes.MSG_HELLO);
                serializer.Serialize(stream, ringInfo.ring.ringID);
                serializer.Serialize(stream, ringInfo.token);
                serializer.Serialize(stream, new Peer(user.node, user.publicUserInfo, ringInfo.IE));
                writer.Write(message);
                writer.Flush();
            }
            catch (Exception e)
            {
                int x = 2;
            }
        }
开发者ID:beghbali,项目名称:ResourceRingEntropyNetwork,代码行数:34,代码来源:NeighborProxy.cs

示例13: Main

        static void Main(string[] args)
        {
            string data = "This must be stored in a file.";

            FileStream fs = new FileStream("SerializedString.Data", FileMode.Create);

            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(fs, data);

            fs.Close();

            fs = new FileStream("SerializedDate.Data", FileMode.Create);

            bf.Serialize(fs, DateTime.Now);

            fs.Close();
            
            fs = new FileStream("SerializedDate.Data", FileMode.Open);

            DateTime output = (DateTime)bf.Deserialize(fs);

            Console.WriteLine(output);

            fs.Close();
        }
开发者ID:oblivious,项目名称:Oblivious,代码行数:26,代码来源:Program.cs

示例14: ShowStudentInfo

        public static void ShowStudentInfo(int id, string ip, int port)
        {
            Student student = null;
            TcpClient eClient = new TcpClient();
            try
            {
                eClient = new TcpClient(ip, port);
                using (NetworkStream writerStream = eClient.GetStream())
                {
                    MSG message = new MSG();
                    message.stat = STATUS.GET_ACCOUNT_BY_ID;
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(writerStream, message);
                    formatter.Serialize(writerStream, id);
                    student = (Student)formatter.Deserialize(writerStream);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                eClient.Close();
            }

            if (student == null)
            {
                throw new ArgumentException(string.Format("Студента з id = {0} не iснує", id));
            }

            StudentInfoWindow sw = new StudentInfoWindow(string.Format("{0} {1} {2}", student.Lastname, student.Firstname, student.Patronymic),
                student.Group, student.Faculty, student.PhoneNumber, student.Email, student.Address, student.AverageMark);
            sw.ShowDialog();
        }
开发者ID:senioroman4uk,项目名称:courseWork,代码行数:35,代码来源:StudentInfo.cs

示例15: InvokeFunc

        /// <summary>
        /// Calls method with one parameter and result. Deserializes parameter and serialize result.
        /// </summary>
        /// <param name="type">Type containing method</param>
        /// <param name="methodName">Name of method to call</param>
        /// <param name="pipeName">Name of pipe to pass parameter and result</param>
        static void InvokeFunc(Type type, string methodName, string pipeName)
        {
            using (var pipe = new NamedPipeClientStream(pipeName))
            {

                pipe.Connect();

                var formatter = new BinaryFormatter();
                ProcessThreadParams pars;
                var lengthBytes = new byte[4];
                pipe.Read(lengthBytes, 0, 4);
                var length = BitConverter.ToInt32(lengthBytes, 0);

                var inmemory = new MemoryStream(length);
                var buf = new byte[1024];
                while (length != 0)
                {
                    var red = pipe.Read(buf, 0, buf.Length);
                    inmemory.Write(buf, 0, red);
                    length -= red;
                }
                inmemory.Position = 0;
                try
                {
                    AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
                      {
                          return type.Assembly;
                      };

                    pars = (ProcessThreadParams)formatter.Deserialize(inmemory);

                    var method = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, pars.Types, null);
                    if (method == null) throw new InvalidOperationException("Method is not found: " + methodName);

                    if (pars.Pipe != null)
                    {
                        var auxPipe = new NamedPipeClientStream(pars.Pipe);
                        auxPipe.Connect();

                        for (int i = 0; i < pars.Parameters.Length; i++)
                            if (pars.Parameters[i] is PipeParameter) pars.Parameters[i] = auxPipe;
                    }
                    object result = method.Invoke(pars.Target, pars.Parameters);

                    var outmemory = new MemoryStream();
                    formatter.Serialize(outmemory, ProcessThreadResult.Successeded(result));
                    outmemory.WriteTo(pipe);
                }
                catch (TargetInvocationException e)
                {
                    formatter.Serialize(pipe, ProcessThreadResult.Exception(e.InnerException));
                    throw e.InnerException;
                }
                catch (Exception e)
                {
                    formatter.Serialize(pipe, ProcessThreadResult.Exception(e));
                    throw;
                }
            }
        }
开发者ID:Rambalac,项目名称:ProcessThreads,代码行数:66,代码来源:ProcessThreadExecutor.cs


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