Note that there are some explanatory texts on larger screens.

plurals
  1. POSerialize/Deserilize array of objects/structs
    primarykey
    data
    text
    <p>I have read many codes on this but none happened to solve the problem. first the code: </p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace Serialization { class Program { static void Main(string[] args) { using (MoveSaver objSaver = new MoveSaver(@"C:\1.bin")) { MoveAndTime mv1, mv2; mv1.MoveStruc = "1"; mv1.timeHLd = DateTime.Now; objSaver.SaveToFile(mv1); mv2.MoveStruc = "2"; mv2.timeHLd = DateTime.Now; objSaver.SaveToFile(mv2); } using (MoveSaver svrObj = new MoveSaver()) { MoveAndTime[] MVTobjs = svrObj.DeSerializeObject(@"C:\1.bin"); foreach (MoveAndTime item in MVTobjs) { //Do Something } } } } public class MoveSaver:IDisposable { public void Dispose() { if (fs != null) { fs.Close(); } } FileStream fs; StreamWriter sw; public string filename { get; set; } public MoveSaver(string FileName) { this.filename = FileName; fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite); } public MoveSaver() { } ~MoveSaver() { if (fs != null) { fs.Close(); } } public MoveAndTime[] DeSerializeObject(string filename) { MoveAndTime[] objectToSerialize; Stream stream = File.Open(filename, FileMode.Open); BinaryFormatter bFormatter = new BinaryFormatter(); objectToSerialize = (MoveAndTime[])bFormatter.Deserialize(stream); stream.Close(); return objectToSerialize; } public bool SaveToFile(MoveAndTime moveTime) { try { BinaryFormatter bformatter = new BinaryFormatter(); bformatter.Serialize(fs, moveTime); return true; } catch (Exception) { return false; } } } [Serializable] public struct MoveAndTime { public string MoveStruc; public DateTime timeHLd; } } </code></pre> <p>The code mimics a need for saving all actions of user on the program. to be later shown on that program (say you play cards or so and you want to review :D what has happened). The problem is when DeSerializeObject function is called the line <code>objectToSerialize = (MoveAndTime[])bFormatter.Deserialize(stream);</code> throws an exception (definitely in runtime) that the cast from a single object to array is not valid:</p> <blockquote> <p>Unable to cast object of type 'Serialization.MoveAndTime' to type 'Serialization.MoveAndTime[]'.</p> </blockquote> <p>Any idea? Any improvement or total change of approach is appreciated.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload