Is there a way to convert a System.IO.Stream to a Windows.Storage.Streams.IRandomAccessStream?

后端 未结 7 943
暖寄归人
暖寄归人 2020-11-30 00:42

In Windows 8; I would like to pass the contents of a MemoryStream to a class that accepts a parameter of type Windows.Storage.Streams.IRandomAccessStream. Is there any way t

7条回答
  •  天命终不由人
    2020-11-30 01:08

    After some experimenting I found the following code to be working.

    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Windows.Storage.Streams;
    
    partial class MainPage
    {
        public MainPage()
        {
            var memoryStream = new MemoryStream(new byte[] { 65, 66, 67 });
            ConvertToRandomAccessStream(memoryStream, UseRandomAccessStream);
            InitializeComponent();
        }
    
        void UseRandomAccessStream(IRandomAccessStream stream)
        {
            var size = stream.Size;
        } // put breakpoint here to check size
    
        private static async void ConvertToRandomAccessStream(MemoryStream memoryStream,
             Action callback)
        {
            var randomAccessStream = new InMemoryRandomAccessStream();
            var outputStream = randomAccessStream.GetOutputStreamAt(0);
            var dw = new DataWriter(outputStream);
            var task = new Task(() => dw.WriteBytes(memoryStream.ToArray()));
            task.Start();
            await task;
            await dw.StoreAsync();
            var success = await outputStream.FlushAsync();
            callback(randomAccessStream);
        }
    }
    

    UPDATE: I also tried more elegant method implementation:

        private static void ConvertToRandomAccessStream(MemoryStream memoryStream,
            Action callback)
        {
            var randomAccessStream = new InMemoryRandomAccessStream();
            var outputStream = randomAccessStream.GetOutputStreamAt(0);
            RandomAccessStream.Copy(memoryStream.AsInputStream(), outputStream);
            callback(randomAccessStream);
        }
    

    Strangely, it doesn't work. When I call stream.Size later, I get zero.

    UPDATE I changed the function to return the IRandomAccessStream rather than using the callback function

    public static async Task ConvertToRandomAccessStream(MemoryStream memoryStream)
    {
        var randomAccessStream = new InMemoryRandomAccessStream();
    
        var outputStream = randomAccessStream.GetOutputStreamAt(0);
        var dw = new DataWriter(outputStream);
        var task = new Task(() => dw.WriteBytes(memoryStream.ToArray()));
        task.Start();
    
        await task;
        await dw.StoreAsync();
    
        await outputStream.FlushAsync();
    
        return randomAccessStream;
    }
    

提交回复
热议问题