private async Task <DriveItem> UploadLargeFileAsync(Stream stream, DriveItemUploadableProperties properties, string filePath) { var uploadSession = await this.GraphClient.Drive.Root.ItemWithPath(filePath).CreateUploadSession(properties).Request().PostAsync(); var maxChunkSize = 1280 * 1024; // 1280 KB - Change this to your chunk size. 5MB is the default. var provider = new ChunkedUploadProvider(uploadSession, this.GraphClient, stream, maxChunkSize); var chunkRequests = provider.GetUploadChunkRequests(); var readBuffer = new byte[maxChunkSize]; var trackedExceptions = new List <Exception>(); DriveItem driveItem = null; // upload the chunks foreach (var request in chunkRequests) { // Do your updates here: update progress bar, etc. // ... // Send chunk request var result = await provider.GetChunkRequestResponseAsync(request, readBuffer, trackedExceptions); if (result.UploadSucceeded) { driveItem = result.ItemResponse; } } // check that upload succeeded if (driveItem == null) { throw new Exception(); } return(driveItem); }
public async Task OneDriveUploadLargeFile() { try { System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter(); var buff = (byte[])converter.ConvertTo(Microsoft.Graph.Test.Properties.Resources.hamilton, typeof(byte[])); using (System.IO.MemoryStream ms = new System.IO.MemoryStream(buff)) { // Describe the file to upload. Pass into CreateUploadSession, when the service works as expected. var props = new DriveItemUploadableProperties(); //props.Name = "_hamilton.png"; //props.Description = "This is a pictureof Mr. Hamilton."; //props.FileSystemInfo = new FileSystemInfo(); //props.FileSystemInfo.CreatedDateTime = System.DateTimeOffset.Now; //props.FileSystemInfo.LastModifiedDateTime = System.DateTimeOffset.Now; props.AdditionalData = new Dictionary <string, object>(); props.AdditionalData.Add("@microsoft.graph.conflictBehavior", "rename"); // Get the provider. // POST /v1.0/drive/items/01KGPRHTV6Y2GOVW7725BZO354PWSELRRZ:/_hamiltion.png:/microsoft.graph.createUploadSession // The CreateUploadSesssion action doesn't seem to support the options stated in the metadata. This issue has been filed. var uploadSession = await graphClient.Drive.Items["01KGPRHTV6Y2GOVW7725BZO354PWSELRRZ"].ItemWithPath("_hamilton.png").CreateUploadSession().Request().PostAsync(); var maxChunkSize = 320 * 1024; // 320 KB - Change this to your chunk size. 5MB is the default. var provider = new ChunkedUploadProvider(uploadSession, graphClient, ms, maxChunkSize); // Setup the chunk request necessities var chunkRequests = provider.GetUploadChunkRequests(); var readBuffer = new byte[maxChunkSize]; var trackedExceptions = new List <Exception>(); DriveItem itemResult = null; //upload the chunks foreach (var request in chunkRequests) { // Do your updates here: update progress bar, etc. // ... // Send chunk request var result = await provider.GetChunkRequestResponseAsync(request, readBuffer, trackedExceptions); if (result.UploadSucceeded) { itemResult = result.ItemResponse; } } // Check that upload succeeded if (itemResult == null) { // Retry the upload // ... } } } catch (Microsoft.Graph.ServiceException e) { Assert.Fail("Something happened, check out a trace. Error code: {0}", e.Error.Code); } }
public async Task UploadDocumentAsync(string directory, string fileName, Stream content) { // Based on example at https://docs.microsoft.com/en-us/graph/sdks/large-file-upload?tabs=csharp var filePath = $"{directory}/{fileName}"; var uploadProps = new DriveItemUploadableProperties { ODataType = null, 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 _client.Drives[_fileStorageConfig.DriveId].Root .ItemWithPath(filePath) .CreateUploadSession(uploadProps) .Request() .PostAsync(); // Max slice size must be a multiple of 320 KiB int maxSliceSize = 320 * 1024; var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, content, maxSliceSize); _logger.LogInformation($"Starting upload file to drive {_fileStorageConfig.DriveId} on path {filePath}"); // Create a callback that is invoked after each slice is uploaded IProgress <long> progress = new Progress <long>(progress => { _logger.LogDebug($"Uploaded {progress} bytes of stream"); }); try { var uploadResult = await fileUploadTask.UploadAsync(progress); if (uploadResult.UploadSucceeded) { _logger.LogInformation($"Uploading file to drive {_fileStorageConfig.DriveId} on path {directory} succeeded (item id: {uploadResult.ItemResponse.Id}"); } else { _logger.LogError($"Uploading file to drive {_fileStorageConfig.DriveId} on path {directory} failed."); throw new CodedException("UploadFailed", "Upload failed", $"Uploading file to drive {_fileStorageConfig.DriveId} on path {directory} failed."); } } catch (TaskCanceledException ex) { _logger.LogError($"Uploading file to drive {_fileStorageConfig.DriveId} on path {directory} failed: {ex.ToString()}"); throw ex; } catch (ServiceException ex) { _logger.LogError($"Uploading file to drive {_fileStorageConfig.DriveId} on path {directory} failed: {ex.ToString()}"); throw ex; } }
public async void UploadToOneDrive(string filepath, string onedrivepath) { var graphServiceClient = new GraphServiceClient( new DelegateAuthenticationProvider((requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", AccessToken); return(Task.CompletedTask); })); //GraphServiceClient graphClient = new GraphServiceClient("https://graph.microsoft.com/v1.0", new DelegateAuthenticationProvider(async (requestMessage) => //{ // requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", AccessToken); //})); using (var fileStream = System.IO.File.OpenRead(filepath)) { // Use properties to specify the conflict behavior // in this case, replace var uploadProps = new DriveItemUploadableProperties { ODataType = null, 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 graphServiceClient.Me.Drive.Root.ItemWithPath(onedrivepath).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); try { // Upload the file var uploadResult = await fileUploadTask.UploadAsync(); if (uploadResult.UploadSucceeded) { toolStripStatusLabel1.Text = filepath + " 上传成功"; } else { MessageBox.Show("上传失败,请检查网络!"); } } catch (ServiceException ex) { MessageBox.Show($"在上传过程中出现错误: {ex}"); } } }
public static async Task <DriveItem> UploadDocumentAsync(IDriveItemRequestBuilder driveItemRequestBuilder, string filename, Stream fileStream, string conflictBehaviour = ConflictBehaviour.Rename) { UploadSession uploadSession = null; try { var uploadProps = new DriveItemUploadableProperties { ODataType = null, AdditionalData = new Dictionary <string, object> { ["@microsoft.graph.conflictBehavior"] = conflictBehaviour } }; uploadSession = await driveItemRequestBuilder .ItemWithPath(filename) .CreateUploadSession(uploadProps) .Request() .PostAsync(); } catch (ServiceException ex) { throw new Exception("An error occured while creating upload session.", ex); } if (uploadSession == null) { throw new Exception("Upload session is null."); } try { // Performs upload, slice by slice int maxSliceSize = 5 * 1024 * 1024; //5MB var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, fileStream, maxSliceSize); var uploadResult = await fileUploadTask.UploadAsync(); if (!uploadResult.UploadSucceeded) { throw new Exception("File upload failed!"); } else { return(uploadResult.ItemResponse); } } catch (Exception ex) { throw new Exception("An error occurred while trying to upload document.", ex); } }
public UploadResult <DriveItem> ReplaceLargeFile(DriveItem item, Stream stream) { UploadResult <DriveItem> uploadResult = null; using (var fileStream = (FileStream)stream) { var uploadProps = new DriveItemUploadableProperties { ODataType = null, AdditionalData = new Dictionary <string, object> { { "@microsoft.graph.conflictBehavior", "replace" } } }; var uploadSession = graphClient.Drive.Root .ItemWithPath(item.Name) .CreateUploadSession(uploadProps) .Request() .PostAsync(); int maxSliceSize = 320 * 1024; var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession.Result, fileStream, maxSliceSize); IProgress <long> progress = new Progress <long>(slice => { Console.WriteLine($"Uploaded {slice} bytes of {fileStream.Length} bytes"); }); try { uploadResult = fileUploadTask.UploadAsync(progress).Result; if (uploadResult.UploadSucceeded) { Console.WriteLine($"Upload complete, item ID: {uploadResult.ItemResponse.Id}"); } else { Console.WriteLine("Upload failed"); } } catch (ServiceException ex) { Console.WriteLine($"Error uploading: {ex.ToString()}"); } } return(uploadResult); }
public async Task UploadLargeFileAsync(string siteUrl, string pathToFile) { var uriSite = new Uri(siteUrl); var siteCollection = await graphServiceClient.Sites.GetByPath(uriSite.AbsolutePath, uriSite.Host).Request().GetAsync(); var drive = graphServiceClient.Sites[siteCollection.Id].Drive.Root; using var fileStream = new FileStream(pathToFile, FileMode.Open, FileAccess.Read); var uploadProps = new DriveItemUploadableProperties { ODataType = null, AdditionalData = new Dictionary <string, object> { { "@microsoft.graph.conflictBehavior", "replace" } } }; var uploadSession = await drive .ItemWithPath("Engagement Request File/AuvenirApis.docx") .CreateUploadSession(uploadProps) .Request() .PostAsync(); int maxSliceSize = 320 * 1024; var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, fileStream, maxSliceSize); IProgress <long> progress = new Progress <long>(progress => { Console.WriteLine($"Uploaded {progress} bytes of {fileStream.Length} bytes"); }); try { var uploadResult = await fileUploadTask.UploadAsync(progress); if (uploadResult.UploadSucceeded) { Console.WriteLine($"Upload complete, item ID: {uploadResult.ItemResponse.Id}"); } else { Console.WriteLine("Upload failed"); } } catch (ServiceException ex) { Console.WriteLine($"Error uploading: {ex.ToString()}"); } }
public async Task <DriveItem> CreateOrUpdateAsync(DriveItem driveItem) { DriveItem newDriveItem = null; using (var stream = File.OpenRead(driveItem.Uri().AbsolutePath)) { if (driveItem.Size <= 4 * 1024 * 1024) // file.Length <= 4 MB { newDriveItem = await this.UploadSmallFileAsync(driveItem, stream); } else { var properties = new DriveItemUploadableProperties() { FileSystemInfo = driveItem.FileSystemInfo }; newDriveItem = await this.UploadLargeFileAsync(stream, properties, driveItem.Uri().AbsolutePath); } } return(newDriveItem); }
/// <summary> /// The deserialization information for the current model /// </summary> public IDictionary <string, Action <IParseNode> > GetFieldDeserializers() { return(new Dictionary <string, Action <IParseNode> > { { "item", n => { Item = n.GetObjectValue <DriveItemUploadableProperties>(DriveItemUploadableProperties.CreateFromDiscriminatorValue); } }, }); }
/// <summary> /// Allows you to send files to sharepoint. Repository: https://github.com/MarcinMichnik-HiQ/Frends.Office /// </summary> /// <param name="input"></param> /// <returns>Returns JToken.</returns> public static async Task <JToken> ExportFileToSharepoint(ExportFileToSharepointInput input) { IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder .Create(input.clientID) .WithTenantId(input.tenantID) .WithClientSecret(input.clientSecret) .Build(); ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication); // Create a new instance of GraphServiceClient with the authentication provider. IGraphServiceClient graphClient = new GraphServiceClient(authProvider); string fileLength; string url = ""; // Get fileName from the sourceFilePath string[] sourcePathSplit = input.sourceFilePath.Split('\\'); string fileName = sourcePathSplit.Last(); try { using (FileStream fileStream = System.IO.File.OpenRead(input.sourceFilePath)) { fileLength = fileStream.Length.ToString(); try { // Use properties to specify the conflict behavior // in this case, replace DriveItemUploadableProperties uploadProps = new DriveItemUploadableProperties { ODataType = null, 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 UploadSession uploadSession = await graphClient .Sites[input.siteID] .Drives[input.driveID] .Root .ItemWithPath(input.targetFolderPath + fileName) .CreateUploadSession(uploadProps) .Request() .PostAsync(); // Max slice size must be a multiple of 320 KiB int maxSliceSize = 320 * 2048; LargeFileUploadTask <DriveItem> fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, fileStream, maxSliceSize); // Create a callback that is invoked after each slice is uploaded IProgress <long> progress = new Progress <long>(); url = uploadSession.UploadUrl; try { // Upload the file UploadResult <DriveItem> uploadResult = await fileUploadTask.UploadAsync(progress); } catch (ServiceException ex) { await fileUploadTask.DeleteSessionAsync(); throw new Exception("Unable to send file.", ex); } } catch (ServiceException ex) { throw new Exception("Unable to establish connection to Sharepoint.", ex); } } } catch (ServiceException ex) { throw new Exception("Unable to open file.", ex); } JToken taskResponse = JToken.Parse("{}"); taskResponse["FileSize"] = fileLength; taskResponse["Path"] = input.sourceFilePath.ToString(); taskResponse["FileName"] = fileName.ToString(); taskResponse["TargetFolderName"] = input.targetFolderPath.ToString(); taskResponse["ClientID"] = input.clientID; taskResponse["TenantID"] = input.tenantID.ToString(); taskResponse["SiteID"] = input.siteID.ToString(); taskResponse["DriveID"] = input.driveID.ToString(); taskResponse["UploadUrl"] = url; return(taskResponse); }
static bool RecurseUploadData(string LocalPath, string RemotePath, bool SkipFailed) { if (TestLogin() == false) { return(false); } List <FileSystemInfos> RemoteFiles = ListFiles(RemotePath); if (RemoteFiles == null) { return(false); } StatNumDirProcessed++; foreach (string LPath in System.IO.Directory.EnumerateDirectories(LocalPath, "*.*", System.IO.SearchOption.TopDirectoryOnly)) { string RP = RemotePath; RP += "/"; string PathOnly = LPath.Substring(LPath.LastIndexOf("\\") + 1); RP += PathOnly; if (PathOnly.StartsWith(" ") == true) { continue; } MarkAsProcessed(RemoteFiles, PathOnly, true); //Create dir in AZ string RemotePathDotDot = RP.Substring(0, RP.LastIndexOf("/")); Drive drv = QuerySync <Drive>(graphClient.Drive.Request().GetAsync()); DriveItem newcreateddir; DriveItem newfolder = new DriveItem() { Name = RP.Substring(RP.LastIndexOf("/") + 1), Folder = new Folder() }; if (TestLogin() == false) { return(false); } if (string.IsNullOrWhiteSpace(RemotePathDotDot) == true || RemotePath == "/") { newcreateddir = QuerySync <DriveItem>(graphClient.Drive.Root.Children.Request().AddAsync(newfolder)); } else { newcreateddir = QuerySync <DriveItem>(graphClient.Drive.Root.ItemWithPath(RemotePathDotDot).Children.Request().AddAsync(newfolder)); } if (newcreateddir == null) { Console.WriteLine("Cannot create directory"); return(false); } if (RecurseUploadData(LPath, RP, SkipFailed) == false) { return(false); } } foreach (string Filename in System.IO.Directory.EnumerateFiles(LocalPath, "*.*", System.IO.SearchOption.TopDirectoryOnly)) { if (System.IO.Path.GetFileName(Filename).StartsWith(" ") == true) { continue; } string RemoteFullName = RemotePath.Replace("#", "%23") + "/" + Uri.EscapeUriString(System.IO.Path.GetFileName(Filename)).Replace("#", "%23"); System.IO.FileInfo fi = new System.IO.FileInfo(Filename); DateTime DTCreated = fi.CreationTimeUtc; DateTime DTModified = fi.LastWriteTimeUtc; Int64 FSZ = fi.Length; Console.Write(Filename + " -> " + RemoteFullName + " (" + NiceSize(FSZ) + ") ... "); if (FSZ == 0) { StatCopyNumSkipped++; Console.WriteLine("\b\b\b\b\bBlank"); continue; } MarkAsProcessed(RemoteFiles, System.IO.Path.GetFileName(Filename), false); FileSystemInfos fsitest = GetFSI(RemoteFiles, System.IO.Path.GetFileName(Filename), false); if (fsitest != null) { if (DTLightTest(fsitest.Modified, DTModified) && DTLightTest(fsitest.Created, DTCreated) && fsitest.SZ == FSZ) { StatCopyNumSkipped++; StatCopySZSkipped += FSZ; Console.WriteLine("\b\b\b\b\bSkipped"); continue; } else { if (TestLogin() == false) { return(false); } QuerySync(graphClient.Drive.Items[fsitest.OneDriveID].Request().DeleteAsync()); } } try { using (System.IO.FileStream fss = System.IO.File.Open(Filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { FileSystemInfo fsi = new Microsoft.Graph.FileSystemInfo(); fsi.CreatedDateTime = new DateTimeOffset(DTCreated); fsi.LastModifiedDateTime = new DateTimeOffset(DTModified); DriveItemUploadableProperties uplprop = new DriveItemUploadableProperties(); uplprop.FileSystemInfo = fsi; if (TestLogin() == false) { return(false); } UploadSession UploadSess = QuerySync <UploadSession>(graphClient.Drive.Root.ItemWithPath(RemoteFullName).CreateUploadSession(uplprop).Request().PostAsync()); const int MaxChunk = 320 * 10 * 1024; ChunkedUploadProvider provider = new ChunkedUploadProvider(UploadSess, graphClient, fss, MaxChunk); IEnumerable <UploadChunkRequest> chunckRequests = provider.GetUploadChunkRequests(); byte[] readBuffer = new byte[MaxChunk]; List <Exception> exceptions = new List <Exception>(); bool Res = false; foreach (UploadChunkRequest request in chunckRequests) { Int64 Perc = (Int64)(((decimal)request.RangeBegin / (decimal)request.TotalSessionLength) * 100m); Console.Write("\b\b\b\b\b" + Perc.ToString().PadLeft(4) + "%"); if (TestLogin() == false) { return(false); } UploadChunkResult result = QuerySync <UploadChunkResult>(provider.GetChunkRequestResponseAsync(request, readBuffer, exceptions)); if (result.UploadSucceeded) { Res = true; } } if (Res == false) { Console.WriteLine("\b\b\b\b\bFAILED"); if (SkipFailed == false) { return(false); } else { continue; } } } } catch (Exception ee) { Debug.WriteLine(ee.ToString()); Console.WriteLine("\b\b\b\b\bFAILED"); StatCopyNumFailed++; StatCopySZFailed += FSZ; if (FailedDetails == true) { Console.WriteLine("---> " + ee.ToString()); WriteEventLog("Copy failed:\nLocal" + Filename + "\nRemote: " + RemoteFullName + "\n\n" + ee.ToString(), EventLogEntryType.Error); } if (SkipFailed == false) { return(false); } else { continue; } } StatCopyNumSuccess++; StatCopySZSuccess += FSZ; Console.WriteLine("\b\b\b\b\bOK "); } foreach (FileSystemInfos fsis in RemoteFiles) { if (fsis.Processed == true) { continue; } string RemoteFullName = RemotePath + "/" + fsis.Name + (fsis.IsDir == true ? " (DIR)" : ""); //deco only Console.Write("Deleting " + RemoteFullName + " ... "); if (TestLogin() == false) { return(false); } QuerySync(graphClient.Drive.Items[fsis.OneDriveID].Request().DeleteAsync()); StatNumDeleted++; Console.WriteLine("OK"); } return(true); }
public async Task <IActionResult> UploadFile(string folderId, List <IFormFile> uploadFiles) { if (string.IsNullOrEmpty(folderId)) { return(RedirectToAction("UploadFile") .WithError("No folder ID was specified")); } try { var graphClient = GetGraphClientForScopes(_filesScopes); var file = uploadFiles.First(); // Use properties to specify the conflict behavior // in this case, replace var uploadProps = new DriveItemUploadableProperties { ODataType = null, AdditionalData = new Dictionary <string, object> { { "@microsoft.graph.conflictBehavior", "replace" } } }; // POST /me/drive/items/folderId:/fileName:/createUploadSession var uploadSession = await graphClient.Me .Drive .Items[folderId] .ItemWithPath(file.FileName) .CreateUploadSession(uploadProps) .Request() .PostAsync(); // Max slice size must be a multiple of 320 KiB // This amount of bytes will be uploaded each iteration int maxSliceSize = 320 * 1024; var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, file.OpenReadStream(), maxSliceSize); // Create a callback that is invoked after each slice is uploaded IProgress <long> callback = new Progress <long>(progress => { _logger.LogInformation($"Uploaded {progress} bytes of {file.Length} bytes"); }); // Start the upload var uploadResult = await fileUploadTask.UploadAsync(callback); if (uploadResult.UploadSucceeded) { // On success, the new file is contained in the // ItemResponse property of the result return(RedirectToAction("Display", new { fileId = uploadResult.ItemResponse.Id }) .WithSuccess("File uploaded")); } return(RedirectToAction("Index", new { folderId = folderId }) .WithError("Error uploading file")); } catch (ServiceException ex) { InvokeAuthIfNeeded(ex); return(RedirectToAction("Index", new { folderId = folderId }) .WithError("Error uploading file", ex.Error.Message)); } }
// Upload File to Onedrive public async Task <string> transferDataToOnedrive(String FilePath) { var fileName = Path.GetFileName(FilePath); if (null == this.graphClient) { return(""); } Label lb = (Label)System.Windows.Forms.Application.OpenForms["Form1"].Controls.Find("label4", false).FirstOrDefault(); using (var fileStream = System.IO.File.OpenRead(FilePath)) { // Use properties to specify the conflict behavior // in this case, replace var uploadProps = new DriveItemUploadableProperties { ODataType = null, 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("ClipboardShare/" + fileName) .CreateUploadSession(uploadProps) .Request() .PostAsync(); int maxSliceSize = UploadDownloadChunkSize; var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, fileStream, maxSliceSize); // Create a callback that is invoked after each slice is uploaded IProgress <long> progress = new Progress <long>(progress => { Console.WriteLine($"Uploaded {progress} bytes of {fileStream.Length} bytes"); lb.Text = StaticHelpers.BytesToString(progress) + " " + ($" from { StaticHelpers.BytesToString(fileStream.Length) }"); }); try { // Upload the file var uploadResult = await fileUploadTask.UploadAsync(progress); if (uploadResult.UploadSucceeded) { // The ItemResponse object in the result represents the // created item. Console.WriteLine($"Upload complete, item ID: {uploadResult.ItemResponse.Id}"); } else { Console.WriteLine("Upload failed"); } } catch (ServiceException ex) { Console.WriteLine($"Error uploading: {ex.ToString()}"); } } lb.Text = ""; return(""); }
public async Task <(CloudStorageResult, CloudStorageFile)> UploadFileToFolderByIdAsync(string filePath, string folderId, CancellationToken ct) { IDriveItemRequestBuilder driveItemsRequest; if (string.IsNullOrEmpty(folderId)) { driveItemsRequest = myDriveBuilder.Root; } else { driveItemsRequest = myDriveBuilder.Items[folderId]; } CloudStorageResult result = new CloudStorageResult(); CloudStorageFile file = null; // Use properties to specify the conflict behavior in this case, replace var uploadProps = new DriveItemUploadableProperties { ODataType = null, AdditionalData = new Dictionary <string, object> { { "@microsoft.graph.conflictBehavior", "replace" } } }; try { // Create an upload session for a file with the same name of the user selected file UploadSession session = await driveItemsRequest.ItemWithPath(Path.GetFileName(filePath)).CreateUploadSession(uploadProps).Request().PostAsync(ct); using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { var fileUploadTask = new LargeFileUploadTask <DriveItem>(session, fileStream, CHUNK_SIZE); // Create a callback that is invoked after each slice is uploaded IProgress <long> progressCallback = new Progress <long>((progress) => { Console.WriteLine($"Uploaded {progress} bytes."); OnProgressChanged(progress); }); // Upload the file var uploadResult = await fileUploadTask.UploadAsync(progressCallback); if (uploadResult.UploadSucceeded) { // The ItemResponse object in the result represents the created item. file = new CloudStorageFile() { Name = uploadResult.ItemResponse.Name, Id = uploadResult.ItemResponse.Id, CreatedTime = uploadResult.ItemResponse.CreatedDateTime?.DateTime ?? DateTime.MinValue, ModifiedTime = uploadResult.ItemResponse.LastModifiedDateTime?.DateTime ?? DateTime.MinValue, Size = uploadResult.ItemResponse.Size ?? 0 }; result.Status = Status.Success; } else { result.Message = "Upload failed."; } } } catch (Exception ex) { result.Message = ex.Message; } return(result, file); }
private void UploadFile(string path, MemoryStream stream) { try { Task.Run(async() => { PathItemBuilder pathItemBuilder = await GetPathItemBuilder(path); //for small files <2MB use the direct upload: if (stream.Length < 2 * 1024 * 1024) { return(await pathItemBuilder .getPathItem() .Content .Request() .PutAsync <DriveItem>(stream)); } //for larger files use an upload session. This is required for 4MB and beyond, but as the docs are not very clear about this //limit, let's use it a bit more often to be safe. var uploadProps = new DriveItemUploadableProperties { ODataType = null, AdditionalData = new Dictionary <string, object> { { "@microsoft.graph.conflictBehavior", "replace" } } }; var uploadSession = await pathItemBuilder .getPathItem() .CreateUploadSession(uploadProps) .Request() .PostAsync(); // Max slice size must be a multiple of 320 KiB int maxSliceSize = 320 * 1024; var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, stream, maxSliceSize); var uploadResult = await fileUploadTask.UploadAsync(); if (!uploadResult.UploadSucceeded) { throw new Exception("Failed to upload data!"); } return(uploadResult.ItemResponse); }).Wait(); } catch (Exception e) { Task.Run(async() => { PathItemBuilder pathItemBuilder = await GetPathItemBuilder(path); pathItemBuilder.verbose = true; pathItemBuilder.getPathItem(); }).Wait(); throw convertException(e); } }