I am a complete beginner to Google Cloud. My aim is to upload files to Google Drive from my .NET application (Rhino3d plugin). But I get this error related to the JSON file.
I followed the basic steps I saw in tutorials:
// Path to your JSON credentials file
string credentialsFilePath = "D:\\credentials.json";
var credential = GoogleCredential.FromFile(credentialsFilePath)
.CreateScoped(DriveService.ScopeConstants.DriveFile);
var driveService = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
});
// Prepare the file metadata and stream
string filePath = "D:\\Points.txt";
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = Path.GetFileName(filePath),
Parents = new[] { "API_Test" }
};
using (var stream = new FileStream(filePath, FileMode.Open))
{
var request = driveService.Files.Create(fileMetadata, stream, "text/plain");
request.Fields = "id";
request.Upload();
}
The error is caused at the GoogleCredential.FromFile()
method. Can anyone help me with this ?
The file you downloaded contains the client ID and client secret that identifies your application to Google. But that does not represent a user credential which you usually need to access user owned resources, like Drive resources. And I'm sorry, I agree that the terminology is confusing.
Here's a code example on how you would obtain user credentials given the client ID and client secret.
// credentials.json points to the file containing the client ID and client secret.
var clientSecrets = await GoogleClientSecrets.FromFileAsync("D:\\credentials.json");
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
clientSecrets.Secrets,
new[] { DriveService.ScopeConstants.DriveFile },
"user",
CancellationToken.None);
var driveService = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
});
You can find more documentation here:
I've filed this issue for myself to improve the error message in the case the file with the client ID and client secret is used to create a credential.