How to upload a large file using one drive API in ASP.net C#

Pradyut Sinha 21 Reputation points
2023-01-31T19:44:22.41+00:00

How to upload a large file using one drive API in C#

Please find the code as below as it is not working

Please Help.

        [HttpPost]

        [Route("Uploadlargefile")]

 

        public async Task<string> UploadFileAsync(IFormFile file, string filePath, string oneDrivePath)

        {

            #region create upload session

            //string uploadUri = await GetUploadSession(oneDrivePath);

            var ClientId = "827401c8-0561-45b5-a1aa-18302e10a9f4";//CommonCredentials.ClientId;

            var app = PublicClientApplicationBuilder.Create(ClientId)

            .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs).Build();

            string username = sa-prd-oddev2-admin@its.jnj.com;//CommonCredentials.UserName;

            // Console.Write("Enter Password: ");

            string pwd = "Re22!Kes"; //CommonCredentials.Password;

            SecureString password = new SecureString();

            foreach (char c in pwd)

                password.AppendChar(c);

            // var Scopes = new string[] { https://graph.microsoft.com/.default };

            var Scopes = new string[] { "Files.ReadWrite.All" };

            Console.WriteLine("** Making Request to get GraphToken Using MSAL.NET ** \n");

            //var result =app.AcquireTokenByUsernamePassword(Scopes, username, password).ExecuteAsync().GetAwaiter().GetResult();

            var uploadSession = string.Empty;

            #region Store MS GraphToken In Memory Caching With Username and Password flow

            var App = new PublicAppUsingUsernamePassword(app);

            var resultToken = App.AcquireATokenFromCacheOrUsernamePasswordAsync(Scopes, username, password).GetAwaiter().GetResult();

            string result = string.Empty;

            if (resultToken != null)

            {

                var spClient = new HttpClient();

                spClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // spClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

                spClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", resultToken.AccessToken);

 

 

                    var fileName = "abc1234.txt";

                    var filePath1 = Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName);

 

                string json1 = @"

{

     ""item"": {

 

{

                        ""@odata.type"": ""microsoft.graph.driveItemUploadableProperties"",

                        ""@microsoft.graph.conflictBehavior"": ""rename"",

                        ""name"": """+fileName + @"""

 

}

}";

 

                HttpContent c = new StringContent(json1, Encoding.UTF8, "application/json");

                // HttpContent content = new StringContent("application/x- www-form-urlencoded");

               var onedriveapi = https://graph.microsoft.com/v1.0/me/drive;

               var uploadSession1 =  spClient.GetStringAsync(onedriveapi).Result;

 

                JObject jo1 = JObject.Parse(uploadSession1);

                var driveid = jo1.SelectToken("id").Value<string>();

 

                //uri: $"{OneDriveApiRoot}drive/root:/{oneDriveFilePath}:/upload.createSession",

                var onedrive_destination = https://graph.microsoft.com/v1.0 + "/drives/root:";

                uploadSession = await spClient.PostAsync(onedrive_destination + "/{item-path}:/upload.createSession", c).Result.Content.ReadAsStringAsync();

 

                JObject jo = JObject.Parse(uploadSession);

                var uploaduri = jo.SelectToken("uploadUrl").Value<string>();

 

                #endregion

 

                //    #region upload the file fragment

 

                //    using (MemoryStream stream = new MemoryStream())

                //    {

                //        await file.CopyToAsync(stream);

                //        long position = 0;

                //        long totalLength = stream.Length;

                //        int length = 10 * 1024 * 1024;

 

                //        while (true)

                //        {

                //            byte[] bytes = await ReadFileFragmentAsync(stream, position, length);

                //            if (position >= totalLength)

                //            {

                //                break;

                //            }

 

                //            result = await UploadFileFragmentAsync(bytes, uploaduri, position, totalLength);

 

                //            position += bytes.Length;

                //        }

                //    }

            }

            #endregion

 

            return result;

        }

 
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,492 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,240 questions
OneDrive
OneDrive
A Microsoft file hosting and synchronization service.
796 questions
{count} votes