private static DriveItem UploadFileInChunks(IGraphServiceClient graphClient, byte[] content, string userId, string fileName, string parentFolderId, bool renameIfExists) { if (content == null || content.Length == 0) { // Create an empty file Dictionary additionalData = new Dictionary(); if (renameIfExists) { additionalData.Add("@microsoft.graph.conflictBehavior", "rename"); } else { additionalData.Add("@microsoft.graph.conflictBehavior", "replace"); } DriveItem driveItem = new DriveItem { Name = fileName, File = new File(), AdditionalData = additionalData }; DriveItem newFile = graphClient.Users[userId].Drive.Items[parentFolderId].Children.Request() .AddAsync(driveItem).Result; return newFile; } // Upload the file in chunks using (MemoryStream stream = new MemoryStream(content)) { DriveItem createdFile = null; ChunkedUploadProvider provider = null; try { if (renameIfExists) { // Create a new file with conflict behaviour 'rename'. // This will cause OneDrive to create an empty file with a new name in case a file with that name exists. DriveItem driveItem = new DriveItem { Name = fileName, File = new File(), AdditionalData = new Dictionary { { "@microsoft.graph.conflictBehavior", "rename" } } }; DriveItem newFile = graphClient.Users[userId].Drive.Items[parentFolderId].Children.Request() .AddAsync(driveItem).Result; fileName = newFile.Name; } // Create the upload session UploadSession uploadSession = graphClient.Users[userId].Drive.Items[parentFolderId] .ItemWithPath(fileName).CreateUploadSession().Request().PostAsync().Result; const int maxChunkSize = 16 * 320 * 1024; // 5MB max chunk size (default value) provider = new ChunkedUploadProvider(uploadSession, graphClient, stream, maxChunkSize); // Setup the chunk request necessities IEnumerable chunkRequests = provider.GetUploadChunkRequests(); List trackedExceptions = new List(); // Upload the chunks foreach (UploadChunkRequest request in chunkRequests) { // Send chunk request UploadChunkResult result = provider.GetChunkRequestResponseAsync(request, trackedExceptions) .Result; if (result.UploadSucceeded) { createdFile = result.ItemResponse; } } } finally { // If the file was not created successfully, the session might still be open => try to delete it. // If the session stays open OneDrive won't create a new one for the same file until the session expired. if (createdFile == null && provider?.Session != null) { try { provider.DeleteSession(); } catch (Exception ex) { _log.LogError(ex); } } } return createdFile; } }