IRandomAccessStream不支持CloneStream方法,因为它需要克隆,并且此流不支持克隆

时间:2018-01-05 15:11:53

标签: c# uwp stream

您好我正在构建一个UWP应用程序(目标10240和Microsoft.NETCore.UniversalWindowsPlatform 6.0.5),以下simiple代码抛出异常:

        var ms = new MemoryStream(new byte[16]);
        var randomAccessStream = RandomAccessStreamReference.CreateFromStream(ms.AsRandomAccessStream());                
        var newStream = await randomAccessStream.OpenReadAsync();

此代码抛出异常:

  Message=This IRandomAccessStream does not support the CloneStream method 
  because it requires cloning and this stream does not support cloning.

Source=System.Runtime.WindowsRuntime
  StackTrace:
   at System.IO.NetFxToWinRtStreamAdapter.ThrowCloningNotSuported(String methodName)
   at System.IO.NetFxToWinRtStreamAdapter.CloneStream()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

2 个答案:

答案 0 :(得分:1)

有人已回答过类似的问题: Is there a way to convert a System.IO.Stream to a Windows.Storage.Streams.IRandomAccessStream?

此代码解决了问题:

  private static async Task<IRandomAccessStreamReference> ConvertToRandomAccessStream(MemoryStream memoryStream)
    {
        var randomAccessStream = new InMemoryRandomAccessStream();
        var outputStream = randomAccessStream.GetOutputStreamAt(0);
        await RandomAccessStream.CopyAndCloseAsync(memoryStream.AsInputStream(), outputStream);
        var result = RandomAccessStreamReference.CreateFromStream(randomAccessStream);
        return result;
    }

答案 1 :(得分:0)

请参阅此How to: Convert Between .NET Framework Streams and Windows Runtime Streams

&#34;即使在转换后,.NET Framework流也不支持克隆。这意味着,如果将.NET Framework流转换为Windows运行时流并调用GetInputStreamAt或GetOutputStreamAt(调用CloneStream或直接调用CloneStream),则会发生异常。&#34;

下面的代码实际上创建了一个.NET Framework流。代码OpenReadAsync可能会在其中调用CloneStream,导致异常发生:

var ms = new MemoryStream(new byte[16]);

要解决此类问题,我们需要了解更多详细信息,以便我们可以帮助您修改代码。一般来说,您需要切换到Windows运行时流以避免此异常。