string[] scopes = new string[] { DriveService.Scope.Drive }; // Full access
var keyFilePath = Environment.CurrentDirectory + "JSON_FILE_LOCATION";
if (!System.IO.File.Exists(keyFilePath))
{
Console.WriteLine("An Error occurred - Key file does not exist");
}
try
{
using (var stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read))
{
var googleCredential = GoogleCredential.FromStream(stream);
if (googleCredential.IsCreateScopedRequired)
{
googleCredential.CreateScoped(scopes);
}
// Create the service.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = googleCredential,
ApplicationName = "APP_NAME",
});
try
{
FilesResource.ListRequest listRequest = service.Files.List();
FileList files = listRequest.Execute();
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
}
}
And this is the exception :
Eccezione generata: 'Google.GoogleApiException' in mscorlib.dll
An error occurred: Google.Apis.Requests.RequestError
Invalid Credentials [401]
Errors [
Message[Invalid Credentials] Location[Authorization - header] Reason[authError] Domain[global]
]
Ok, now this code is working but there is a problem.
---------------------------------------------------------------------
string[] scopes = new string[] { DriveService.Scope.Drive };
GoogleCredential credential;
using (var stream = new FileStream(JSON_PATH, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream);
}
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential.CreateScoped(scopes),
ApplicationName = APPLICATION_NAME
});
FilesResource.ListRequest listRequest = service.Files.List();
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
if (files != null && files.Count > 0)
{
foreach (var file in files)
{
Console.WriteLine("{0} ({1}) {2}", file.Name, file.Id);
}
}
------------------------------------------------------------------