Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 15.01.2017, 02:04   #1
marluna
Пользователь
 
Регистрация: 15.12.2016
Сообщений: 50
По умолчанию сериализация десириализация

имею длл которая содержит сериализаторы
using ICSharpCode.SharpZipLib.BZip2;
using System;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Format ters;
using System.Runtime.Serialization.Format ters.Binary;

namespace yuan.YuanSerializationDataSet
{
public class SerializationDataSet
{
public static byte[] YuanSerialize(object obj)
{
byte[] result;
using (MemoryStream memoryStream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, obj);
memoryStream.Flush();
memoryStream.Position = 0L;
byte[] array = new byte[memoryStream.Length];
memoryStream.Read(array, 0, array.Length);
result = array;
}
return result;
}

public static object YuanDeserialize(byte[] buffer)
{
object result = new object();
using (MemoryStream memoryStream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.AssemblyFormat = FormatterAssemblyStyle.Simple;
binaryFormatter.Binder = new YuanBinder();
memoryStream.Position = 0L;
memoryStream.Write(buffer, 0, buffer.Length);
memoryStream.Position = 0L;
result = binaryFormatter.Deserialize(memoryS tream);
}
return result;
}

public static void YuanSerializeToFile<T>(T mClass, string mFilePath)
{
try
{
using (FileStream fileStream = new FileStream(mFilePath, FileMode.Create))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (BZip2OutputStream bZip2OutputStream = new BZip2OutputStream(fileStream))
{
using (MemoryStream memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStr eam, mClass);
byte[] array = memoryStream.ToArray();
bZip2OutputStream.Write(array, 0, array.Length);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}

public static T YuanDeserializeForFile<T>(string mFilePath)
{
T result;
try
{
T t = default(T);
if (File.Exists(mFilePath))
{
using (FileStream fileStream = new FileStream(mFilePath, FileMode.Open))
{
using (BZip2InputStream bZip2InputStream = new BZip2InputStream(fileStream))
{
using (new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
t = (T)((object)binaryFormatter.Deseria lize(bZip2InputStream));
}
}
}
}
result = t;
}
catch (Exception ex)
{
throw ex;
}
return result;
}

public static T YuanDeserializeForByte<T>(byte[] mByte)
{
T result;
try
{
T t = default(T);
using (MemoryStream memoryStream = new MemoryStream(mByte))
{
using (BZip2InputStream bZip2InputStream = new BZip2InputStream(memoryStream))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
t = (T)((object)binaryFormatter.Deseria lize(bZip2InputStream));
}
}
result = t;
}
catch (Exception ex)
{
throw ex;
}
return result;
}

public static byte[] Compress(byte[] data)
{
MemoryStream memoryStream = new MemoryStream();
GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true);
gZipStream.Write(data, 0, data.Length);
gZipStream.Close();
gZipStream.Dispose();
byte[] result = memoryStream.ToArray();
memoryStream.Close();
memoryStream.Dispose();
return result;
}

public static byte[] Decompress(byte[] data)
{
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(data, 0, data.Length);
memoryStream.Position = 0L;
GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress, true);
byte[] array = new byte[1024];
MemoryStream memoryStream2 = new MemoryStream();
for (int i = gZipStream.Read(array, 0, array.Length); i > 0; i = gZipStream.Read(array, 0, array.Length))
{
memoryStream2.Write(array, 0, i);
}
gZipStream.Close();
gZipStream.Dispose();
memoryStream.Close();
memoryStream.Dispose();
byte[] result = memoryStream2.ToArray();
memoryStream2.Close();
memoryStream2.Dispose();
return result;
}
}
}

есть сериализованый файл
десириализуем его
поток
WWW download;
System.Threading.Thread dataTherad;
byte[] myByte;

void SerializationData(){//Сериализация потоке
try{
//Начало декомпрессии (выгрузка содержимого бинарного массива myByte, в словарь dicGet)
Dictionary<string, yuan.YuanMemoryDB.YuanTable> dicGet = yuan.YuanSerializationDataSet.Seria lizationDataSet.YuanDeserializeForB yte<Dictionary<string, yuan.YuanMemoryDB.YuanTable>>(myByt e);
//Всё распаковано
Debug.Log("Записей в словаре: "+ dicGet.Count);
//Debug.Log("Ключей в словаре: "+ dicGet.Keys.Count);
DictSizeText.text = dicGet.Count.ToString();
int num = 0;//Счётчик таблиц
//int l = dicGet.Count;
foreach(KeyValuePair<string, yuan.YuanMemoryDB.YuanTable> item in YuanUnityPhoton.dicGetYT){//Перебор всего словаря загруженных данных, и перегрузка из него таблиц в базу YuanUnityPhoton.dicGetYT
item.Value.Rows = dicGet[item.Key].Rows;//

num++;
//Debug.Log(string.Format("{0}", (float)(num/l)));
//progressImage.fillAmount = (float)num/l;
}
progressAnimation.Stop();
Debug.Log(string.Format("Загружено таблиц: {0} ",num));//Число таблиц
TablesCountText.text = num.ToString();
//Загружаем список таблиц, в выпадающий список:
popUpBar.ListLoad();
}catch(System.Exception ex){
Debug.LogError(string.Format(ex.ToS tring()));
//return;
}
}


и вопрос как сохранить информацию из сериализованной базы данных в текстовый файл?

public void SaveDataFile()
{
if (filename == "") filename = "C:/Data/Save/Position.txt";
StreamWriter sw = new StreamWriter(filename); // Создаем файл
sw.WriteLine(transform.position.x); // Пишем координаты
sw.WriteLine(transform.position.y);
sw.WriteLine(transform.position.z);
//sw.Write(TableText.text);
sw.Close(); // Закрываем(сохраняем)
}

могу координаты сохранить...но понимания опыта знаний не хватает что бы сохранить таблицы. как десериализовать в файл..?
marluna вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Сериализация Лета C# (си шарп) 9 24.09.2014 14:13
Сериализация Gregor Компоненты Delphi 10 16.04.2011 12:18
Сериализация Вов@ныч Общие вопросы Delphi 2 06.07.2009 09:54
сериализация Crucian Общие вопросы C/C++ 5 18.11.2007 16:37