Deserialize() public method

public Deserialize ( Stream serializationStream ) : object
serializationStream Stream
return object
Beispiel #1
0
        static void Main(string[] args)
        {
            ///序列化:
            Person person = new Person();

            person.age    = 18;
            person.name   = "tom";
            person.secret = "i will not tell you";
            FileStream stream = new FileStream(@"C:\Users\Public\Desktop\person.xml", FileMode.Create);

            System.Runtime.Serialization.Formatters.Soap.SoapFormatter bFormat =
                new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
            //SoapFormatter bFormat = new SoapFormatter();
            bFormat.Serialize(stream, person);
            stream.Close();

            ///反序列化
            Person     person1 = new Person();
            FileStream stream1 = new FileStream(@"C:\Users\Public\Desktop\person.xml", FileMode.Open);

            System.Runtime.Serialization.Formatters.Soap.SoapFormatter bFormat1 =
                new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
            //SoapFormatter bFormat1 = new SoapFormatter();
            person1 = (Person)bFormat.Deserialize(stream1);
            //反序列化得到的是一个object对象.必须做下类型转换
            stream1.Close();
            Console.WriteLine(person1.age + person1.name + person1.secret);
            //结果为18tom.因为secret没有有被序列化.

            Console.ReadKey();
        }
 // on a different thread
 private void ReceiveDone(IAsyncResult ar)
 {
     byte[] got;
     try
     {   // at Form.Close time, the last one sometimes fails
         got = listener.EndReceive(ar, ref groupEP);
     }
     catch
     {
         return;
     }
     OnFreqUpdated notify = m_notify;
     if (notify == null)
         return;
     using (MemoryStream stream = new MemoryStream(got))
     {
         SoapFormatter formatter = new SoapFormatter();
         for (;;)
         {
             EntryFrequencyUpdate efu = null;
             try
             {
                 efu = formatter.Deserialize(stream) as EntryFrequencyUpdate;
             }
             catch { }
             if (efu == null)
                 break;
             notify(efu);
         }
     }
     StartListener();
 }
        public void WhenConstructorCalledWithSerialization_ExpectPropertiesSetCorrectly()
        {
            // Arrange
            const int expectedCode = 400;
            const string expectedMessage = "Test Message";

            // Act
            RandomOrgException target = new RandomOrgException(expectedCode, expectedMessage);

            IFormatter formatter = new SoapFormatter();
            MemoryStream stream = new MemoryStream();
            formatter.Serialize(stream, target);
            stream.Position = 0;

            using (var sr = new StreamReader(stream))
            {
                var actualMessage = sr.ReadToEnd();

                // Assert
                actualMessage.Should().Contain(expectedMessage);

                stream.Position = 0;
                RandomOrgException ex = formatter.Deserialize(stream) as RandomOrgException;
                ex.Code.Should().Equal(expectedCode);
                ex.Message.Should().Equal(expectedMessage);
            }

        }
Beispiel #4
0
 /// <summary>
 /// 
 /// </summary>
 /// <returns></returns>
 public object Deserialize()
 {
     SoapFormatter aSoap = new SoapFormatter();
     FileStream fs = null;
     object obj = null;
     try
     {
         fs = new FileStream(_filename, FileMode.Open);
         obj = aSoap.Deserialize(fs, null);
     }
     catch (FileNotFoundException)
     {
         return null;
     }
     catch (SerializationException)
     {
         return null;
     }
     finally
     {
         if (fs != null)
         {
             fs.Close();
             fs = null;
         }
     }
     return obj;
 }
        static void Deserialize()
        {
            // Declare the hashtable reference.
            Hashtable addresses = null;

            // Open the file containing the data that you want to deserialize.
            FileStream fs = new FileStream("DataFile.soap", FileMode.Open);
            try
            {
                SoapFormatter formatter = new SoapFormatter();

                // Deserialize the hashtable from the file and
                // assign the reference to the local variable.
                addresses = (Hashtable)formatter.Deserialize(fs);
            }
            catch (SerializationException e)
            {
                Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
                throw;
            }
            finally
            {
                fs.Close();
            }

            // To prove that the table deserialized correctly,
            // display the key/value pairs to the console.
            foreach (DictionaryEntry de in addresses)
            {
                Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
            }
            Console.ReadKey();
        }
Beispiel #6
0
 public static bool Load(Type static_class, string filename)
 {
     try
     {
         FieldInfo[] fields = static_class.GetFields(BindingFlags.Static | BindingFlags.NonPublic);
         object[,] a;
         Stream f = File.Open(filename, FileMode.Open);
         SoapFormatter formatter = new SoapFormatter();
         a = formatter.Deserialize(f) as object[,];
         f.Close();
         if (a.GetLength(0) != fields.Length) return false;
         int i = 0;
         foreach (FieldInfo field in fields)
         {
             if (field.Name == (a[i, 0] as string))
             {
                 if (a[i, 1] != null)
                     field.SetValue(null, a[i, 1]);
             }
             i++;
         };
         return true;
     }
     catch
     {
         return false;
     }
 }
        public static void ReadXml()
        {
            var static_class = typeof(Settings);
            const string filename = "settings.xml";

            try
            {
                var fields = static_class.GetFields(BindingFlags.Static | BindingFlags.Public);
                Stream f = File.Open(filename, FileMode.Open);
                SoapFormatter formatter = new SoapFormatter();
                object[,] a = formatter.Deserialize(f) as object[,];
                f.Close();
                if (a != null && a.GetLength(0) != fields.Length) return;
                var i = 0;
                foreach (var field in fields)
                {
                    if (a != null && field.Name == (a[i, 0] as string))
                    {
                        if (a[i, 1] != null)
                            field.SetValue(null, a[i, 1]);
                    }
                    i++;
                }
            }
            catch
            {
            }
        }
Beispiel #8
0
        public static SocketEntity Receive(NetworkStream ns)
        {
            MemoryStream mem = new MemoryStream();
            SocketEntity entity;
            byte[] data = new byte[4];
            int revc = ns.Read(data, 0, 4);
            int size = BitConverter.ToInt32(data, 0);

            if (size > 0)
            {
                data = new byte[4096];
                revc = ns.Read(data, 0, size);
                mem.Write(data, 0, revc);

                IFormatter formatter = new SoapFormatter();
                mem.Position = 0;
                entity = (SocketEntity)formatter.Deserialize(mem);
                mem.Close();
            }
            else
            {
                entity = null;
            }

            return entity;
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            using (FileStream arquivoEscrita = new FileStream("saida.txt", FileMode.Create, FileAccess.Write))
            {
                Pessoa p = new Pessoa() { Codigo = 1, Nome = "Adão" };

                SoapFormatter sf = new SoapFormatter();

                sf.Serialize(arquivoEscrita, p);

                arquivoEscrita.Close();
            }

            using (FileStream arquivoLeitura = new FileStream("saida.txt", FileMode.Open, FileAccess.Read))
            {
                SoapFormatter sf = new SoapFormatter();

                Pessoa p = sf.Deserialize(arquivoLeitura) as Pessoa;

                arquivoLeitura.Close();

                if(p != null)
                    Console.WriteLine("{0} - {1}", p.Codigo, p.Nome);
            }

            Console.ReadKey();
        }
        /// <summary>
        /// Deserialisiert die Daten zu einem Object
        /// </summary>
        /// <param name="data"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static object DeSerialize(this byte[] data, DataFormatType format)
        {
            MemoryStream ms = new MemoryStream(data);
            object objectToSerialize = null;
            try {
                switch (format) {
                    case DataFormatType.Binary:
                        BinaryFormatter bFormatter = new BinaryFormatter();
                        objectToSerialize = bFormatter.Deserialize(ms);
                        break;
                    case DataFormatType.Soap:
                        SoapFormatter sFormatter = new SoapFormatter();
                        objectToSerialize = sFormatter.Deserialize(ms);
                        break;
                    case DataFormatType.XML:
                        throw new NotImplementedException();
                        //XmlSerializer xFormatter = new XmlSerializer();
                        //objectToSerialize = xFormatter.Deserialize(ms);
                        //break;
                }

            #pragma warning disable 0168
            } catch (Exception ex) { }
            #pragma warning restore 0168

            ms.Close();
            return objectToSerialize;
        }
        public static void ReadXml()
        {
            try
            {
                var staticClass = typeof(logOnOffSettings);

                if (!File.Exists(Filename)) return;

                var fields = staticClass.GetFields(BindingFlags.Static | BindingFlags.Public);

                using (Stream f = File.Open(Filename, FileMode.Open))
                {
                    var formatter = new SoapFormatter();
                    var a = formatter.Deserialize(f) as object[,];
                    f.Close();
                    if (a != null && a.GetLength(0) != fields.Length) return;
                    var i = 0;
                    foreach (var field in fields)
                    {
                        if (a != null && field.Name == (a[i, 0] as string))
                        {
                            if (a[i, 1] != null)
                                field.SetValue(null, a[i, 1]);
                        }
                        i++;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Trace("ERROR Send to MySQL: {0}", ex.ToString());
            }
        }
        public void WhenConstructorCalledWithSerialization_ExpectPropertiesSetCorrectly()
        {
            // Act
            RandomOrgRuntimeException target = new RandomOrgRuntimeException();

            IFormatter formatter = new SoapFormatter();
            using (MemoryStream stream = new MemoryStream())
            {
                formatter.Serialize(stream, target);
                stream.Position = 0;

                using (var sr = new StreamReader(stream))
                {
                    var actualMessage = sr.ReadToEnd();

                    // Assert
                    actualMessage.Should().Contain("RandomOrgRuntimeException");

                    stream.Position = 0;
                    RandomOrgRuntimeException ex = formatter.Deserialize(stream) as RandomOrgRuntimeException;
                    ex.Should().Not.Be.Null();
                    ex?.Message.Should().Contain("RandomOrgRuntimeException");
                }
            }
        }
 /// <summary>
 /// Executes when form is loaded.
 /// </summary>
 /// <param name="sender">Sender of the event.</param>
 /// <param name="e">Event parameters.</param>
 private void OnLoad(object sender, System.EventArgs e)
 {
     this.Text = "Loading configuration...";
     System.IO.FileStream fs = null;
     try
     {
         fs = new System.IO.FileStream(iniFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
         SoapFormatter optFormatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
         this.opt = ((APCService.APCServiceOptions)(optFormatter.Deserialize(fs)));
     }
     catch (System.Exception _e)
     {
         System.Diagnostics.Debug.WriteLine(_e.ToString());
         this.opt = new APCService.APCServiceOptions();
     }
     finally
     {
         if (fs != null)
         {
             fs.Close();
         }
     }
     this.TargetMachineNameTextBox.Text = this.opt.MachineName;
     this.TargetMachinePortTextBox.Text = this.opt.MachinePort.ToString();
     this.Text = "APCServiceControl configuration manager";
 }
Beispiel #14
0
 public static Parameters Load(string filename)
 {
     Parameters p = new Parameters();
     PropertyInfo[] properties = typeof(Parameters).GetProperties();
     object[,] a;
     Stream f = File.Open(filename, FileMode.Open);
     SoapFormatter formatter = new SoapFormatter();
     a = formatter.Deserialize(f) as object[,];
     f.Close();
     //if (a.GetLength(0) != properties.Length) return null;
     int i = 0;
     foreach (PropertyInfo property in properties)
     {
         try
         {
             if (property.Name == (a[i, 0] as string))
             {
                 property.SetValue(p, a[i, 1]);
             }
         }
         catch
         {
         }
         i++;
     };
     return p;
 }
Beispiel #15
0
    /// <summary>
    /// 演示SoapFormatter的序列化和反序列化
    /// </summary>
    void ShowSoapFormatter()
    {
        var soapFormatterOjbect = new API.SoapFormatterOjbect {
            ID = Guid.NewGuid(), Name = "ShowSoapFormatter", Age = 28, Time = DateTime.Now
        };

        var formatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();

        // 序列化
        var ms = new MemoryStream();

        formatter.Serialize(ms, soapFormatterOjbect);

        ms.Position = 0;
        var str = System.Text.Encoding.UTF8.GetString(ms.GetBuffer());

        txtSoapFormatter.Text = str;


        // 反序列化
        var buffer = System.Text.Encoding.UTF8.GetBytes(str);
        var ms2    = new MemoryStream(buffer);
        var soapFormatterOjbect2 = formatter.Deserialize(ms2) as API.SoapFormatterOjbect;

        lblSoapFormatter.Text = soapFormatterOjbect2.Name;
    }
Beispiel #16
0
 public static void LoadFromSOPAPFormat(string fileName)
 {
     SoapFormatter myBin = new SoapFormatter();
     using (Stream myFStream = File.OpenRead(fileName))
     {
         Device deviceFromBinaryFile = (Device)myBin.Deserialize(myFStream);
     }
 }
Beispiel #17
0
 /// <summary>
 /// Désérialise la chaîne en paramètre
 /// </summary>
 /// <param name="value">le dictionnaire de controles</param>
 /// <returns>le dictionnaire de controles désérialisé</returns>
 public ControlDataWrapper[] UnSerialize(string value)
 {
     using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(value)))
     {
         IFormatter formatter = new SoapFormatter();
         return (ControlDataWrapper[])formatter.Deserialize(stream);              
     }
 }
 public static object DeSerializeSOAP(MemoryStream memStream)
 {
     if (memStream.Position > (long)0 && memStream.CanSeek) memStream.Position = (long)0;
     SoapFormatter soapFormatter = new SoapFormatter();
     object local1 = soapFormatter.Deserialize(memStream);
     memStream.Close();
     return local1;
 }
Beispiel #19
0
 public static object DeSerializeSOAP(MemoryStream memStream){
     object sr = null;
     var deserializer = new SoapFormatter();
     memStream.Position = 0;
     sr = deserializer.Deserialize(memStream);
     memStream.Close();
     return sr;
 }
Beispiel #20
0
 //customized Serialization for SoapFormatter :: Read operation
 static void Main()
 {
     FileStream fs = new FileStream("XmlFormatter.xml", FileMode.Open);
     SoapFormatter sf = new SoapFormatter();
     Time t5=sf.Deserialize(fs) as Time;
     Console.WriteLine(t5);
     Console.ReadLine();
     fs.Close();
 }
Beispiel #21
0
 static void LoadFromSoapFile(string fileName)
 {
     SoapFormatter sf = new SoapFormatter();
     using (Stream fstream = File.OpenRead(fileName))
     {
         JamesBondCar jbc = (JamesBondCar)sf.Deserialize(fstream);
         Console.WriteLine(jbc.theRadio.hasTweeters + "---" + jbc.theRadio.stationPresets.ToString());
     }
 }
Beispiel #22
0
 //Soap Formatter :: Read Operation
 public static void Main4()
 {
     FileStream fs = new FileStream("SoapFormatter.xml", FileMode.Open);
     Time t4;
     SoapFormatter sf=new SoapFormatter();
     t4=(Time)sf.Deserialize(fs);
     Console.WriteLine(t4);
     Console.ReadLine();
 }
        public bool deserializeHashtable(ref Hashtable productList)
        {
            FileStream fileStream;

            try
            {
                fileStream = new FileStream(this.filePath, FileMode.Open);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message);

                return false;
            }

            SoapFormatter soapFormatter = new SoapFormatter();

            object obj = null;

            try
            {
                obj = soapFormatter.Deserialize(fileStream);

                if (obj is Hashtable)
                {
                    productList = (Hashtable)obj;

                    fileStream.Flush();
                    fileStream.Close();

                    return true;
                }
                else
                {
                    fileStream.Flush();
                    fileStream.Close();

                    return false;
                }
            }
            catch (EndOfStreamException) { }
            catch (SerializationException e1)
            {
                Console.WriteLine(e1.Message);
                //break;
            }
            catch (System.Xml.XmlException e2)
            {
                 Console.WriteLine(e2.Message);
                 //break;
            }

            fileStream.Flush();
            fileStream.Close();

            return false;
        }
Beispiel #24
0
 static void Main10(string[] args)
 {
     FileStream fs = new FileStream
         ("myEmp.xml", FileMode.Open);
     Emp e1;
     SoapFormatter bf = new SoapFormatter();
     e1 = (Emp)bf.Deserialize(fs);
     Console.WriteLine(e1);
     fs.Close();
 }
 private void Serialize( object obj, String fileName )
 {
     SoapFormatter formatter = new SoapFormatter();
      using (Stream stream = new FileStream( fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None ))
      {
     formatter.Serialize( stream, obj );
     stream.Seek(0, SeekOrigin.Begin);
     formatter.Deserialize(stream);
      }
      Console.WriteLine("{0} Serialized to {1}", obj, fileName);
 }
Beispiel #26
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configureFileName"></param>
        /// <returns></returns>
        public static ConfigureInfosStrcut LoadConfigureInfos(string configureFileName)
        {
            ConfigureInfosStrcut oResult = new ConfigureInfosStrcut();
            SoapFormatter oXmlFomatter = new SoapFormatter();

            System.IO.FileStream oFileStream = new System.IO.FileStream(configureFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            oResult = (ConfigureInfosStrcut)oXmlFomatter.Deserialize(oFileStream);

            oFileStream.Close();
            return oResult;
        }
        public static object XmlFileToObject(string FileName)
        {
            FileStream stream;
              SoapFormatter formatter = new SoapFormatter();
              object obj;

              stream = new FileStream(FileName, FileMode.Open);

              obj = formatter.Deserialize(stream);

              return obj;
        }
Beispiel #28
0
        public static object Deserialize(string filename)
        {
            FileStream fs = new FileStream(filename, FileMode.Open);

            SoapFormatter soapf = new SoapFormatter();

            object o = soapf.Deserialize(fs);

            fs.Close();

            return o;
        }
Beispiel #29
0
        protected Printer[] LoadPrinters()
        {
            if (!File.Exists(configFileName))
                return new Printer[]{};

            FileStream f = new FileStream(configFileName, FileMode.Open);
            SoapFormatter formatter = new SoapFormatter();
            Printer[] printers = (Printer[])formatter.Deserialize(f);
            f.Close();

            return printers;
        }
Beispiel #30
0
 /// <summary>
 /// Load data from XML-file
 /// </summary>
 /// <returns></returns>
 public static Staff Load()
 {
     FileStream file = new FileStream(fileName, FileMode.OpenOrCreate);
     object data = null;
     if (file.Length != 0)
     {
         SoapFormatter fm = new SoapFormatter();
         data = fm.Deserialize(file);
     }
     file.Close();
     return (Staff) data;
 }
        // Called on worker thread from btnStartThread_Click
        private void WorkerThreadFunction()
        {
            string result;
            SendOrPostCallback callback = new SendOrPostCallback(AddString);

            SoapFormatter formatter = new SoapFormatter();
            networkStream = Server.Listen();
            Data data = formatter.Deserialize(networkStream) as Data;
            result = String.Format("privateData: {0}\r\npublicData: {1}", data.PrivateData, data.publicData);
            networkStream.Close();

            ctx.Send(callback, result);
        }
Beispiel #32
0
        public object BinaryDeserialize(Type ReturnType)
        {
            var formatter = new SoapFormatter();

            if (File.Exists(ConfigFile + ".dat"))
            {
                using (Stream s = File.OpenRead(ConfigFile + ".dat"))
                    return formatter.Deserialize(s);

            }
            else
                return Activator.CreateInstance(ReturnType);
        }
Beispiel #33
0
        static void Main(string[] args)
        {
            using (FileStream arquivo = new FileStream("saida.txt", FileMode.Open, FileAccess.Read))
            {
                SoapFormatter formatador = new SoapFormatter();

                String msg = formatador.Deserialize(arquivo).ToString();

                Console.WriteLine(msg);

                Console.ReadKey();
            }
        }
        public static object Deserialize(string objectString)
        {
            object obj = null;

            byte[]     bytData   = System.Text.UTF8Encoding.UTF8.GetBytes(objectString);
            IFormatter formatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();

            MemoryStream ms = new MemoryStream(bytData);

            obj = formatter.Deserialize(ms);
            ms.Close();
            return(obj);
        }