Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LindaLawton/c8bf4da53629ddc9f36a4db5a9e2fbc0 to your computer and use it in GitHub Desktop.
Save LindaLawton/c8bf4da53629ddc9f36a4db5a9e2fbc0 to your computer and use it in GitHub Desktop.
Google drive v3 File list full console example
using System;
using System.IO;
using System.Threading;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Requests;
using Google.Apis.Services;
using Google.Apis.Util.Store;
namespace ConsoleApp1
{
class Program
{
private static UserCredential GetUserCredential(string clientSecretJson, string userName, string[] scopes)
{
try
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
if (string.IsNullOrEmpty(clientSecretJson))
throw new ArgumentNullException("clientSecretJson");
if (!System.IO.File.Exists(clientSecretJson))
throw new Exception("clientSecretJson file does not exist.");
// These are the scopes of permissions you need. It is best to request only what you need and not all of them
using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/",
System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
// Requesting Authentication or loading previously stored authentication for userName
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
scopes,
userName,
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
credential.GetAccessTokenForRequestAsync();
return credential;
}
}
catch (Exception ex)
{
throw new Exception("Get user credentials failed.", ex);
}
}
/// <summary>
/// This method get a valid service
/// </summary>
/// <param name="credential">Authecated user credentail</param>
/// <returns>DriveService used to make requests against the Drive API</returns>
private static DriveService GetService(UserCredential credential)
{
try
{
if (credential == null)
throw new ArgumentNullException("credential");
// Create Drive API service.
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive Oauth2 Authentication Sample"
});
}
catch (Exception ex)
{
throw new Exception("Get Drive service failed.", ex);
}
}
private const string pathToClientSecretJson = "";
private const string userName = "Daimto";
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var cred = GetUserCredential(pathToClientSecretJson, userName,
new[] {Google.Apis.Drive.v3.DriveService.Scope.Drive});
var service = GetService(cred);
}
public class ListFilesOptionalParameters
{
/// <summary>
/// Selector specifying which fields to include in a partial response.
/// </summary>
public string Fields { get; set; }
/// <summary>
/// An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// </summary>
public string QuotaUser { get; set; }
/// <summary>
/// Lists or searches files.
/// </summary>
public string Corpora { get; set; }
/// <summary>
/// Lists or searches files.
/// </summary>
public string Corpus { get; set; }
/// <summary>
/// Lists or searches files.
/// </summary>
public string DriveId { get; set; }
/// <summary>
/// Lists or searches files.
/// </summary>
public bool IncludeItemsFromAllDrives { get; set; }
/// <summary>
/// Lists or searches files.
/// </summary>
public bool IncludeTeamDriveItems { get; set; }
/// <summary>
/// Lists or searches files.
/// </summary>
public string OrderBy { get; set; }
/// <summary>
/// Lists or searches files.
/// </summary>
public int PageSize { get; set; }
/// <summary>
/// Lists or searches files.
/// </summary>
public string PageToken { get; set; }
/// <summary>
/// Lists or searches files.
/// </summary>
public string Q { get; set; }
/// <summary>
/// Lists or searches files.
/// </summary>
public string Spaces { get; set; }
/// <summary>
/// Lists or searches files.
/// </summary>
public bool SupportsAllDrives { get; set; }
/// <summary>
/// Lists or searches files.
/// </summary>
public bool SupportsTeamDrives { get; set; }
/// <summary>
/// Lists or searches files.
/// </summary>
public string TeamDriveId { get; set; }
}
/// <summary>
/// Lists or searches files.
/// </summary>
/// <param name="service"></param>
/// <param name="options"></param>
/// <returns></returns>
public static FileList ListFiles(DriveService service, ListFilesOptionalParameters options)
{
// A page streamer is a helper to provide both synchronous and asynchronous page streaming
// of a listable or queryable resource.
var pageStreamer =
new PageStreamer<Google.Apis.Drive.v3.Data.File, FilesResource.ListRequest, FileList, string>(
(request, token) => request.PageToken = token,
response => response.NextPageToken, response => response.Files);
try
{
var results = new FileList();
var request = service.Files.List();
// Applying optional parameters to the request.
request = (FilesResource.ListRequest) SampleHelpers.ApplyOptionalParms(request, options);
// iterate through the results
foreach (var result in pageStreamer.Fetch(request))
{
results.Files.Add(result);
}
return results;
}
catch (Exception ex)
{
throw new Exception($"Request Files.List failed with message {ex.Message}", ex);
}
}
}
public static class SampleHelpers
{
/// <summary>
/// Using reflection to apply optional parameters to the request.
///
/// If the optonal parameters are null then we will just return the request as is.
/// </summary>
/// <param name="request">The request. </param>
/// <param name="optional">The optional parameters. </param>
/// <returns></returns>
public static object ApplyOptionalParms(object request, object optional)
{
if (optional == null)
return request;
System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties();
foreach (System.Reflection.PropertyInfo property in optionalProperties)
{
// Copy value from optional parms to the request. They should have the same names and datatypes.
System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name);
if (property.GetValue(optional, null) != null
) // TODO Test that we do not add values for items that are null
piShared.SetValue(request, property.GetValue(optional, null), null);
}
return request;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment