static void Main(string[] args) { Number.ComplexNumber cn = new Number.ComplexNumber(8, 3); // Class ComplexNumber is moved to a ClassLibrary ComplexNumber DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Number.ComplexNumber)); // Serialize using JSON serializer using (FileStream fs = new FileStream(@"D:\repos\Lab4\Task1\ComNum.json", FileMode.OpenOrCreate)) { ser.WriteObject(fs, cn); // Serialization } }
static void Main(string[] args) // Deserialize from other file to demostrate the use of serialization { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Number.ComplexNumber)); // Json serializer FileStream fs = null; try { // Try/Catch to avoid exceptions fs = new FileStream(@"D:\repos\Lab4\Task1\ComNum.json", FileMode.Open); Number.ComplexNumber serCn = (Number.ComplexNumber)ser.ReadObject(fs); // Deserialization from .json serCn.Display(); } catch (FileNotFoundException e) { Console.WriteLine(e.Message); } catch (Exception) { Console.WriteLine("Unknown Error"); } finally { if (fs != null) // Closing stream anyway { fs.Close(); } } }