Как получить FolderID из папок Google Диска с помощью Chilkat DLL

Я использую ChilKat для разработки инструмента с использованием VB.NET, который выполняет загрузку одного файла в мою учетную запись на Google Диске. Я могу получить идентификатор папки в корневой папке, но мне не удается получить идентификатор папки, если есть путь к папкам.

В настоящий момент аргумент FolderPath не используется (я буду, когда узнаю, как правильно получить FolderID). На данный момент я могу получить идентификатор папки Nova, но ни одну из других папок в следующем дереве:

введите описание изображения здесь

Есть ли более простой способ получить идентификатор папки из GoogleDrive? Я также хотел бы создать путь к папкам на Google Диске, если их не существует.

Я никогда не работал с JSON или HTTP-запросами, поэтому я как бы потерялся здесь. Любая помощь будет в основном оценена! Заранее спасибо!

Private Function FolderID(ByVal FolderPath As String) As String

    Dim rest As New Chilkat.Rest

    '  Connect using TLS.
    Dim success As Boolean = rest.Connect("www.googleapis.com", 443, True, True)

    '  Provide the authentication credentials (i.e. the access token)
    Dim gAuth As New Chilkat.AuthGoogle
    gAuth.AccessToken = M_AccessToken
    rest.SetAuthGoogle(gAuth)

    Dim json As New Chilkat.JsonObject
    json.EmitCompact = False

    '  Get the folder Testes folder that is in the Google Drive root.
    rest.AddQueryParam("q", "'root' in parents and name='Testes'")
    Dim jsonResponse As String = rest.FullRequestNoBody("GET", "/drive/v3/files")
    If Not rest.LastMethodSuccess Then
        Return rest.LastErrorText
        Exit Function
    End If

    json.Load(jsonResponse)

    rest.ClearAllQueryParams()

    '  Now that we know the ID for the Testes directory, get the id for the folder Nova having Testes as the parent.
    Dim sbQuery As New Chilkat.StringBuilder
    sbQuery.Append("name = 'nova' and '")
    sbQuery.Append(json.StringOf("files[0].id"))
    sbQuery.Append("' in parents")

    rest.AddQueryParamSb("q", sbQuery)

    jsonResponse = rest.FullRequestNoBody("GET", "/drive/v3/files")
    If Not rest.LastMethodSuccess Then
        Return (rest.LastErrorText)
        Exit Function
    End If

    json.Load(jsonResponse)

    Return json.StringOf("files[0].id")

End Function

person Rui Manso    schedule 23.01.2021    source источник


Ответы (1)


Мне удалось найти способ, выполняя итеративные запросы. Не знаю, правильный ли это способ, но он работает ...

Вот код, теперь использующий FolderPath с форматом / folder1 / folder2 / folderN

Private Function GetFolderID(ByVal FolderPath As String) As String

    Dim Rest As New Chilkat.Rest

    ' Connect to Google APIs server
    Dim Connected As Boolean = Rest.Connect("www.googleapis.com", 443, True, True)
    If Not Connected Then
        Return "Error attempting to connect: " & Rest.ConnectFailReason
        Exit Function
    End If

    ' Provide the Access token
    Dim GAuth As New Chilkat.AuthGoogle
    GAuth.AccessToken = M_AccessToken
    Rest.SetAuthGoogle(GAuth)

    ' Instance to JSON object
    Dim JSON As New Chilkat.JsonObject
    JSON.EmitCompact = False

    ' Parse the provided path and split to array
    Dim ParseFolder As String = Strings.Right(FolderPath, Len(FolderPath) - 1)
    Dim Folders As String() = Split(ParseFolder, "/")

    '  Get the root folder that is in the Google Drive folders structure
    Rest.AddQueryParam("q", "'root' in parents and name='" & Folders(0) & "'")
    Dim Response As String = Rest.FullRequestNoBody("GET", "/drive/v3/files")
    If Not Rest.LastMethodSuccess Then
        Return Rest.LastErrorText
        Exit Function
    End If
    JSON.Load(Response)

    'Iterate on the folders to get the last folder's id
    Rest.ClearAllQueryParams()
    For i = 1 To Folders.Length - 1
        Dim sbQuery As New Chilkat.StringBuilder

        sbQuery.Append("name = '" & Folders(i) & "' and '")
        sbQuery.Append(JSON.StringOf("files[0].id"))
        sbQuery.Append("' in parents")

        Rest.AddQueryParamSb("q", sbQuery)

        Response = Rest.FullRequestNoBody("GET", "/drive/v3/files")

        If Not Rest.LastMethodSuccess Then
            Return Rest.LastErrorText
            Exit Function
        End If

        JSON.Load(Response)
    Next

    ' Get the folder id
    Return JSON.StringOf("files[0].id")

End Function
person Rui Manso    schedule 23.01.2021