Not sure if this is the best option, but if you close the stream, and then catch the ObjectDisposedException, it handles it reasonably easily.
CANCEL UPLOAD LARGE FILE
Giorgio Sfiligoi
391
Reputation points
Here is code from: https://learn.microsoft.com/en-us/graph/sdks/large-file-upload?tabs=csharp
using var fileStream = System.IO.File.OpenRead(filePath);
// Use properties to specify the conflict behavior
// in this case, replace
var uploadProps = new DriveItemUploadableProperties
{
AdditionalData = new Dictionary<string, object>
{
{ "@microsoft.graph.conflictBehavior", "replace" }
}
};
// Create the upload session
// itemPath does not need to be a path to an existing item
var uploadSession = await graphClient.Me.Drive.Root
.ItemWithPath(itemPath)
.CreateUploadSession(uploadProps)
.Request()
.PostAsync();
// Max slice size must be a multiple of 320 KiB
int maxSliceSize = 320 * 1024;
var fileUploadTask =
new LargeFileUploadTask<DriveItem>(uploadSession, fileStream, maxSliceSize);
var totalLength = fileStream.Length;
// Create a callback that is invoked after each slice is uploaded
IProgress<long> progress = new Progress<long>(prog => {
Console.WriteLine($"Uploaded {prog} bytes of {totalLength} bytes");
});
try
{
// Upload the file
var uploadResult = await fileUploadTask.UploadAsync(progress);
Console.WriteLine(uploadResult.UploadSucceeded ?
$"Upload complete, item ID: {uploadResult.ItemResponse.Id}" :
"Upload failed");
}
catch (ServiceException ex)
{
Console.WriteLine($"Error uploading: {ex.ToString()}");
}
I would like to have the capability to cancel a long upload. The Graph documentation says that DeleteSessionAsync should do the job, so I added a button Cancel:
private async void OnCancel(object sender, EventArgs e)
{
await fileUploadTask.DeleteSessionAsync();
}
For this, I moved the declaration of fileUploadTask :
private LargeFileUploadTask<DriveItem> fileUploadTask;
DOES NOT WORK
I also tried to insert the DeleteSessionAsync instruction in the progress status loop - that should immediately abort upload:
IProgress<long> progress = new Progress<long>(async prog =>
{
ResultPage.message.AppendFormat($"Uploaded {prog} bytes of {totalLength} bytes\n");
UploadProgress = (float)prog / (float)totalLength;
await fileUploadTask.DeleteSessionAsync();
});
DOES NOT WORK
Any suggestion?
Developer technologies .NET Xamarin
5,380 questions
Microsoft Security Microsoft Graph
13,721 questions