If you want to use BinaryFormatter
(which I really don't advise), you can use:
[Serializable]
class PicInfo
{
public string fileName { get; set; }
public string completeFileName { get; set; }
public string filePath { get; set; }
public byte[] hashValue { get; set; }
public PicInfo() { }
}
static class Program
{
static void Main()
{
List<PicInfo> pi = new List<PicInfo>();
pi.Add(new PicInfo {fileName = "foo.bar", hashValue = new byte[] {1, 2, 3}});
var ser = new BinaryFormatter();
using (var ms = new MemoryStream())
{
ser.Serialize(ms, pi);
var bytes = ms.ToArray();
}
}
}
If you want to use XmlSerializer
(probably preferable IMO), but need the byte[]
, then:
public class PicInfo
{
public string fileName { get; set; }
public string completeFileName { get; set; }
public string filePath { get; set; }
public byte[] hashValue { get; set; }
public PicInfo() { }
}
static class Program
{
static void Main()
{
List<PicInfo> pi = new List<PicInfo>();
pi.Add(new PicInfo {fileName = "foo.bar", hashValue = new byte[] {1, 2, 3}});
var ser = new XmlSerializer(typeof(List<PicInfo>));
using (var ms = new MemoryStream())
{
ser.Serialize(ms, pi);
var bytes = ms.ToArray();
}
}
}
Personally, I'd use protobuf-net:
[ProtoContract]
public class PicInfo
{
[ProtoMember(1)]public string fileName { get; set; }
[ProtoMember(2)]public string completeFileName { get; set; }
[ProtoMember(3)]public string filePath { get; set; }
[ProtoMember(4)]public byte[] hashValue { get; set; }
public PicInfo() { }
}
static class Program
{
static void Main()
{
List<PicInfo> pi = new List<PicInfo>();
pi.Add(new PicInfo {fileName = "foo.bar", hashValue = new byte[] {1, 2, 3}});
using (var ms = new MemoryStream())
{
Serializer.Serialize(ms, pi);
var bytes = ms.ToArray();
}
}
}
Sizes:
BinaryFormatter
: 488 bytes
XmlSerializer
: 251 bytes
- protobuf-net: 16 bytes
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…