Search code examples
microsoft-graph-apionedrive

Object reference not set to an object while file upload in OneDrive


I am using Microsoft Graph SDK to upload file in chunks in OneDrive. I am using below code to upload the file:

try
{
    GraphServiceClient graphClient = this.GetGraphServiceClient(accessToken);

    string fileName = Path.GetFileName(srcFilePath);

    using (var fileContentStream = System.IO.File.Open(srcFilePath, System.IO.FileMode.Open))
    {
        var uploadSession = await graphClient.Me.Drive.Root.ItemWithPath(fileName).CreateUploadSession().Request().PostAsync();

        var maxChunkSize = 5 * 1024 * 1024;
        var provider = new ChunkedUploadProvider(uploadSession, graphClient, fileContentStream, maxChunkSize);

        var chunkRequests = provider.GetUploadChunkRequests();
        var readBuffer = new byte[maxChunkSize];
        var trackedExceptions = new List<Exception>();
        Microsoft.Graph.DriveItem itemResult = null;

        foreach (var request in chunkRequests)
        {
            var result = await provider.GetChunkRequestResponseAsync(request, readBuffer, trackedExceptions);

            if (result.UploadSucceeded)
            {
                itemResult = result.ItemResponse;
            }
        }
    }
}
catch (Microsoft.Graph.ServiceException e)
{
}
catch (Exception ex)
{ 
}

The above code works fine with normal file names. However, when I am trying to upload a file with name as Test#123.pdf, "Object reference not set to an object" exception is thrown at line var provider = new ChunkedUploadProvider(uploadSession, graphClient, fileContentStream, maxChunkSize); Please see below screenshot:enter image description here

Is this a limitation of OneDrive SDK, or am I not passing the parameters correctly?


Solution

  • The # sign has a special meaning in a URL. Before you can use it, you'll need to URL Encode the file name: Test%23123.pdf.