/// <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(); }
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); } }
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); } } }
// Serialize and Save all Template list private void SerializeAndSave(string fileName, Template templejt) { System.IO.Stream stream = System.IO.File.Open(fileName, System.IO.FileMode.Truncate); BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, templejt); stream.Close(); }
/// <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; } }
public void Constructor_InitializesSerializer() { serializer = new BinaryFormatter(); Assert.IsTrue(serverStream.IsConnected); Assert.IsTrue(clientStream.IsConnected); }
/// <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); }
public void Save(string path) { BinaryFormatter binaryFormatter = new BinaryFormatter(); FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write); binaryFormatter.Serialize(fileStream, this); fileStream.Close(); }
public static object DeserializeFromStream(MemoryStream stream) { IFormatter formatter = new BinaryFormatter(); stream.Seek(0, SeekOrigin.Begin); object o = formatter.Deserialize(stream); return o; }
static MethodEvaluator() { BinaryFormatter formatter = new BinaryFormatter { AssemblyFormat = FormatterAssemblyStyle.Simple }; s_Formatter = formatter; }
/// <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(); }
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(); }
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; } }
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); } }
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; }
public Guid SendJob(Base activity) { if (_ConnectionToManager == null || !_ConnectionToManager.IsConnected()) throw new Exception("Not connected to the manager"); while (true) { BinaryFormatter binaryFormatter = new BinaryFormatter(); MemoryStream datastream = new MemoryStream(); binaryFormatter.Serialize(datastream, activity); Packet p = new Packet(1000); Byte[] data= datastream.ToArray(); p.Add(data,true); _ConnectionToManager.SendPacket(p); Stopwatch sendTime = new Stopwatch(); sendTime.Start(); while (sendTime.ElapsedMilliseconds < _CommsTimeout) { if (_ConnectionToManager.GetPacketsToProcessCount() > 0) { foreach (Guid jobGuid in from packet in _ConnectionToManager.GetPacketsToProcess() where packet.Type == 1001 select new Guid((Byte[]) packet.GetObjects()[0])) { return jobGuid; } } Thread.Sleep(1); } if (_ConnectionToManager.IsConnected()) _ConnectionToManager.Disconnect(); _ConnectionToManager.Connect(_IpAddress, _Port, 20480 * 1024); } throw new Exception("Mananger unavailable or busy"); }
public static MemoryStream SerializeToStream(object o) { MemoryStream stream = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, o); return stream; }
static void Main(string[] args) { string quit = "n"; while (quit == "n") { ITransport transport = TcpTransport.CreateTransport(45459); if (transport != null) { IEvent e = new TcpEvent((int)EventId.Media, null); BinaryFormatter bf = new BinaryFormatter(); MemoryStream mem = new MemoryStream(); bf.Serialize(mem, e); transport.Send(mem.GetBuffer()); Console.WriteLine("Quit?(y/n)"); quit = Console.ReadLine(); transport.Close(); //if (quit != "n") //{ // Console.WriteLine("send disconned event to Server to close the server"); // IEvent d = new TcpEvent((int)EventId.Disconnect, null); // BinaryFormatter bfd = new BinaryFormatter(); // MemoryStream memd = new MemoryStream(); // bfd.Serialize(memd, d); // transport.Send(memd.GetBuffer()); // transport.Close(); //} } } }
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; } }
private static Object DeserializeFromMemory(Stream stream) { //构造一个序列化格式化器来做所有辛苦的工作 BinaryFormatter formatter = new BinaryFormatter(); //告诉格式化器从流中反序列化对象 return formatter.Deserialize(stream); }
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}")); }
/// <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."); }
//Méthode statique pour l'envoi et la réception public void Send(Paquet paquet, NetworkStream stream) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(stream, paquet); stream.Flush(); }
public void Save() { Stream stream = File.Open(filepath, FileMode.Create); BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, this); stream.Close(); }
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; }
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; } }
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; } }
public static void LoadFromFile(string filePath, object options) { FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryFormatter bf = new BinaryFormatter(); options = bf.Deserialize(fs); fs.Close(); }
public Base GetCompletedWork(Guid jobGuid) { if (_ConnectionToManager == null || !_ConnectionToManager.IsConnected()) throw new Exception("Not connected to the manager"); while (true) { Packet p = new Packet(1100); p.Add(jobGuid.ToByteArray(),true); _ConnectionToManager.SendPacket(p); Stopwatch sendTime = new Stopwatch(); sendTime.Start(); while (sendTime.ElapsedMilliseconds < _CommsTimeout) { if (_ConnectionToManager.GetPacketsToProcessCount() > 0) { foreach (Packet packet in _ConnectionToManager.GetPacketsToProcess()) { switch (packet.Type) { case 1101: return null; case 1102: Object[] packetObjects = packet.GetObjects(); BinaryFormatter binaryFormatter = new BinaryFormatter(); return (Base) binaryFormatter.Deserialize(new MemoryStream((Byte[]) packetObjects[0])); } } Thread.Sleep(100); } } if (_ConnectionToManager.IsConnected())_ConnectionToManager.Disconnect(); _ConnectionToManager.Connect(_IpAddress, _Port, 204800); } return null; }
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(); } }
/// <summary> /// Deserializes a <see cref="Stream"/> to the specified <paramref name="instance"/>. /// </summary> /// <param name="instance">The instance that the <paramref name="stream"/> will be deserialized to.</param> /// <param name="stream">The <see cref="Stream"/> containing the data to deserialize.</param> /// <exception cref="ArgumentNullException"> thrown if the <paramref name="instance"/> or <paramref name="stream"/> is <c>Null</c>.</exception> public static void Deserialize(this IBinarySerializable instance, Stream stream) { if (instance.IsNull()) { throw new ArgumentNullException("instance"); } if (stream.IsNull()) { throw new ArgumentNullException("stream"); } Formatters.Binary.BinaryFormatter formatter = new Formatters.Binary.BinaryFormatter(); formatter.Deserialize(stream).CopyTo(instance); }
// 加载地图 public void LoadMapBlockData(string path) { if (!File.Exists(path)) { return; } using (FileStream stream = File.Open(path, FileMode.Open)) { MapSaveData map_save_data = new MapSaveData(); var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); map_save_data = (MapSaveData)binaryFormatter.Deserialize(stream); map_width = map_save_data.map_width; map_height = map_save_data.map_height; map_step = map_save_data.map_step; _grid_array = map_save_data.grid_array; InitMeshComponent(); UpdateMesh(); } }
public static bool SaveSnapshotBin(string binFilePath, string binFileName, PackedMemorySnapshot packed) { try { string fullName = Path.Combine(binFilePath, binFileName); if (!File.Exists(fullName)) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (Stream stream = File.Open(fullName, FileMode.Create)) { bf.Serialize(stream, packed); } } return(true); } catch (Exception ex) { Debug.LogError(string.Format("save snapshot error ! msg ={0}", ex.Message)); Debug.LogException(ex); return(false); } }
public void SaveIt() { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); System.IO.FileStream fs = new System.IO.FileStream(Application.dataPath + "SaveMesh.dat", System.IO.FileMode.Create); Serialize_Mesh Ser_Mesh = new Serialize_Mesh(filter.mesh); bf.Serialize(fs, Ser_Mesh); fs.Close(); float red = this.GetComponent <Renderer>().material.color.r; float green = this.GetComponent <Renderer>().material.color.g; float blue = this.GetComponent <Renderer>().material.color.b; float alpha = this.GetComponent <Renderer>().material.color.a; string mycolor = red + " " + green + " " + blue + " " + alpha; Debug.Log(mycolor + "......................................"); string path = Application.dataPath + "file.txt"; System.IO.File.WriteAllText(path, mycolor); }
public bool saveAllSnapshot(List <MemSnapshotInfo> snapshotInfos, eProfilerMode profilerMode, string ip = null) { if (snapshotInfos.Count <= 0) { return(false); } try { _basePath = combineBasepath(profilerMode, ip); if (!Directory.Exists(_basePath)) { Directory.CreateDirectory(_basePath); } for (int index = 0; index < snapshotInfos.Count; index++) { var packed = snapshotInfos[index]; string fileName = Path.Combine(_basePath, string.Format("{0}.memsnap", index)); if (!File.Exists(fileName)) { saveSnapshotJson(index, packed); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (Stream stream = File.Open(fileName, FileMode.Create)) { bf.Serialize(stream, packed); } } } return(true); } catch (Exception ex) { Debug.LogError(string.Format("save snapshot error ! msg ={0}", ex.Message)); Debug.LogException(ex); return(false); } }
static void Main(string[] args) { List <salesman> salesmanList = new List <salesman>(); string dir = @"c:\temp"; string serializationFile = Path.Combine(dir, "salesmen.bin"); //serialize using (Stream stream = File.Open(serializationFile, FileMode.Create)) { var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bformatter.Serialize(stream, salesmanList); } //deserialize using (Stream stream = File.Open(serializationFile, FileMode.Open)) { var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); List <salesman> salesman = (List <salesman>)bformatter.Deserialize(stream); } }
static void construct_bulknpose_bundle() { //new version, serializes as a dictionary in one big file IEnumerable <Object> files = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets).Where(e => is_text_file(e)); Debug.Log("making a pose bundle out of " + files.Count() + " files"); Dictionary <string, string> index = new Dictionary <string, string> (); foreach (var e in files) { index[e.name] = (e as TextAsset).text; Debug.Log("set data for " + e.name); } AssetDatabase.ImportAsset("Assets/POSEDICT.txt"); TextAsset cdtxt = (TextAsset)AssetDatabase.LoadAssetAtPath("Assets/POSEDICT.txt", typeof(TextAsset)); System.IO.Stream stream = System.IO.File.Open(AssetDatabase.GetAssetPath(cdtxt), System.IO.FileMode.Create); //System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(Dictionary<string,string>)); //xs.Serialize(stream, index); var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(stream, index); stream.Close(); AssetDatabase.ImportAsset("Assets/POSEDICT.txt"); cdtxt = (TextAsset)AssetDatabase.LoadAssetAtPath("Assets/POSEDICT.txt", typeof(TextAsset)); List <Object> assets = new List <Object> (); assets.Add(cdtxt); BuildPipeline.BuildAssetBundle( Selection.activeObject, assets.ToArray(), "Assets/Resources/BULKPOSES.unity3d", BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, EditorUserBuildSettings.activeBuildTarget); //, BuildOptions.UncompressedAssetBundle);//, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets); }
private DataSet decom(byte[] data) { var dt = new DataSet(); try { var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple; //formatter.Binder = new MyBinder(); using (var ms = new MemoryStream(data)) { using (var desr = new GZipStream(ms, CompressionMode.Decompress, true)) { dt = formatter.Deserialize(desr) as DataSet; } } } catch (Exception ex) { dt = null; // removed error handling logic! } return(dt); }
/// <summary> /// Saves the given settings object to the standard location /// </summary> /// <param name="settings"></param> public static void saveSettings(SettingsObj settings) { if (settings == null) // can't save the object if there is no object { throw new System.ArgumentException("Parameter \"settings\" cannot be null"); } Stream stream = null; try { // crashing due to file access issues is a bitch, so don't crash System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); //Debug.Log("Saving to File: \"" + Application.persistentDataPath + "\\Settings.txt\""); stream = new FileStream(Application.persistentDataPath + "\\Settings.txt", FileMode.Create, FileAccess.Write); formatter.Serialize(stream, settings); stream.Close(); } catch (System.Exception e) { Debug.Log(e.Message); // notify me about any exceptions. if (stream != null) // make sure the stream is closed if an exception was generated. { stream.Close(); } } return; }
public static StaticVariables Load(string filename, ref List <string> messages) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); FileStream fromStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); StaticVariables sv = null; try { sv = (StaticVariables)formatter.Deserialize(fromStream); sv.verifyPrimitiveDataTypesExist(); } catch (Exception ex) { //Interaction.MsgBox("Oops, we could not load the variables due to the following error: " messages.Add("Oops, we could not load the variables due to the following error: " + ex.Message); } finally { if (fromStream != null) { fromStream.Close(); fromStream.Dispose(); } } return(sv); }
public void Layout() { string decision; do { Console.WriteLine("\t ==============================="); Console.WriteLine("\t|\t1.Manage To-do List\t|"); Console.WriteLine("\t|\t2.Manage My-day List\t|"); Console.WriteLine("\t|\t3.Exit\t\t\t|"); Console.WriteLine("\t ==============================="); Console.Write("\t\tPlease choose: "); decision = Console.ReadLine(); if (decision != "1" && decision != "2" && decision != "3") { Console.WriteLine("\nWrong input. Please choose again.\n"); } } while (decision != "1" && decision != "2" && decision != "3"); switch (decision) { case "1": menutodoList(); break; case "2": //menumyDayList(); break; case "3": break; } void menutodoList() { string dir = @"c:\temp"; string serializationFile = Path.Combine(dir, "salesmen.bin"); while (true) { string menuTaskDecision = ""; //Menu Student while (menuTaskDecision != "1" && menuTaskDecision != "2" && menuTaskDecision != "3" && menuTaskDecision != "4" && menuTaskDecision != "5" && menuTaskDecision != "6") { Console.WriteLine("\t*****************************************"); Console.WriteLine("\t*\t\tTask in List: \t\t*"); foreach (var it in todoList) { Console.Write("\t*\t"); it.DisplayList(); } Console.WriteLine("\t*****************************************"); Console.WriteLine(""); Console.WriteLine("\t ==============================="); Console.WriteLine("\t|\t1.Add new item\t\t|"); Console.WriteLine("\t|\t2.Delete item\t\t|"); Console.WriteLine("\t|\t3.Update item\t\t|"); Console.WriteLine("\t|\t4.Back to main menu\t|"); Console.WriteLine("\t|\t5.Save List\t\t|"); Console.WriteLine("\t|\t6.Load List\t\t|"); Console.WriteLine("\t ==============================="); Console.Write("\t\tPlease choose: "); menuTaskDecision = Console.ReadLine(); if (menuTaskDecision != "1" && menuTaskDecision != "2" && menuTaskDecision != "3" && menuTaskDecision != "4" && menuTaskDecision != "5" && menuTaskDecision != "6") { Console.WriteLine("Wrong Input! Please try again"); } } switch (Convert.ToInt32(menuTaskDecision)) { case 1: Input(todoList, 0); break; case 2: Console.WriteLine("Please enter task name that you want to delete: "); String TaskDeleteValue = Console.ReadLine(); Console.WriteLine(CheckDelete(TaskDeleteValue, todoList)); NumberTask(todoList); menutodoList(); break; case 3: Console.WriteLine("Please enter task Name that you want to update: "); String studentUpdateValue = Console.ReadLine(); CheckUpdate(studentUpdateValue, todoList); menutodoList(); break; case 4: Layout(); break; case 5: //serialize using (Stream stream = File.Open(serializationFile, FileMode.Create)) { var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bformatter.Serialize(stream, todoList); } /*var fileName = @"E:\Desktop\wordss.txt"; * if(!File.Exists(fileName)) * { * FileStream fsCreate = new FileStream(fileName, FileMode.Create); * fsCreate.Close(); * Console.Write($"File has been created and the Path is {fileName}"); * } * FileStream fs = new FileStream(fileName, FileMode.Append); * byte[] bdata = Encoding.Default.GetBytes("Hello File Handling!"); * fs.Write(bdata, 0, bdata.Length); * fs.Close();*/ break; case 6: try { using (Stream stream = File.Open(serializationFile, FileMode.Open)) { BinaryFormatter bin = new BinaryFormatter(); var tasklist = (List <TaskItem>)bin.Deserialize(stream); foreach (var taskload in tasklist) { todoList.Add(taskload); } } } catch (IOException) { } break; } } } }
private void setTypeValue(string fieldname, string type, string Value) { FieldInfo info = obj.GetType().GetField(fieldname, flags); if (info == null) { try { Type type1 = obj.GetType().BaseType; while (type1 != null) { info = type1.GetField(fieldname, flags); if (info == null) { try { type1 = type1.BaseType; } catch { type = null; } } else { break; } } } catch { } } Type valueType = info.FieldType; if (valueType == typeof(string)) { info.SetValue(obj, Value); } else if (valueType == typeof(char)) { info.SetValue(obj, char.Parse(Value)); } else if (valueType == typeof(bool)) { info.SetValue(obj, Boolean.Parse(Value)); } else if (valueType == typeof(sbyte)) { info.SetValue(obj, sbyte.Parse(Value)); } else if (valueType == typeof(byte)) { info.SetValue(obj, byte.Parse(Value)); } else if (valueType == typeof(ushort)) { info.SetValue(obj, ushort.Parse(Value)); } else if (valueType == typeof(short)) { info.SetValue(obj, short.Parse(Value)); } else if (valueType == typeof(uint)) { info.SetValue(obj, uint.Parse(Value)); } else if (valueType == typeof(int)) { info.SetValue(obj, int.Parse(Value)); } else if (valueType == typeof(ulong)) { info.SetValue(obj, ulong.Parse(Value)); } else if (valueType == typeof(long)) { info.SetValue(obj, long.Parse(Value)); } else if (valueType == typeof(float)) { info.SetValue(obj, float.Parse(Value)); } else if (valueType == typeof(Single)) { info.SetValue(obj, Single.Parse(Value)); } else if (valueType == typeof(double)) { info.SetValue(obj, double.Parse(Value)); } else if (valueType == typeof(decimal)) { info.SetValue(obj, decimal.Parse(Value)); } else if (valueType == typeof(DateTime)) { info.SetValue(obj, DateTime.Parse(Value)); } else if (valueType.BaseType == typeof(Array)) { setArrayValue(info, Value); } else if (valueType.BaseType == typeof(XmlSerializer)) { string xmlcode = System.Text.Encoding.Default.GetString(Convert.FromBase64String(Value)); object o = Activator.CreateInstance(valueType); info.SetValue(obj, ((XmlSerializer)o).DeSerialize(xmlcode)); } else { byte[] bytes = Convert.FromBase64String(Value); MemoryStream ms = new MemoryStream(); ms.Write(bytes, 0, bytes.Length); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); object obj3 = bf.Deserialize(ms); info.SetValue(obj, obj3); } }
/*******************************/ public static void Serialize(System.IO.BinaryWriter binaryWriter, System.Object obj) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(binaryWriter.BaseStream, obj); }
/*******************************/ public static System.Object Deserialize(System.IO.BinaryReader binaryReader) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); return(formatter.Deserialize(binaryReader.BaseStream)); }
public void Enable(AudioClip _loadedClip) { if (!Serializer.IsExtratingClip && Serializer.ClipExtratedComplete) { audioSource.clip = _loadedClip; audioSourceLoaded = true; m_Slider.maxValue = audioSource.clip.length; m_Slider.value = 0; if (IsSpectrumCached()) { try { using (FileStream file = File.OpenRead(spectrumCachePath + Serializer.CleanInput(Serializer.ChartData.AudioName + spc_ext))) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); preProcessedSpectralFluxAnalyzer = (SpectralFluxAnalyzer)bf.Deserialize(file); } EndSpectralAnalyzer(); Debug.Log("Spectrum loaded from cached"); } catch (Exception ex) { Miku_DialogManager.ShowDialog(Miku_DialogManager.DialogType.Alert, "Error while dezerializing Spectrum " + ex.ToString() ); Debug.Log(ex.ToString()); } } else { Debug.Log("Spectrum data not cached!"); } } }
public void LoadSession() { string pathName = EditorUtility.OpenFolderPanel("Load Snapshot Folder", MemUtil.SnapshotsDir, ""); if (string.IsNullOrEmpty(pathName)) { return; } List <object> packeds = new List <object>(); try { DirectoryInfo TheFolder = new DirectoryInfo(pathName); if (!TheFolder.Exists) { throw new Exception(string.Format("bad path: {0}", TheFolder.ToString())); } System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); foreach (var file in TheFolder.GetFiles()) { var fileName = file.FullName; if (fileName.EndsWith(".memsnap")) { using (Stream stream = File.Open(fileName, FileMode.Open)) { packeds.Add(bf.Deserialize(stream)); } } } if (packeds.Count == 0) { MemUtil.NotifyError("no snapshots found."); return; } } catch (Exception ex) { Debug.LogError(string.Format("load snapshot error ! msg ={0}", ex.Message)); return; } Clear(); foreach (var obj in packeds) { MemSnapshotInfo memInfo = new MemSnapshotInfo(); if (memInfo.AcceptSnapshot(obj as PackedMemorySnapshot)) { _snapshots.Add(memInfo); } } if (_snapshots.Count == 0) { MemUtil.NotifyError("empty snapshot list, ignored."); return; } RefreshIndices(); _selected = _snapshots.Count - 1; }
public void Save(MemoryStream stream) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(stream, this); stream.Close(); }
private void setArrayValue(FieldInfo info, string Value) { Match regex; string xmlcodes = System.Text.Encoding.Default.GetString(Convert.FromBase64String(Value)); string[] strings = xmlcodes.Split('\n'); string regexstr = @"<List Length='(.*)' Type='(.*)'>"; int length = 0; Type listType = null; foreach (string str in strings) { if (str == "" || str == "<nullreferance>") { continue; } try { regex = Regex.Match(str, regexstr); if (regex.Groups[1].Value != "") { length = Convert.ToInt32(regex.Groups[1].Value); listType = Type.GetType(regex.Groups[2].Value); } } catch { } } Array arr = null; int selectval = -1; regexstr = @"<Arr_(.*) Type='(.*)'>(.*)</Arr_(.*)>"; foreach (string str in strings) { if (str == "" || str == "<nullreferance>") { continue; } try { regex = Regex.Match(str, regexstr); if (regex.Groups[1].Value != "" | regex.Groups[2].Value != "" | regex.Groups[3].Value != "") { selectval++; Type valueType = Type.GetType(regex.Groups[2].Value); if (arr == null) { arr = Array.CreateInstance(valueType, length); } if (valueType == typeof(string)) { arr.SetValue(regex.Groups[3].Value, selectval); } else if (valueType == typeof(char)) { arr.SetValue(char.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(bool)) { arr.SetValue(Boolean.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(sbyte)) { arr.SetValue(sbyte.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(byte)) { arr.SetValue(byte.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(ushort)) { arr.SetValue(ushort.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(short)) { arr.SetValue(short.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(uint)) { arr.SetValue(uint.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(int)) { arr.SetValue(int.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(ulong)) { arr.SetValue(ulong.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(long)) { arr.SetValue(long.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(float)) { arr.SetValue(float.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(Single)) { arr.SetValue(Single.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(double)) { arr.SetValue(double.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(decimal)) { arr.SetValue(decimal.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(DateTime)) { arr.SetValue(DateTime.Parse(regex.Groups[3].Value), selectval); } else if (valueType == typeof(Array)) { setArrayValue(info, regex.Groups[3].Value); } else if (valueType.BaseType == typeof(XmlSerializer)) { string xmlcode = System.Text.Encoding.Default.GetString(Convert.FromBase64String(regex.Groups[3].Value)); object o = Activator.CreateInstance(valueType); arr.SetValue(((XmlSerializer)o).DeSerialize(xmlcode), selectval); } else { byte[] bytes = Convert.FromBase64String(regex.Groups[3].Value); MemoryStream ms = new MemoryStream(); ms.Write(bytes, 0, bytes.Length); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); object obj3 = bf.Deserialize(ms); arr.SetValue(obj3, selectval); } } } catch { } } info.SetValue(obj, arr); }
static PackedMemorySnapshot LoadFromFile(string filePath) { #if UNITY_5_OR_NEWER PackedMemorySnapshot result = null; string fileExtension = Path.GetExtension(filePath); if (string.Equals(fileExtension, ".memsnap2", System.StringComparison.OrdinalIgnoreCase)) { UnityEngine.Profiling.Profiler.BeginSample("PackedMemorySnapshotUtility.LoadFromFile(json)"); var json = File.ReadAllText(filePath); result = JsonUtility.FromJson <PackedMemorySnapshot>(json); UnityEngine.Profiling.Profiler.EndSample(); } else if (string.Equals(fileExtension, ".memsnap", System.StringComparison.OrdinalIgnoreCase)) { UnityEngine.Profiling.Profiler.BeginSample("PackedMemorySnapshotUtility.LoadFromFile(binary)"); var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (Stream stream = File.Open(filePath, FileMode.Open)) { result = binaryFormatter.Deserialize(stream) as PackedMemorySnapshot; } UnityEngine.Profiling.Profiler.EndSample(); } else { Debug.LogErrorFormat("MemoryProfiler: Unrecognized memory snapshot format '{0}'.", filePath); } return(result); #else PackedMemorySnapshot result = null; string fileExtension = Path.GetExtension(filePath); if (string.Equals(fileExtension, ".memsnap2", System.StringComparison.OrdinalIgnoreCase)) { Profiler.BeginSample("PackedMemorySnapshotUtility.LoadFromFile(json)"); var json = File.ReadAllText(filePath); result = JsonUtility.FromJson <PackedMemorySnapshot>(json); Profiler.EndSample(); } else if (string.Equals(fileExtension, ".memsnap", System.StringComparison.OrdinalIgnoreCase)) { Profiler.BeginSample("PackedMemorySnapshotUtility.LoadFromFile(binary)"); var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (Stream stream = File.Open(filePath, FileMode.Open)) { result = binaryFormatter.Deserialize(stream) as PackedMemorySnapshot; } Profiler.EndSample(); } else { Debug.LogErrorFormat("MemoryProfiler: Unrecognized memory snapshot format '{0}'.", filePath); } return(result); #endif }