Andex
Andex

Reputation: 25

How to add file to Sub-Folder of Google Drive using VB.NET

I have spent hours trying to add Subfolder to google drive and also to add a file to subfolders but in vain. Below code works to upload file to drive but I'm not able to add a reference to subset folder to add to them. I have referred to below links but don't know how to convert lines like below to vb.net. any help will be much appreciated.

body.Parents = New List<ParentReference>() { New ParentReference() { Id = _parent } };

https://developers.google.com/drive/api/v3/folder https://developers.google.com/drive/api/v2/reference/files/insert#.net

Please help.

 Dim vFIle As New File()
        vFIle.Title = "My document.txt"
        vFIle.Description = "A test document"
        vFIle.MimeType = "text/plain"

        Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
        Dim Stream As New System.IO.MemoryStream(ByteArray)

        Dim UploadRequest As FilesResource.InsertMediaUpload = Service.Files.Insert(vFIle, Stream, vFIle.MimeType)
        UploadRequest.Upload()
        Dim file As File = UploadRequest.ResponseBody

---- > test2

Dim filetoUp As String = "C:\install log.txt"
If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()
Dim folderId As String = "1UDFFDxi25Hfdgh34sdefcciRE67qzisdRL"
'Dim FodlersList As New List(Of String) From {folderId, "1UDFFDxi25Hfdgh34sdefcciRE67qzisdRLX1", "1UDFFDxi25Hfdgh34sdefcciRE67qzisdRLX2"}
'Dim plist As New List(Of ParentList) From {folderId}

Dim fileMetadata = New File()
With fileMetadata
    .Title = "new.txt"
    .MimeType = "application/vnd.google-apps.folder"
    '.Parents = New List(Of String) From {folderId}
    .Parents(0) = Service.Files.List(folderId)
End With


'System.IO.FileMode.Open
Dim stream = New System.IO.FileStream(filetoUp, System.IO.FileMode.Open)

Dim request
request = Service.Files.Insert(fileMetadata, stream, "text/plain")
'fields is not valid member
'request.Fields = "id" 
request.Upload()

Upvotes: 0

Views: 868

Answers (1)

Alessandro
Alessandro

Reputation: 2998

Approach

Our File resource has a Parents parameter that accepts a List of ParentReference Objects. A simple ParentReference Object has a Id parameter representing the folder Id in Google Drive.

Here you are trying to implicitly cast a string into a ParentList.

Dim folderId As String = "1UDFFDxi25Hfdgh34sdefcciRE67qzisdRL"
Dim plist As New List(Of ParentList) From {folderId}

I'm not sure this ParentList class exists in Google Api but this is what causes your program to fail.

You should instead create a List of ParentReference, like this:

Dim folderId = "your-folder-id"
Dim TheFile As New File()
TheFile.Title = "My document"
TheFile.Description = "A test document"
TheFile.MimeType = "text/plain"
TheFile.Parents = New List(Of ParentReference) From {New ParentReference() With {.Id = folderId}}

Reference

Drive v2 Files

Drive API v2 .Net Guide

Upvotes: 0

Related Questions