public Author Deserializing(string filePath) { string line = string.Empty; List<string> authorInfo = new List<string>(); using (StreamReader sr = new StreamReader(filePath)) { while ((line = sr.ReadLine()) != null) { authorInfo.Add(line); } } Author author = new Author(); author.Name = authorInfo[0]; author.Email = authorInfo[1]; for (int i = 2; i < authorInfo.Count; i++) { string[] bookInfo = authorInfo[i].Split('$'); var book = new Book(); book.Title = bookInfo[0]; book.PublishDate = DateTime.Parse(bookInfo[1]); author.Books.Add(book); } return author; }
static void Main(string[] args) { Book one = new Book(); one.Title = "Think and grow rich"; one.PublishDate = DateTime.Now; Book two = new Book(); two.Title = "The virgin way"; two.PublishDate = DateTime.Now.AddDays(23); List<Book> listbooks = new List<Book>() { one, two }; Author aut = new Author("Richard Branson", listbooks); string path = @"C:\Users\Ivan Ivanov\Documents\Visual Studio 2015\Projects\BooksAndAuthors\targ.txt"; aut.Deserializing(aut, path); }
//using Bulit in Deserialization for XML //public void Deserializing(Author author, string path) //{ // try // { // string xmlatt = string.Empty; // XmlDocument xmldoc = new XmlDocument(); // xmldoc.Load(path); // string xmlString = xmldoc.OuterXml; // using (StringReader reader = new StringReader(xmlString)) // { // XmlSerializer selializer = new XmlSerializer(author.GetType()); // using (XmlReader xmlreader = new XmlTextReader(reader)) // { // author = (Author)selializer.Deserialize(xmlreader); // xmlreader.Close(); // } // } // } // catch (Exception ex) // { // Console.WriteLine(ex.Message); // } //} // Using custom serialization //public void Serializing(Author author, string path) //{ // using (StreamWriter writer = new StreamWriter(path)) // { // writer.WriteLine(author.Name); // writer.WriteLine(author.Email); // string booksandDateTime = string.Empty; // foreach (var item in author.Books) // { // booksandDateTime = item.Title + "$" + item.PublishDate; // writer.WriteLine(booksandDateTime); // } // } //} public void Deserializing(Author author, string path) { using (StreamReader reader = new StreamReader(path)) { Author test = new Author(); test.Books = new List<Book>(); test.Name = reader.ReadLine(); test.Email = reader.ReadLine(); string[] books = new string[2]; while (true) { try { books = reader.ReadLine().Split('$'); } catch(NullReferenceException) { return; } DateTime time = DateTime.Parse(books[1]); Book book = new Book(); book.Title = books[0]; book.PublishDate = time; test.Books.Add(book); } } }