How to upload PDF and Excel files to Google Docs using C#?

Hey everyone,

I’m having trouble with a project where I need to upload different file types to Google Docs using C#. So far, I’ve managed to get text and Word files working fine. But when I try to upload PDF or Excel files, I keep getting a bad request error. It’s driving me crazy!

I’m using Single Sign-On (SSO) for Google login with ASP.NET C#. Has anyone run into this issue before? Any tips or tricks for handling these file types specifically?

I’d really appreciate any help or advice you can give. Thanks a bunch in advance!

// Example code snippet
public async Task<bool> UploadFile(string filePath, string fileType)
{
    try
    {
        var service = new DocsService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential,
            ApplicationName = "MyApp"
        });

        var fileMetadata = new Google.Apis.Drive.v3.Data.File()
        {
            Name = Path.GetFileName(filePath),
            MimeType = GetMimeType(fileType)
        };

        FilesResource.CreateMediaUpload request;
        using (var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open))
        {
            request = service.Files.Create(fileMetadata, stream, GetMimeType(fileType));
            request.Fields = "id";
            await request.UploadAsync();
        }

        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error uploading file: {ex.Message}");
        return false;
    }
}

hey neo_stars, i’ve dealt with this before. for PDFs and Excel, you gotta use Google Drive API instead of Docs API. Switch your DocsService to DriveService and it should work. Also, double-check your MimeType method - make sure it returns the right types for PDF and Excel. Good luck!

I encountered a similar issue in a recent project. The key is to use the Google Drive API for PDFs and Excel files, as these aren’t natively supported by Google Docs. Modify your code to use DriveService instead of DocsService. Also, ensure your GetMimeType method returns ‘application/pdf’ for PDFs and ‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’ for Excel files. If you’re still getting errors, check your OAuth2 scope - you might need to include ‘https://www.googleapis.com/auth/drive.file’ for file creation permissions. Let me know if you need more specific guidance on implementation.