C# UWP/WinRT Google Drive: Download a File (Stream to the Filesystem)

Back to Index

Downloads the content of a file by ID. (In this example the file id = 1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl) The file is streamed directly to the filesystem. Note: The alt=media query param must be used to download the file content (as opposed to the file metadata).

Documentation: https://developers.google.com/drive/v3/reference/files/get


Chilkat.Rest rest = new Chilkat.Rest();
bool success;

//   Provide a previously obtained OAuth2 access token.
Chilkat.OAuth2 oauth2 = new Chilkat.OAuth2();
oauth2.AccessToken = "OAUTH2_ACCESS_TOKEN";
rest.SetAuthOAuth2(oauth2);

success = await rest.ConnectAsync("www.googleapis.com",443,true,true);
if (success != true) {
    Debug.WriteLine(rest.LastErrorText);
    return;
}

rest.AddQueryParam("includeTeamDriveItems","true");
rest.AddQueryParam("supportsTeamDrives","true");
rest.AddQueryParam("alt","media");

//  First send the HTTP request.
success = await rest.SendReqNoBodyAsync("GET","/drive/v3/files/1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl");
if (success != true) {
    Debug.WriteLine(rest.LastErrorText);
    return;
}

//  Read the response header.  If the response status code is success, stream to the file.
//  Otherwise receive the error response text.
int statusCode = await rest.ReadResponseHeaderAsync();
if (statusCode < 0) {
    Debug.WriteLine(rest.LastErrorText);
    return;
}

if (statusCode != 200) {
    Debug.WriteLine("Received error response code: " + Convert.ToString(statusCode));
    //  Read the error response body.
    Chilkat.StringBuilder sbErrResponse = new Chilkat.StringBuilder();
    success = await rest.ReadRespSbAsync(sbErrResponse);
    if (success != true) {
        Debug.WriteLine(rest.LastErrorText);
        return;
    }

    Debug.WriteLine("Error response:" + sbErrResponse.GetAsString());
    return;
}

//  Stream the response body to the output file.
Chilkat.Stream respBodyStream = new Chilkat.Stream();
respBodyStream.SinkFile = "/someDirectory/penguins.jpg";
success = await rest.ReadRespBodyStreamAsync(respBodyStream,true);
if (success != true) {
    Debug.WriteLine(rest.LastErrorText);
    return;
}

Debug.WriteLine("Example Completed.");