public static bool Save(Type static_class, string filename) { try { FieldInfo[] fields = static_class.GetFields(BindingFlags.Static | BindingFlags.NonPublic); object[,] a = new object[fields.Length, 2]; int i = 0; foreach (FieldInfo field in fields) { a[i, 0] = field.Name; a[i, 1] = field.GetValue(null); i++; }; Stream f = File.Open(filename, FileMode.Create); SoapFormatter formatter = new SoapFormatter(); formatter.Serialize(f, a); f.Close(); return true; } catch { return false; } }
/// <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; }
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 logger() { //bugs = new List<bugData>(); //x = new XmlSerializer(bugs.GetType()); sf = new SoapFormatter(); initialize(); }
/// <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 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"); } } }
static void PersisUser() { List<JamesBondCar> myCars = new List<JamesBondCar>(); XmlSerializer xmlSer = new XmlSerializer(typeof(Person)); Person ps = new Person(); using (Stream fStream = new FileStream("Person.xml", FileMode.Create, FileAccess.Write, FileShare.None)) { xmlSer.Serialize(fStream, ps); } SoapFormatter soapFormat = new SoapFormatter(); using (Stream fStream = new FileStream("Person.soap", FileMode.Create, FileAccess.Write, FileShare.None)) { soapFormat.Serialize(fStream, ps); } BinaryFormatter binFormat = new BinaryFormatter(); UserPrefs userData = new UserPrefs(); userData.WindowColor = "Yelllow"; userData.FontSize = 50; //Store object in a local file using (Stream fStream = new FileStream("user.dat", FileMode.Create, FileAccess.Write, FileShare.None)) { binFormat.Serialize(fStream, userData); } }
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(); }
/// <summary> /// 读取配置文件到当前类 /// </summary> public void ReadFromConfigureFile() { //从配置文件中读 Log.OverallLog.Log("读取配置文件"); IFormatter formatter = new SoapFormatter(); //当前dll的目录下的config.cfg string pathOfConfigFile = GetConfigPath(); System.IO.Stream stream=null; try { stream = new System.IO.FileStream(pathOfConfigFile, FileMode.Open, FileAccess.Read, FileShare.Read); ApplicationSettings obj = (ApplicationSettings)formatter.Deserialize(stream); this.FlushTime = obj.FlushTime; this.ItemConfigWoods = obj.ItemConfigWoods; this.SwitchTypeItems = obj.SwitchTypeItems; stream.Close(); } catch (FileNotFoundException) { Log.OverallLog.LogForErr("配置文件不存在"); return; } catch (SerializationException) { if (stream != null) stream.Dispose(); System.IO.File.Delete(pathOfConfigFile); Log.OverallLog.LogForErr("配置文件存在错误,试图删除"); } }
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; }
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(); }
static void Main(string[] args) { ArrayList hobbies = new ArrayList(); hobbies.Add("Skiing"); hobbies.Add("Biking"); hobbies.Add("Snowboarding"); Person person = new Person("Brian Pfeil", 28, hobbies); // Binary formatter IFormatter formatter = new BinaryFormatter(); formatter.Serialize(Console.OpenStandardOutput(), person); Console.WriteLine("End Binary Formatter output. Press enter to continue ..."); Console.Read(); // SOAP formatter formatter = new SoapFormatter(); formatter.Serialize(Console.OpenStandardOutput(), person); Console.WriteLine("End Soap Formatter output. Press enter to continue ..."); Console.Read(); //XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person)); //xmlSerializer.Serialize(Console.Out, person); Console.Read(); }
public void BinarySerialize(Type ReturnType, object obj) { var formatter = new SoapFormatter(); using (Stream s = File.Create(ConfigFile + ".dat")) formatter.Serialize(s, obj); }
static void Main (string[] args) { object x = null; string strTypes = null; string argValues = null; if (args.Length == 1) { Type t = Type.GetType (args[0]); Console.WriteLine ("\nPlease enter the arguments to the constructor for type {0}", t.ToString()); strTypes = Console.ReadLine (); Console.WriteLine ("\nPlease enter the values"); argValues = Console.ReadLine (); Type[] types = ToTypeArray (strTypes.Split (',')); string[] param = argValues.Split (','); x = LiveCreateObject (t, types, param); } else { x = StaticCreateObject (); } string fileName = x.GetType().FullName + ".xml"; Stream output = new FileStream (fileName, FileMode.Create, FileAccess.Write, FileShare.None); IFormatter formatter = new SoapFormatter (); formatter.Serialize ((Stream) output, x); output.Close (); }
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(); }
protected void SavePrinters( Printer[] printers ) { FileStream f = new FileStream(configFileName, FileMode.Create); SoapFormatter formatter = new SoapFormatter(); formatter.Serialize(f, printers); f.Close(); }
public static void WriteXml() { var static_class = typeof(Settings); const string filename = "settings.xml"; try { var fields = static_class.GetFields(BindingFlags.Static | BindingFlags.Public); object[,] a = new object[fields.Length, 2]; var i = 0; foreach (var field in fields) { a[i, 0] = field.Name; a[i, 1] = field.GetValue(null); i++; } Stream f = File.Open(filename, FileMode.Create); SoapFormatter formatter = new SoapFormatter(); formatter.Serialize(f, a); f.Close(); } catch { } }
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); } }
/// <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; }
public static bool Load(Type staticClass, string filename, bool binaryFormatter = true) { try { FieldInfo[] fields = staticClass.GetFields(BindingFlags.Static | BindingFlags.Public); object[,] a; Stream f = File.Open(filename, FileMode.Open); IFormatter formatter; if (binaryFormatter) formatter = new BinaryFormatter(); else 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)) { field.SetValue(null, a[i, 1]); } i++; }; return true; } catch { return false; } }
// 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(); }
static void Main(string[] args) { Employee empl = new Employee("Müller", 28, 1, 10000, "ssn-0001"); // Save it with a BinaryFormatter FileInfo f = new FileInfo(@"L7U2_EmployeeBin.txt"); using (BinaryWriter bw = new BinaryWriter(f.OpenWrite())) { bw.Write(empl.Age); bw.Write(empl.ID); bw.Write(empl.Name); bw.Write(empl.Pay); bw.Write(empl.SocialSecurityNumber); } // Save it with a SoapFormatter using (FileStream str = File.Create("L7U2_EmployeeSoap.txt")) { SoapFormatter sf = new SoapFormatter(); sf.Serialize(str, empl); } // Save it with a XmlSerializer XmlSerializer SerializerObj = new XmlSerializer(typeof(Employee)); TextWriter WriteFileStream = new StreamWriter(@"L7U2_EmployeeXml.txt"); SerializerObj.Serialize(WriteFileStream, empl); WriteFileStream.Close(); }
/// <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"; }
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 { } }
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; }
/// <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){ object sr = null; var deserializer = new SoapFormatter(); memStream.Position = 0; sr = deserializer.Deserialize(memStream); memStream.Close(); return sr; }
//---------------------------------------------------------------------------------------- public void SoapSerWorkList(List<Person> workList, string soapFileName) { SoapFormatter sFormatter = new SoapFormatter(); using (FileStream fs = new FileStream(soapFileName, FileMode.OpenOrCreate, FileAccess.Write)) { sFormatter.Serialize(fs, workList); } }
//customized Serialization for SoapFormatter public static void Main1() { FileStream fs = new FileStream("XmlFormatter.xml", FileMode.Create); Time t5 = new Time(50, 100, 150); SoapFormatter bf = new SoapFormatter(); bf.Serialize(fs, t5); fs.Close(); }
public static void LoadFromSOPAPFormat(string fileName) { SoapFormatter myBin = new SoapFormatter(); using (Stream myFStream = File.OpenRead(fileName)) { Device deviceFromBinaryFile = (Device)myBin.Deserialize(myFStream); } }
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; }
static void SaveAsSoapFormat(object objGraph, string fileName) { SoapFormatter binFormat = new SoapFormatter(); using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) { binFormat.Serialize(fStream, objGraph); } Console.WriteLine("Saved object in SOAP format"); }
//Soap Formatter :: Write Operation public static void Main3() { FileStream fs = new FileStream("SoapFormatter.xml",FileMode.Create); Time t3 = new Time(10, 20, 30); SoapFormatter sf = new SoapFormatter(); sf.Serialize(fs, t3); fs.Close(); }
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); }
/// <summary> /// Saves all options. /// </summary> /// <param name="sender">Sender of the event.</param> /// <param name="e">Event parameters.</param> private void SaveOptions(object sender, System.EventArgs e) { if (this.ApplyConfigurationButton.Enabled) { System.IO.FileStream fs = null; try { // Saving settings. fs = new System.IO.FileStream(iniFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite); SoapFormatter optFormatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter(); optFormatter.Serialize(fs, this.opt); // Setting application to autostart or remove it from. Microsoft.Win32.RegistryKey AppStartUpKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(autostartRegKey, true); if (this.AutoStartCheckBox.Checked) { // Setting. AppStartUpKey.SetValue(autostartValueKey, autostartValue); } else { // Removing. AppStartUpKey.DeleteValue(autostartValueKey); } } catch (System.Exception x) { MessageBox.Show("Exception while applying new settings:" + Environment.NewLine + x.ToString() + Environment.NewLine + "Settings for your application could be set through changing file \"" + Application.ExecutablePath + ".ini\" manually." + Environment.NewLine + "Application can't continue execution... quit now.", "Unrecoverable error", MessageBox.Type.Error); this.DialogResult = DialogResult.Cancel; this.Close(); } finally { if (fs != null) { fs.Close(); } } } if (sender == this.ApplyConfigurationButton) { this.DialogResult = DialogResult.OK; } else { this.DialogResult = DialogResult.Cancel; } this.Close(); }