1

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;
        }
        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);

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

I just found a tip to use StringWriter elsewhere too. How do I specify it to use ASCII though?
@George - if it must be ASCII, then firstly note that you really need to spin up an XmlWriter explicitly - otherwise the encoding is wrong. I'll add an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.