CANCEL UPLOAD LARGE FILE

Giorgio Sfiligoi 391 Reputation points
2022-06-03T17:27:01.547+00:00

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
Microsoft Security Microsoft Graph
{count} votes

1 answer

Sort by: Most helpful
  1. Jeremy Prestidge 0 Reputation points
    2023-01-26T05:46:18.5933333+00:00

    Not sure if this is the best option, but if you close the stream, and then catch the ObjectDisposedException, it handles it reasonably easily.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.