问题
Hi I'm building a UWP application (targeting 10240 and Microsoft.NETCore.UniversalWindowsPlatform 6.0.5) and the following simiple code throws an exception:
var ms = new MemoryStream(new byte[16]);
var randomAccessStream = RandomAccessStreamReference.CreateFromStream(ms.AsRandomAccessStream());
var newStream = await randomAccessStream.OpenReadAsync();
This code is throwing the exception:
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()
回答1:
Someone already answered a similar question in: Is there a way to convert a System.IO.Stream to a Windows.Storage.Streams.IRandomAccessStream?
This code solves the problem:
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;
}
回答2:
See this How to: Convert Between .NET Framework Streams and Windows Runtime Streams:
".NET Framework streams do not support cloning, even after conversion. This means that if you convert a .NET Framework stream to a Windows Runtime stream and call GetInputStreamAt or GetOutputStreamAt, which call CloneStream or call CloneStream directly, an exception will occur."
Your code below actually creates a .NET Framework stream. And the code OpenReadAsync may called CloneStream in it which caused the exception to occur:
var ms = new MemoryStream(new byte[16]);
To resolve this kind of problem we need to know more details so that we can help you modify your code. Genrally speaking, you need to switch to windows runtime stream to avoid this exception.
来源:https://stackoverflow.com/questions/48116297/irandomaccessstream-does-not-support-the-clonestream-method-because-it-requires