Cameron
Cameron

Reputation: 184

Stream output to String

So I want to serialise a class which contains an IReadOnlyList<InkStroke> from Windows.UI.Input.Inking, as I'm working on a UWP app.

I'm using a DataContractSerializer to serialise my class, however I need to serialise the IReadOnlyList first, to a string or byte[], so that it can be serialised with the DataContractSerializer.

The most appropriate method of saving the strokes from a StrokeContainer is the StrokeContainer.SaveAsync() method, which takes in an IOutputStream.

How can I create an IOutputStream and then capture the output as a string or byte[]?

Below is the method I am trying to implement this functionality to:

private async Task<string> SerializeStrokes(InkCanvas canvas)
{
    IReadOnlyList<InkStroke> currentStrokes = canvas.InkPresenter
                                                    .StrokeContainer
                                                    .GetStrokes();

    if (currentStrokes.Count > 0)
    {
        string serializedString = string.Empty;

        using (IOutputStream outputStream = somethinghere)
        {
            await canvas.InkPresenter.StrokeContainer.SaveAsync(outputStream);
            await outputStream.FlushAsync();
        }

    // use some kind of stream reader to return contents of output ?
    }
    else
    {
        return string.Empty;
    }
}

Upvotes: 1

Views: 316

Answers (1)

lindexi
lindexi

Reputation: 4357

I think you can return a base64 string for the stream is binary.

The first is save it to stream

        var stream = new InMemoryRandomAccessStream();
        await canvas.InkPresenter.StrokeContainer.SaveAsync(stream);
        await stream.FlushAsync();

The last is change stream to base64

        var buffer = new byte[stream.Size];
        await stream.AsStream().ReadAsync(buffer, 0, buffer.Length);
        return Convert.ToBase64String(buffer);

Upvotes: 1

Related Questions