comparison Stocks/Stocks.Common/Core/FileSerializer.cs @ 0:e5d46bb6cdb0

Initial commit
author adminSH stevenhollidge@hotmail.com
date Mon, 20 Feb 2012 13:52:35 +0700
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:e5d46bb6cdb0
1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4 using System.Runtime.Serialization;
5 using System.Text;
6 using Newtonsoft.Json;
7
8 namespace Stocks.Common.Core
9 {
10 public class FileSerializer
11 {
12 public void SerializeJson(string filename, object obj)
13 {
14 string json = JsonConvert.SerializeObject(obj);
15 Serialize(filename, json);
16 }
17
18 public void Serialize(string filename, string text)
19 {
20 using (StreamWriter writer = new StreamWriter(filename))
21 { writer.Write(text); }
22 }
23
24 public void Serialize(string filename, IFormatter formatter, object objectToSerialize)
25 {
26 using (Stream stream = File.Open(filename, FileMode.Create))
27 formatter.Serialize(stream, objectToSerialize);
28 }
29
30 public string Deserialize(string filename)
31 {
32 StringBuilder sb = new StringBuilder();
33 using (StreamReader reader = new StreamReader(filename))
34 if (reader != null)
35 sb.AppendLine(reader.ReadToEnd());
36
37 return sb.ToString();
38 }
39
40 public List<T> DeserializeJson<T>(string filename)
41 {
42 var json = Deserialize(filename);
43 return JsonConvert.DeserializeObject<List<T>>(json);
44 }
45
46 public T[] Deserialize<T>(string filename, IFormatter formatter, Type type)
47 {
48 using (Stream stream = File.Open(filename, FileMode.Open))
49 {
50 var items = (T[])formatter.Deserialize(stream);
51 return items;
52 }
53 }
54 }
55 }