Last active
June 22, 2017 01:52
-
-
Save bonjin6770/0932f5506204e25b46f7a3a7c0d18a4c to your computer and use it in GitHub Desktop.
Data Serializer Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Runtime.Serialization.Json; | |
using System.Text; | |
namespace Sample | |
{ | |
public static class DataSerializerSample | |
{ | |
public static SampleClass Load() | |
{ | |
var l = new SampleClass(); | |
if (!File.Exists(GetDataFilePath())) | |
{ | |
return l; | |
} | |
string json; | |
using (System.IO.StreamReader file = new System.IO.StreamReader(GetDataFilePath(), Encoding.UTF8)) | |
{ | |
json = file.ReadToEnd(); | |
} | |
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)); | |
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(SampleClass)); | |
l = ser.ReadObject(ms) as SampleClass; | |
ms.Close(); | |
return l; | |
} | |
public static void Save(SampleClass list) | |
{ | |
// ファイルが無い場合は空ファイルを作成します。 | |
if (!File.Exists(GetDataFilePath())) | |
{ | |
GetDataFilePath(); | |
} | |
byte[] json; | |
using (MemoryStream ms = new MemoryStream()) | |
{ | |
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(SampleClass)); | |
ser.WriteObject(ms, list); | |
json = ms.ToArray(); | |
} | |
using (System.IO.StreamWriter file = new System.IO.StreamWriter(GetDataFilePath())) | |
{ | |
file.WriteLine(Encoding.UTF8.GetString(json, 0, json.Length)); | |
} | |
} | |
private static string GetDataFilePath() | |
{ | |
var exePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); | |
return Path.Combine(exePath, "__DATA__.json"); | |
} | |
private static void CreateEmptyDataFile() | |
{ | |
File.Create(GetDataFilePath()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment