public Serialize ( Stream serializationStream, object graph ) : void | ||
serializationStream | Stream | |
graph | object | |
리턴 | void |
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 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 (); }
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; } }
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(); }
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 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 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) { ///序列化: 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) { 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() { // 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"); } } }
//---------------------------------------------------------------------------------------- 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(); }
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(); }
static void SaveAsSoapFormat(object obj, string fileName) { SoapFormatter sf = new SoapFormatter(); using (Stream fstream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) { sf.Serialize(fstream,obj); } Console.WriteLine(" => save car in Soap format"); }
/// <summary> /// Save data to XML - file using the SOAP protocol /// File is placed in current directory (where *.exe is placed) /// </summary> /// <param name="data"></param> public static void Save(Staff data) { FileStream file = new FileStream(fileName, FileMode.Create); SoapFormatter formatter = new SoapFormatter(); //BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(file, data); file.Close(); }
static void Main13(string[] args) { FileStream fs = new FileStream ("myEmp.xml", FileMode.Create); Emp e1 = new Emp("AAAA", 101, 10000); SoapFormatter bf = new SoapFormatter(); bf.Serialize(fs, e1); fs.Close(); }
/// <summary> /// Serializes the obj into SOAP format file. /// </summary> /// <param name="value_">The object to be serialized.</param> /// <param name="fileName_">The file name_.</param> public static void ObjIntoSoapFile(this object value_, string fileName_) { if (null == value_) new ArgumentNullException("Null object given!"); SoapFormatter formatter = new SoapFormatter(); using (FileStream fs = new FileStream(fileName_, FileMode.Create)) { formatter.Serialize(fs, value_); } }
/// <summary> /// Sérialise les données /// </summary> /// <param name="value">le dictionnaire de controles</param> /// <returns>la chaîne sérialisée</returns> public string Serialize(ControlDataWrapper[] controls) { using (MemoryStream stream = new MemoryStream()) { IFormatter formatter = new SoapFormatter(); formatter.Serialize(stream, controls); return Encoding.ASCII.GetString(stream.GetBuffer()); } }
static public void SaveAppSettings() { IsolatedStorageFile store = IsolatedStorageFile.GetMachineStoreForApplication(); using (Stream stream = new IsolatedStorageFileStream("AppSettings.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, store)) { IFormatter formatter = new SoapFormatter(); formatter.Serialize(stream, AppSettings); } }
public void SaveConfig() { using (Stream stream = new FileStream(fileName, FileMode.Create)) { // Serialize SioData IFormatter formatter = new SoapFormatter(); //formatter.Serialize(stream, new SioData(oData)); formatter.Serialize(stream, oData); } }
public static void ObjectToXmlFile(object Data, string FileName) { FileStream stream = new FileStream(FileName, FileMode.Create); SoapFormatter formatter = new SoapFormatter(); formatter.Serialize(stream, Data); stream.Close(); stream.Dispose(); }
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); }
private static void CreateDataSampleToFile(int size, int dimension) { double[][] data = GetDataSample(size, dimension); StreamWriter sw = new System.IO.StreamWriter( "DataSample_" + size.ToString() + "_" + dimension.ToString() + ".dat", false, System.Text.Encoding.UTF8 ); SoapFormatter soap = new SoapFormatter(); soap.Serialize(sw.BaseStream, data); sw.Flush(); sw.Close(); }
private void SaveAsSoapFormat( object objGraph, string fileName ) { SoapFormatter soapFormatter = new SoapFormatter(); using(Stream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) { soapFormatter.Serialize(stream, objGraph); } Console.WriteLine( "Corvette has been saved to Soap Format" ); }
static void Main(string[] args) { Data data = new Data(); using (FileStream fileStream = new FileStream(@"SoapData.txt", FileMode.OpenOrCreate, FileAccess.Write)) { SoapFormatter soapFormatter = new SoapFormatter(); soapFormatter.Serialize(fileStream, data); fileStream.Close(); } }
public void Func1() { string xmlFilename = @"C:\temp\test.xml"; Person person = new Person { Name = "김성효", Age = 40, Weight = 100 }; SoapFormatter soapFmt = new SoapFormatter(); using (FileStream fs = new FileStream(xmlFilename, FileMode.Create)) { soapFmt.Serialize(fs, person); } }
static void SaveAsSoapFormat(object objGraph, string fileName) { // Save object to a file named CarData.soap in SOAP format. SoapFormatter soapFormat = new SoapFormatter(); using (Stream fStream = new FileStream(fileName,FileMode.Create,FileAccess.Write,FileShare.None)) { soapFormat.Serialize(fStream, objGraph); } Console.WriteLine("=> Saved car in SOAP format!"); }
/// <summary> /// 将一个对象串行化到指定的文件中(SOAP格式) /// </summary> /// <param name="obj"></param> /// <param name="filename"></param> public static void SoapSerialize(Object obj, String filename) { if (string.IsNullOrEmpty(filename.Trim())) { throw new Exception("请指定要串行化的文件名,在DeepSerializer.SoapSerialize() 中"); } using (FileStream stream = File.Create(filename)) { SoapFormatter formatter = new SoapFormatter(); formatter.Serialize(stream, 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(); }