I\'m beating myself bloody trying to get a simple service acccount login to work in C#, to Google API and Google Analytics. My company is already getting data into Analytics, an
In 2020 you don't need to do all this and the GoogleCredential works fine. The code in the question looks correct except for one line:
credentials.CreateScoped(new string[] { DriveService.Scope.Drive });
The CreateScoped method returns a copy of the credentials. If you reassign it back to itself it just works.
For the sake of completeness, this is my test code that works perfectly:
using (var stream =
new FileStream("drive-credentials.json", FileMode.Open, FileAccess.Read))
{
var credentials = GoogleCredential.FromStream(stream);
if (credentials.IsCreateScopedRequired)
{
credentials = credentials.CreateScoped(new string[] { DriveService.Scope.Drive });
}
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "application name",
});
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 10;
listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
IList files = listRequest.Execute()
.Files;
}