Riddari
Riddari

Reputation: 1773

Google Drive API Upload to Shared Drive in C#

I'm using this code to upload a file to Google Drive, and it correctly uploads ... to the root of My Drive. I need it to upload to the shared drive _driveId. What am I doing wrong here?

    public string Add(GoogleDriveItem item)
    {
        FilesResource.CreateMediaUpload request;
        using (FileStream stream = new FileStream(item.LocalPath,
            FileMode.Open))
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                stream.CopyTo(memoryStream);
                Google.Apis.Drive.v3.Data.File fileMetadata = new Google.Apis.Drive.v3.Data.File
                {
                    Name = Path.GetFileName(item.LocalPath),
                    MimeType = item.ContentType,
                    DriveId = _driveId,
                    TeamDriveId = _driveId
                };
                request = _service.Files.Create(
                    fileMetadata, memoryStream, item.ContentType);
                request.Fields = "id";
                request.SupportsTeamDrives = true;
                request.SupportsAllDrives = true;
                request.Upload();
            }
        }
        Google.Apis.Drive.v3.Data.File file = request.ResponseBody;
        return file.Id;
    }

I've tried adding Parents = { _driveId} to the properties of fileMetaData, but then I get a null reference exception. :(

Upvotes: 1

Views: 1411

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499760

While I don't know whether it will actually work, this will fix the NPE:

Parents = new[] { _driveId }

Basically the REST client libraries don't create empty lists by default, so Parents is null until you give it a value - but it's just an IList<string>, so an array should be fine.

Upvotes: 2

Related Questions