I have a MemoryStream object that contains the contents of a file. I would like to convert it from a MemoryStream to a FileStream in order to pass it to MS Graph’s LargeFileUploadTask() method.
It seems that the method accepts the generic type called "Stream" so I tried using it as is, but it’s taking a very long time. In fact I get an HTTP timeout for larger streams.
I have another method similar to this one that also uses the LargeFileUploadTask and trying to upload the same file works – it’s using a FileStream (the difference between the two methods is that one writes to a local file, and then opens a filestream before sending to MS Graph, and the one here receives a memorystream as a parameter)
Code
private static async Task<Boolean> UploadInChunksToSharepoint(MemoryStream fileContents, string fileName)
....
// Max slice size must be a multiple of 320 KiB
int maxSliceSize = 320 * 204800 * 4;
var fileUploadTask =
new LargeFileUploadTask<DriveItem>(uploadSession, fileContents, maxSliceSize);
What I’ve Tried
In reading other posts, I see that there’s a WriteTo method in the fileContents object. So i tried something like this:
FileStream fileStream = new FileStream();
fileContents.WriteTo(fileStream);
But … I guess I can’t do that because the FileStream doesn’t allow you to just initialize without any parameters. If there’s a way… I’d like to be able to try this to compare apples to apples between the two methods to see why there’s such a time diff.
In the meantime, I’m poking around the rest of the code to see if there might be other deltas that I just missed.
>Solution :
The OP said the problem was that they forgot to rewind the MemoryStream before attempting to use it as the source of a HTTP request payload.
@Dai, that’s all it was. I reset position to 0. if you want to add as answer… i’ll accept
Gladly.
So watch out if you have this:
using( MemoryStream ms = new MemoryStream() )
{
using( StreamWriter wtr = new StreamWriter( ms, false ) )
{
CopyLoremIpsum( wtr );
}
await UploadStreamAsync( ms );
}
The StreamWriter (or any other writing action) will set the MemoryStream.Position to the end of the stream, where it cannot be read any further (basically as if you had a cassette tape movie or VHS played past the end-credits).
So make sure you reset .Position or use .Seek after writing to it, but before attempting to read from it:
using( MemoryStream ms = new MemoryStream() )
{
using( StreamWriter wtr = new StreamWriter( ms, false ) )
{
CopyLoremIpsum( wtr );
}
ms.Position = 0;
await UploadStreamAsync( ms );
}