I have a method that will search for a file by name and then download that file:
public static void DownloadFile(string filename)
{
service = GetDriveService();
//check if file exists and grab id
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.SupportsAllDrives = true;
listRequest.IncludeItemsFromAllDrives = true;
listRequest.PageSize = 1000;
listRequest.Q = "name = '" + filename + ".pdf'";
FileList files = listRequest.Execute();
if (files.Files.Count > 0) //the file exists, DOWNLOAD
{
var request = service.Files.Get(files.Files[0].Id);
var stream = new System.IO.MemoryStream();
request.Download(stream);
}
}
The problem is that FileList files = listRequest.Execute(); will return 0 files unless I have recently opened that file on Google Drive in Chrome. it's like the files are not indexed. Am I missing a parameter?
I've tested this on loads of files and without fail, if I've opened the file on chrome FileList files = listRequest.Execute(); returns 1 element otherwise it returns nothing.
I have also tested searching in specific folders only, same issue.
Any help is much appreciated.
thanks
edit; Here is the GetDriveService Method:
private static DriveService GetDriveService()
{
string[] scopes = new string[] { DriveService.Scope.Drive }; // Full access
GoogleDrive cr = JsonConvert.DeserializeObject<GoogleDrive>(System.IO.File.ReadAllText(@"\\PATH_TO_JSONFILE\GoogleAPI.json"));
ServiceAccountCredential xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email)
{
User = "xxxxx@xxxx.xx",
Scopes = new[] { DriveService.Scope.Drive }
}.FromPrivateKey(cr.private_key));
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = xCred,
ApplicationName = "APPLICATION_NAME",
});
return service;
}
The User email is the same account I use to open the files in Chrome.