Is it possible to deserialize part of a binary file?
Basically I have an object similar to below, which I serialize into a binary file.
public class MyObject
{
public string Name { get; set; }
public int Value { get; set; }
public IList<MyOtherObject> { get; set; } // lots of data in here (order of kB-MB)
}
What I would like is to be able to deserialize only Name and Value by way of populating a ListView for file selection purposes and then deserialize the rest of the file when needed (i.e. the user chooses that file from the ListView).
As always, any help greatly appreciated and if any 3rd party libraries are suggested they would need to be able to be used freely in a commercial environment.
protobuf-net can do that, because it is not tied to the specific type; for example:
using ProtoBuf;
using System.Collections.Generic;
using System.IO;
[ProtoContract]
public class MyOtherObject { }
[ProtoContract]
public class MyObject
{
[ProtoMember(1)]
public string Name { get; set; }
[ProtoMember(2)]
public int Value { get; set; }
[ProtoMember(3)]
public IList<MyOtherObject> Items { get; set; }
}
[ProtoContract]
public class MyObjectLite
{
[ProtoMember(1)]
public string Name { get; set; }
[ProtoMember(2)]
public int Value { get; set; }
}
static class Program
{
static void Main()
{
var obj = new MyObject
{
Name = "abc",
Value = 123,
Items = new List<MyOtherObject>
{
new MyOtherObject(),
new MyOtherObject(),
new MyOtherObject(),
new MyOtherObject(),
}
};
using (var file = File.Create("foo.bin"))
{
Serializer.Serialize(file, obj);
}
MyObjectLite lite;
using (var file = File.OpenRead("foo.bin"))
{
lite= Serializer.Deserialize<MyObjectLite>(file);
}
}
}
But if you don't want two different types, and/or you don't want to have to add attributes - that can be done too:
using ProtoBuf.Meta;
using System.Collections.Generic;
using System.IO;
public class MyOtherObject { }
public class MyObject
{
public string Name { get; set; }
public int Value { get; set; }
public IList<MyOtherObject> Items { get; set; }
}
static class Program
{
static readonly RuntimeTypeModel fatModel, liteModel;
static Program()
{
// configure models
fatModel = TypeModel.Create();
fatModel.Add(typeof(MyOtherObject), false);
fatModel.Add(typeof(MyObject), false).Add("Name", "Value", "Items");
liteModel = TypeModel.Create();
liteModel.Add(typeof(MyOtherObject), false);
liteModel.Add(typeof(MyObject), false).Add("Name", "Value");
}
static void Main()
{
var obj = new MyObject
{
Name = "abc",
Value = 123,
Items = new List<MyOtherObject>
{
new MyOtherObject(),
new MyOtherObject(),
new MyOtherObject(),
new MyOtherObject(),
}
};
using (var file = File.Create("foo.bin"))
{
fatModel.Serialize(file, obj);
}
MyObject lite;
using (var file = File.OpenRead("foo.bin"))
{
lite = (MyObject)liteModel.Deserialize(
file, null, typeof(MyObject));
}
}
}
How about putting the Name and Valueinto a superclass and serializing them separately?
Alternatively, you could maintain a Dictionary and serialize that into one file.
Related
I am connecting to an external API which seems to be returning JSON
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances;
}
When I move over .Data.Balances, it shows:
IEnumerable<API.Net.Objects.Spot.SpotData.APIBalance>
API.Net.Objects.Spot.SpotData.APIAccountInfo.Balances { get; set; }
List of assets and their current balances
Here is an extract of the JSON data:
"balances":[
{
"asset":"ABC",
"free":"0.00000000",
"locked":"0.00000000"
},
{
"asset":"DEF",
"free":"0.00000000",
"locked":"0.00000000"
},
{
"asset":"GHI",
"free":"0.00000000",
"locked":"0.00000000"
}
]
How do I make use of this data so if I type console.writeline(data[0]["asset"]), it gives me ABC?
This seems to be the simplist solution:
using System.Linq;
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances.ToList();
Console.WriteLine(data[0].asset);
Console.WriteLine(data[0].free);
Console.WriteLine(data[0].locked);
}
Hy,
From the sample file you can create a class ´balance »
Public class balance
{
Public string asset {get; set;}
Public Free .......
Public Locked .....
}
And then you can use Json.net
To deserialize the JSon file
public void serializejson()
{
List balances = JsonConvert.DeserializeObject<List>(data);
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Game
{
public class Balance
{
[JsonPropertyName("asset")]
public string Asset { get; set; }
[JsonPropertyName("free")]
public string Free { get; set; }
[JsonPropertyName("locked")]
public string Locked { get; set; }
}
public class Root
{
[JsonPropertyName("balances")]
public List<Balance> Balances { get; set; }
}
class Program
{
static void Main(string[] args)
{
var data = File.ReadAllText("test.json");
var deserialized = JsonSerializer.Deserialize<Root>(data);
var balances = deserialized.Balances;
// Don't iterati in such a way! Use foreach instead.
for (int i = 0; i < balances.Count; i++)
{
Console.WriteLine($"{balances[i].Asset} {balances[i].Free} {balances[i].Locked}");
}
foreach (var balance in balances)
{
Console.WriteLine($"{balance.Asset} {balance.Free} {balance.Locked}");
}
}
}
}
You can use this code for you:
public class Balance {
public string asset { get; set; }
public string free { get; set; }
public string locked { get; set; }
}
public class Root {
public List<Balance> balances { get; set; }
}
And for deserialize:
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances;
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(data);
Console.WriteLine(myDeserializedClass.balances[0].asset);
}
I'm working on a c# application and trying to make this code working. It fails when it tries to copy a property which is a list of a subclass object.
I'm able to check the common properties in both classes and the code works fine for most types I've used, even List<string>. When I have properties of type e.g. List<SubClass>it fails. The code fails also for simple objects of the Subclass.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Questions
{
class Program
{
static void Main(string[] args)
{
Class1 class1 = new Class1
{
Prop1 = "X",
List1 = new List<Class1.SubClass>
{
new Class1.SubClass { SubProp1 = "A", SubProp2 = "B" }
}
};
Class2 class2 = class1.CopyTo<Class2>(); //---> fails when it tries to SetValue for the List<SubClass>
}
}
public class Class1
{
public string Prop1 { get; set; }
public List<SubClass> List1 { get; set; }
public string Prop3 { get; set; }
public class SubClass
{
public string SubProp1 { get; set; }
public string SubProp2 { get; set; }
}
}
public class Class2
{
public string Prop1 { get; set; }
public List<SubClass> List1 { get; set; }
public string Prop4 { get; set; }
public class SubClass
{
public string SubProp1 { get; set; }
public string SubProp2 { get; set; }
}
}
public static class Extensions
{
public static T CopyTo<T>(this Object sourceObject)
{
Type sourceObjectType = sourceObject.GetType();
Type targetType = typeof(T);
var targetInstance = Activator.CreateInstance(targetType, false);
List<PropertyInfo> identicalProperties = new List<PropertyInfo>();
var propertiesTarget = typeof(T).GetProperties();
var propertiesSource = sourceObject.GetType().GetProperties();
foreach (var s_property in propertiesSource)
{
foreach (var t_property in propertiesTarget)
{
if (s_property.Name.Equals(t_property.Name))
{
identicalProperties.Add(s_property);
continue;
}
}
}
object value;
foreach (PropertyInfo property in propertiesTarget)
{
var res = identicalProperties.Any(x=>x.Name.Equals(property.Name));
if (!res)
{
continue;
}
value = sourceObjectType.GetProperty(property.Name).GetValue(sourceObject, null);
property.SetValue(targetInstance, value, null);
}
return (T)targetInstance;
}
}
}
I assume this is achievable but I'm struggling to find a way to identify the type of property and when to cast the value to the correct type here property.SetValue(targetInstance, value, null);. value should probably be casted as a List.
The error thrown by the compiler is:
System.ArgumentException: 'Object of type 'System.Collections.Generic.List1[Questions.Class1+SubClass]' cannot be converted to type 'System.Collections.Generic.List1[Questions.Class2+SubClass]'
Can anyone help? Much appreciated.
In absence of further details or comments I would just like to feedback the final solution I'm adopting. Basically, the use of a outside defined class (instead an internal defined class) will allow the code to work but and provides a practical example how it can work based on this assumption. This is an workaround rather than the solution for my original question.
The example final code as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Questions
{
class Program
{
static void Main(string[] args)
{
Class1 class1 = new Class1
{
Prop1 = "X",
Prop2 = "Y",
List1 = new List<OutsideClass>
{
new OutsideClass { SubProp1 = "A", SubProp2 = "B" },
new OutsideClass { SubProp1 = "C", SubProp2 = "D" },
new OutsideClass { SubProp1 = "E", SubProp2 = "F" }
}
};
Class2 class2 = class1.CopyTo<Class2>();
}
}
public class Class1
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public List<OutsideClass> List1 { get; set; }
public string Prop3 { get; set; }
}
public class Class2
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public List<OutsideClass> List1 { get; set; }
public string Prop4 { get; set; }
}
public class OutsideClass
{
public string SubProp1 { get; set; }
public string SubProp2 { get; set; }
public override string ToString()
{
string text = string.Format("{0} ---> {1}", SubProp1, SubProp2);
return text;
}
}
public static class Extensions
{
public static T CopyTo<T>(this Object sourceObject)
{
Type sourceObjectType = sourceObject.GetType();
Type targetType = typeof(T);
var targetInstance = Activator.CreateInstance(targetType, false);
List<PropertyInfo> identicalProperties = new List<PropertyInfo>();
var propertiesTarget = typeof(T).GetProperties();
var propertiesSource = sourceObject.GetType().GetProperties();
foreach (var s_property in propertiesSource)
{
foreach (var t_property in propertiesTarget)
{
if (s_property.Name.Equals(t_property.Name))
{
identicalProperties.Add(s_property);
continue;
}
}
}
object value;
foreach (PropertyInfo property in propertiesTarget)
{
var res = identicalProperties.Any(x=>x.Name.Equals(property.Name));
if (!res)
{
continue;
}
value = sourceObjectType.GetProperty(property.Name).GetValue(sourceObject, null);
property.SetValue(targetInstance, value, null);
}
return (T)targetInstance;
}
}
}
All common properties will be copied from one class to the other (Prop3 and Prop4 will be disregarded as they only exist in each one of these classes).
I hope this can help anyone trying to do the same.
Please feel free to comment back and provide further details.
Thanks a lot for everyone comments.
Happy new year!
I have to pass following JSON format to the REST api.
"weconnect_validate":{
"Row":[
{"0":"44063fe6-fe22-11ea-bb30-005056923098::TEST10800::9888880470","1":"TEST10800"}
]
}
Now problem occurring here is that how i create class for
Row with variable name 0 and 1.
I have tried following
public class BasicRow
{
[JsonProperty("0")]
public string Zero { get; set; }
[JsonProperty("1")]
public string One { get; set; }
}
public class Weconnect_Validate
{
public BasicRow[] rows { get; set; }
}
but it is not working. In debug mode it is passing
Row:[{"Zero":......
Please suggest some tricks or different way to create c# class.
Edit
Following json object i need to send to REST api using http client .
{"PWSESSIONRS":{"PWPROCESSRS":{"PWDATA":{"weconnect_validate":{"Row":[{"0":"dc9a2d38-fe28-11ea-bb30-005056923098","1":"TEST10800"}]}},"PWHEADER":{"LOGIN_ID":"TEST10800","ORG_ID":"HSA","APP_ID":"HSA","IN_PROCESS_ID":"1","OUT_PROCESS_ID":"weconnect_validate"}}}}
My question is how to build c# classes for this type of json string or object.
QuickType.io suggested this, which is what my first thought was (Array of Dictionary<string, string>) given that your assertion that JsonProperty wasn't working:
namespace SomeNamespaceHere
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class RootClassNameHere
{
[JsonProperty("weconnect_validate")]
public WeconnectValidate WeconnectValidate { get; set; }
}
public partial class WeconnectValidate
{
[JsonProperty("Row")]
public Dictionary<string, string>[] Row { get; set; }
}
public partial class RootClassNameHere
{
public static RootClassNameHere FromJson(string json) => JsonConvert.DeserializeObject<RootClassNameHere>(json, SomeNamespaceHere.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this RootClassNameHere self) => JsonConvert.SerializeObject(self, SomeNamespaceHere.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
But I didn't actually encounter any problems using your proposed route:
with this code:
public class Row
{
[JsonProperty("0")]
public string Zero { get; set; }
[JsonProperty("1")]
public string One { get; set; }
}
public class WeconnectValidate
{
public List<Row> Row { get; set; }
}
public class Root
{
[JsonProperty("weconnect_validate")]
public WeconnectValidate WeconnectValidate { get; set; }
}
Used like:
var x = JsonConvert.SerializeObject(new Root()
{
WeconnectValidate = new WeconnectValidate()
{
Row = new List<Row>(){
new Row() { Zero = "a", One = "b" },
new Row() { Zero = "c", One = "d" }
}
}
});
With the latest Newtonsoft.Json
i have an application that has to deserialize an array of data wrapped in a "results" Root Object, using Netwonsoft.Json package from NuGet
The Json string is exactly this:
{"results":[{"Coin":"SBD","LP":0.000269,"PBV":-54.36,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true},{"Coin":"XMR","LP":0.027135,"PBV":11.44,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true}]}
This Json string is created from a Console App i made, i wanted it to look like this https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=BTC-NEO&tickInterval=hour
My class looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp2
{
public class Result
{
public string Coins { get; set; }
public decimal LastPrice { get; set; }
public decimal PercentBuyVolume { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
}
In the Main form i have a function to download from a URL that Json (i have XAMPP running Apache) and deserialize it in an array. And it looks like this:
private void DownloadBittrexData()
{
int PanelID = 0;
var Coin = new List<string>();
var LastPrice = new List<decimal>();
var PercentBuyVolume = new List<decimal>();
var MACD1M = new List<bool>();
var MACD30M = new List<bool>();
var MACD1H = new List<bool>();
var MACD1D = new List<bool>();
var client = new WebClient();
var URL = client.DownloadString("http://localhost/test.json");
Console.WriteLine("Json String from URL: " + URL);
var dataDeserialized = JsonConvert.DeserializeObject<RootObject>(URL);
foreach (var data in dataDeserialized.results)
{
Coin.Add(data.Coins);
LastPrice.Add(data.LastPrice);
PercentBuyVolume.Add(data.PercentBuyVolume);
}
int sizeOfArrayClose = Coin.Count - 1;
for (int i = 0; i <= sizeOfArrayClose; i++)
{
Console.WriteLine("Coin: " + Coin[i]);
Console.WriteLine("Lastprice: " + LastPrice[i]);
Console.WriteLine("PBV: " + PercentBuyVolume[i]);
}
}
Newtonsoft.Json is of course declared at the beginning of the form together with System.Net
using System.Net;
using Newtonsoft.Json;
The output looks like this:
Json String from URL: {"results":[{"Coin":"SBD","LP":0.000269,"PBV":-54.36,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true},{"Coin":"XMR","LP":0.027135,"PBV":11.44,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true}]}
Coin:
Lastprice: 0
PBV: 0
Coin:
Lastprice: 0
PBV: 0
It's like it fails to deserialize it after downloading it.
What should i do? Thank you very much.
Your property names don't map to the field names in the JSON. You could rename your C# properties to match the JSON, but it would make for unreadable downstream code.
Instead, you should map your properties (with nice, readable names) to the names that appear in the JSON, using JsonPropertyAttribute:
public class Result
{
public string Coin { get; set; } //didn't bother here: changed property name to Coin
[JsonProperty("LP")]
public decimal LastPrice { get; set; }
[JsonProperty("PBV")]
public decimal PercentBuyVolume { get; set; }
}
your model should be like this for deserialize json
public class Result
{
public string Coin { get; set; }
public double LP { get; set; }
public double PBV { get; set; }
public bool MACD1M { get; set; }
public bool MACD30M { get; set; }
public bool MACD1H { get; set; }
public bool MACD1D { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
LastPrice and PercentBuyVolume are not available in your model that's the reason it's getting an error.
I tried your exact code on my system and I was able to retrieve the result as expected. Hope this helps, It's easy to understand.
Here is the main class
static void Main(string[] args)
{
RootObject configfile = LoadJson();
foreach (var tResult in configfile.results)
{
Console.WriteLine("Coin: " + tResult.Coin);
Console.WriteLine("Lastprice: " + tResult.LP);
Console.WriteLine("PBV: " + tResult.PBV);
}
Console.ReadLine();
}
LoadJson Function would be
private static RootObject LoadJson()
{
string json = "{\"results\":[{\"Coin\":\"SBD\",\"LP\":0.000269,\"PBV\":-54.36,\"MACD1M\":true,\"MACD30M\":true,\"MACD1H\":true,\"MACD1D\":true},{\"Coin\":\"XMR\",\"LP\":0.027135,\"PBV\":11.44,\"MACD1M\":true,\"MACD30M\":true,\"MACD1H\":true,\"MACD1D\":true}]}";
RootObject configs = Deserialize<RootObject>(json);
return configs;
}
and Deserialize function would be
private static T Deserialize<T>(string json)
{
T unsecureResult;
string _DateTypeFormat = "yyyy-MM-dd HH:mm:ss";
DataContractJsonSerializerSettings serializerSettings = new DataContractJsonSerializerSettings();
DataContractJsonSerializer serializer;
MemoryStream ms;
unsecureResult = default(T);
serializerSettings.DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat(_DateTypeFormat);
serializer = new DataContractJsonSerializer(typeof(T));
ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
unsecureResult = (T)serializer.ReadObject(ms);
return unsecureResult;
}
and Now your Datamodel would be
public class Result
{
public string Coin { get; set; }
public double LP { get; set; }
public double PBV { get; set; }
public bool MACD1M { get; set; }
public bool MACD30M { get; set; }
public bool MACD1H { get; set; }
public bool MACD1D { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
I have an Album class which contains title, description and an integer value of the index of a cover image. It also contains an imageList.
I need to serialize this obj and while the imageList is not serializeable but the imageListStream is...
I'm a complete c# noob so would appreciate what ever guidance available.
The desired result would be somethings like:
<Album>
<Title>Album Title</Title>
<Description>Some explanation.</Description>
<CoverImgIndx>2</CoverImgIdx>
<Images>
<Image>
<indx>0</indx>
<filepath>"C:\Images\file1.jpg"</filepath>
</Image>
<Image>
<indx>1</indx>
<filepath>"C:\Images\file2.png"</filepath>
</Image>
<Image>
<indx>2</indx>
<filepath>"C:\Images\file3.jpg"</filepath>
</Image>
<Image>
<indx>3</indx>
<filepath>"C:\Images\file4.bmp"</filepath>
</Image>
</Images>
</Album>
obviously I need to reconstitute the imageList when deserializing...
Sounds like you simply need to use the XmlSerializer class to serialize your Album class into XML.
Something like this should work: https://dotnetfiddle.net/yE8RAl
Generally speaking you can define your Album / Image like this:
[XmlType(TypeName = "Image")]
public class ImageSerializationContainer
{
[XmlElement(ElementName = "indx")]
public int Index { get; set; }
[XmlElement(ElementName = "filepath")]
public string FilePath { get; set; }
}
[XmlType(TypeName = "Album")]
public class AlbumSerializationContainer
{
public string Title { get; set; }
public string Description { get; set; }
public int CoverImgIndx { get; set; }
public List<ImageSerializationContainer> Images { get; set; }
}
And then use XmlSerializer like this:
XmlSerializer ser = new XmlSerializer(typeof(AlbumSerializationContainer));
StringWriter sw = new StringWriter();
ser.Serialize(sw, yourObjectToSerialize);
return sw.ToString();
However I'm guessing that what you really want is to somehow convert your existing class in a form that you can serialize.
Unfortunately you don't give a lot to go on in your question, so I have to make some assumptions. Now, some of this assumptions are bound to be wrong, but that's to be expected with the level of information you have provided.
I'm going to assume that you are using the ImageList class and that the filenames that you have in your example are stored in a string array that is attached to the ImageList Tag property. Feel free to modify the code to take this value from elsewhere. You did not give information about how you structure your index values. I'm assuming these are indexes in the ImageList.Images collection.
There are several ways to approach your problem. I'm going to show you how to use AutoMapper to convert what could be your class to a class that you can serialize and then serialize it.
Below you can find a complete example. Please note that you might need to update the AutoMapper configuration if your classes are different from presented below.
I'm demonstrating both: serializing an class to XML (example 1) and converting another class to serializable class (example 2).
using System;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.Collections.Generic;
using AutoMapper;
namespace SO24174411
{
class Program
{
static void Main()
{
AlbumSerializationContainer example1 = new AlbumSerializationContainer
{
CoverImgIndx = 2,
Description = "Some explanation.",
Images = new List<ImageSerializationContainer>
{
new ImageSerializationContainer {FilePath = #"C:\Images\file1.jpg", Index = 0},
new ImageSerializationContainer {FilePath = #"C:\Images\file2.png", Index = 1},
new ImageSerializationContainer {FilePath = #"C:\Images\file3.jpg", Index = 2},
new ImageSerializationContainer {FilePath = #"C:\Images\file4.bmp", Index = 3}
},
Title = "Album Title"
};
Console.WriteLine("Example 1");
Console.WriteLine(Serialize(example1));
Album album = new Album
{
CoverImgIndx = 2,
Description = "Some explanation.",
Images = new ImageList(),
Title = "Album Title"
};
SetImages(album.Images, new[]
{
#"C:\Images\file1.jpg",
#"C:\Images\file1.jpg",
#"C:\Images\file2.png",
#"C:\Images\file4.bmp"
});
var example2 = PerformMapping(album);
Console.WriteLine("Example 2");
Console.WriteLine(Serialize(example2));
}
private static AlbumSerializationContainer PerformMapping(Album album)
{
Mapper.CreateMap<Album, AlbumSerializationContainer>();
Mapper.CreateMap<ImageList, List<ImageSerializationContainer>>().ConvertUsing<ImageListconverter>();
AlbumSerializationContainer example2 = Mapper.Map<AlbumSerializationContainer>(album);
return example2;
}
public class ImageListconverter : TypeConverter<ImageList, List<ImageSerializationContainer>>
{
protected override List<ImageSerializationContainer> ConvertCore(ImageList source)
{
if (source == null)
{
return null;
}
List<ImageSerializationContainer> result = new List<ImageSerializationContainer>();
for (int i = 0; i < source.Images.Count; i++)
{
result.Add(new ImageSerializationContainer { FilePath = ((string[])source.Tag)[i], Index = i });
}
return result;
}
}
public static string Serialize(AlbumSerializationContainer a)
{
XmlSerializer ser = new XmlSerializer(typeof(AlbumSerializationContainer));
StringWriter sw = new StringWriter();
ser.Serialize(sw, a);
return sw.ToString();
}
public static void SetImages(ImageList l, string[] names)
{
l.Tag = names;
for(int i=0;i<names.Length;i++)
{
// Aparently you can read names[i] file here if you want
l.Images.Add(new Bitmap(1, 1));
}
}
}
public class Album
{
public string Title { get; set; }
public string Description { get; set; }
public int CoverImgIndx { get; set; }
public ImageList Images { get; set; }
}
[XmlType(TypeName = "Image")]
public class ImageSerializationContainer
{
[XmlElement(ElementName = "indx")]
public int Index { get; set; }
[XmlElement(ElementName = "filepath")]
public string FilePath { get; set; }
}
[XmlType(TypeName = "Album")]
public class AlbumSerializationContainer
{
public string Title { get; set; }
public string Description { get; set; }
public int CoverImgIndx { get; set; }
public List<ImageSerializationContainer> Images { get; set; }
}
}
You will be able to easily de-serialize your xml back to the serialization container class with XmlSerializer.Deserialize. Some more work will be required to map these back to your required class. Since this part depends more than any other on the information you have not provided I leave it as an exercise for the reader.