BinaryFormatter
를 사용하여 데이터를 직렬화/역직렬화하는 스크립트
namespace Utils.Data
{
public class BinaryConverter
{
public byte[] SerializeCompressed<T>(T value)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, value);
using (MemoryStream input = new MemoryStream(ms.ToArray()))
using (MemoryStream output = new MemoryStream())
{
using (GZipStream compression = new GZipStream(output, CompressionMode.Compress))
{
input.CopyTo(compression);
}
return output.ToArray();
}
}
}
public T DeserializeCompressed<T>(byte[] bytes)
{
using (var inStream = new MemoryStream(bytes))
using (var zipStream = new GZipStream(inStream, CompressionMode.Decompress))
using (var outStream = new MemoryStream())
{
zipStream.CopyTo(outStream);
BinaryFormatter bf = new BinaryFormatter();
outStream.Position = 0;
var deserialized = bf.Deserialize(outStream);
T result = (T)deserialized;
zipStream.Close();
return result;
}
}
public void SaveToPath(string path, string fileName, byte[] bytes)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
File.WriteAllBytes(path + fileName, bytes);
}
public byte[] LoadFromPath(string path)
{
return File.ReadAllBytes(path);
}
public FileInfo[] ReadFilesFromDirectory(string dir, string pattern)
{
if (!Directory.Exists(dir))
{
return null;
}
DirectoryInfo di = new DirectoryInfo(dir);
return di.GetFiles(pattern);
}
public void DeleteFileAtPath(string path)
{
File.Delete(path);
}
public string GetFileName(FileInfo info)
{
return Path.GetFileNameWithoutExtension(info.FullName);
}
}
}