首页 > 解决方案 > 如何使用 VB.NET 将文件添加到 Google Drive 的子文件夹

问题描述

我花了几个小时试图将子文件夹添加到谷歌驱动器,并将文件添加到子文件夹但徒劳无功。下面的代码可以将文件上传到驱动器,但我无法添加对子文件夹的引用以添加到它们。我提到了下面的链接,但不知道如何将下面的行转换为 vb.net。任何帮助都感激不尽。

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

请帮忙。

 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()

标签: vb.netgoogle-drive-api

解决方案


方法

我们的文件资源有一个接受ParentReference对象列表的父母参数。一个简单的ParentReferenceObject 有一个Id参数表示 Google Drive 中的文件夹 ID。

在这里,您尝试将字符串隐式转换为ParentList.

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

我不确定ParentListGoogle Api 中是否存在此类,但这就是导致您的程序失败的原因。

您应该创建一个 List ParentReference,如下所示:

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}}

参考

驱动器 v2 文件

Drive API v2 .Net 指南


推荐阅读