How to append a Stream into file?

0

I have a stream I get from HTTP.

I would like to save each packet I receive and append it to the end of a file: "myData.dat"

I wrote the code below, and it runs each time a packet arrives.

private async void FrameReady( object sender, IBuffer DataBuffer )
{
    InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
    await stream.WriteAsync( DataBuffer );
    stream.Seek( 0 );
    using ( Stream file = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync( "myData.dat", CreationCollisionOption.OpenIfExists ) )
    {
        file.Seek( 0, SeekOrigin.End );
        var dataReader = new Windows.Storage.Streams.DataReader( stream );
        byte [] buffer = new byte [DataBuffer.Length];
        dataReader.ReadBytes( buffer );
        await file.WriteAsync( buffer, 0, (int)DataBuffer.Length );
    }
}

However, when running the code it fails on this line:

dataReader.ReadBytes( buffer );

The error message is:

The operation attempted to access data outside the valid range (Exception from HRESULT: 0x8000000B)

Not sure why is that? Any idea?

c#
c#-4.0
windows-8
windows-runtime
asked on Stack Overflow Jan 16, 2013 by (unknown user) • edited Jan 16, 2013 by (unknown user)

1 Answer

1

I've come across a similar problem with the ReadBytes function.

I'm using the following workaround which might be of help to someone.

private async Task<uint> ProcessBulkIn(Task<DataReader> task)
{
    byte[] rawData;
    DataReader b = await task;
    uint length = b.UnconsumedBufferLength;
    IBuffer iBuf = b.ReadBuffer(length);
    rawData = iBuf.ToArray();
    return length;
}

You will need to include the namespace for the ToArray function on IBuffer.

using System.Runtime.InteropServices.WindowsRuntime;
answered on Stack Overflow Aug 21, 2013 by spatial

User contributions licensed under CC BY-SA 3.0