开发者

Serializing a simple array with XmlSerializer

Its late and fully possible I'm missing something obvious but what is it?

I'm trying to create a backing property which reveals an int array as serialized (which is then used to build up a Queue).

I'm pretty sure this is right but the getter always return a blank string, even when there are values in there (not that it should ever return a blank string.

Here is my code:

readonly Lazy<XmlSerializer> _queueSerializer = new Lazy<XmlSerializer>(() => new XmlSerializer(typeof(int[])));
[StringLength(1000)]
public string _MostRecentPlayers
{
    get
    {
        var stream = new MemoryStream();
        _queueSerializer.Value.Serialize(stream, _mostRecentPlayers.ToArray());
        return new StreamReader(stream).ReadToEnd();
    }
    set
    {
        if (value.IsEmpty())
        {
            _mostRecentPlayers.Clear();
            return;
        }
    开发者_如何学C    MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(value));
        var tempQueue = _queueSerializer.Value.Deserialize(stream) as int[];
        _mostRecentPlayers.Clear();
        tempQueue.ForEach(_mostRecentPlayers.Enqueue);
    }
}
readonly Queue<int> _mostRecentPlayers = new Queue<int>(_mostRecentAmountTracked);


You haven't rewound the stream; it is positioned at the end. Set .Position = 0 before reading it. Or easier, just serialize to a StringWriter, or if you really want to use a MemoryStream, pass the (oversized) backing array from GetBuffer() along with the .Length to an Encoding and call GetString().

using(var sw = new StringWriter()) {
    _queueSerializer.Value.Serialize(sw, _mostRecentPlayers.ToArray());
    xml = sw.ToString();
}

or for ASCII (see comments):

using(var ms = new MemoryStream()) {
    var settings = new XmlWriterSettings {
        Encoding = Encoding.ASCII
    };
    using(var xw = XmlWriter.Create(ms, settings)) {
        _queueSerializer.Value.Serialize(xw, _mostRecentPlayers.ToArray());
    }
    xml = Encoding.ASCII.GetString(ms.GetBuffer(), 0, (int)ms.Length);
}

Also, unless it is unlikely that you will serialize in the exe, I would suggest simplifying to just:

static readonly XmlSerializer _queueSerializer =new XmlSerializer(typeof(int[]));

Finally, note that xml is quite verbose as a mechansim to throw some ints around. CSV would seem a lot simpler (assuming you want text).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜