Add OneNote page using C#

222 Views Asked by At

I am trying to add a page to a Onenote notebook using C#, and the code below. I can create notebooks and sections in notebooks, so I think the client and scopes are valid, but the last line throws an exception: "Microsoft.Graph.Models.ODataErrors.ODataError.' Any help would be appreciated.

private async void createOnenotePage(string sectionId, string htmlString)
    {
        var graphClient = GraphHelper._userClient;

        var onenotePage = new OnenotePage();

        // Convert the HTML string to a byte array
        byte[] contentBytes = Encoding.UTF8.GetBytes(htmlString);

        onenotePage.Content = contentBytes;

        var response = await graphClient.Me.Onenote.Sections[sectionId].Pages.PostAsync(onenotePage);
        
    }
1

There are 1 best solutions below

0
user3673052 On

In case anyone has the same question, the C# SDK does not appear to support this. This works:

 public static async Task<string> createPageAsync3(string token, string sectionId, string htmlContent)
    //Posts a OneNote page.
    {
        // Set up the HttpClient and request header
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // Set up the request content as multipart/form-data
        using (var content = new MultipartFormDataContent("MyPartBoundary198374"))
        {
            // Add the Presentation HTML content as a form-data part
            var presentationContent = new StringContent(htmlContent);

            presentationContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/html");
            content.Add(presentationContent, "Presentation");

            // Make the POST request to create the OneNote page
            
            var response = await client.PostAsync($"https://graph.microsoft.com/v1.0/me/onenote/sections/{sectionId}/pages", content);

            return response.StatusCode.ToString();
        }
    }