Visual basic Dot Net



我在下面的代码中没有遇到任何错误,但文件没有上传到谷歌驱动器中。我错过了什么?请帮忙。

注意:cred.json是从谷歌开发者控制台生成的文件。

Dim Service As New DriveService
Dim cred As Google.Apis.Auth.OAuth2.GoogleCredential
Dim UploadRequest As FilesResource.CreateMediaUpload
Dim body As New Data.File()
cred = GoogleCredential.FromFile("D:cred.json")

cred.CreateScoped(DriveService.Scope.Drive)
Service = New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = cred})
body.Name = IO.Path.GetFileName("D:Test.txt")
body.MimeType = "text/plain"
Using Stream = New FileStream("D:Test.txt", FileMode.Open)
UploadRequest = Service.Files.Create(body, Stream, body.MimeType)
UploadRequest.SupportsAllDrives = True
UploadRequest.Upload()
End Using

我已经有一段时间没有使用vb.net了,很抱歉花了这么长时间。这个示例应该向您展示如何正确加载服务帐户密钥文件并将文件上传到您选择的目录。

只需记住与服务帐户的电子邮件地址共享文件夹即可。如果打开json密钥文件,它是唯一一个包含@的变量。

Imports System
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Drive.v3
Imports Google.Apis.Drive.v3.Data
Imports Google.Apis.Services
Imports Google.Apis.Upload
Module Program
Sub Main(args As String())
Console.WriteLine("Hello World!")

REM path to your service account key file. 
Const  pathToServiceAccountKeyFile = "C:DevelopmentFreeLanceGoogleSamplesCredentialsServiceAccountCred.json"
REM load the service account credentials and use drive scope 
Dim credential = GoogleCredential.FromFile(pathToServiceAccountKeyFile).CreateScoped(DriveService.Scope.Drive)

Rem Create the drive service 
Dim service = new DriveService(new BaseClientService.Initializer() with { 
.HttpClientInitializer = credential
})
Task.Run(Async Function()
Await UploadFileAsync(service)
End Function).GetAwaiter().GetResult()

End Sub

Private Async Function UploadFileAsync(service As DriveService) As Task(Of Boolean)

Const FilePath As String = "C:DevelopmentFreeLanceGoogleSamplesDatadummy.txt"

Dim plist As List(Of String) = New List(Of String)
REM Folder id to upload the file To
Const idFolderSave = "0B5pJkOVaKccEYm5pVTJCWGFJbGM"

plist.Add(idFolderSave) 'Set parent folder
If (System.IO.File.Exists(FilePath)) Then
Dim fileMetadata = New File() With {
.Name = "Test",
.MimeType = "text/plain",
.Parents = plist
}
Dim request As FilesResource.CreateMediaUpload
Using stream = New System.IO.FileStream(FilePath, System.IO.FileMode.Open)
request = service.Files.Create(fileMetadata, stream, "text/plain")
request.Fields = "id, parents"
dim results = await request.UploadAsync()

If (results.Status = UploadStatus.Failed)
Console.WriteLine("failed")
Console.WriteLine(results.Exception)

else
Dim file As File = request.ResponseBody
Console.WriteLine("File upload: " + file.Id)
End If

End Using

Else
Console.WriteLine("File does not exist: " + FilePath)
End If
End Function

End Module

我会确保在一些地方记录这一点,我认为我们目前没有任何可视化的基本样本,图书馆的任何地方。

最新更新