Advertisement
Tosker

ContactBook Finish - JsonContactDataService

Jul 18th, 2018
480
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.83 KB | None | 0 0
  1.     public class JsonContactDataService : IContactDataService
  2.     {
  3.         private readonly string _dataPath = "Resources/contactdata.json";
  4.  
  5.         public IEnumerable<Contact> GetContacts()
  6.         {
  7.             if (!File.Exists(_dataPath))
  8.             {
  9.                 File.Create(_dataPath).Close();
  10.             }
  11.  
  12.             var serializedContacts = File.ReadAllText(_dataPath);
  13.             var contacts = JsonConvert.DeserializeObject<IEnumerable<Contact>>(serializedContacts);
  14.  
  15.             if (contacts == null)
  16.                 return new List<Contact>();
  17.  
  18.             return contacts;
  19.         }
  20.  
  21.         public void Save(IEnumerable<Contact> contacts)
  22.         {
  23.             var serializedContacts = JsonConvert.SerializeObject(contacts);
  24.             File.WriteAllText(_dataPath, serializedContacts);
  25.         }
  26.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement