Я могу получить файлы с Google Диска, используя API, по ссылке: Display (View) list of files from Google Drive using Google Drive API in ASP.Net with C# and VB.Net.Как получить все файлы из всех папок с API Google Диска в C#
Но я получаю только 100 записей. У меня несколько тысяч записей. Может кто-нибудь, пожалуйста, дайте мне знать, что нужно изменить, чтобы получить полный отчет.
Вы можете найти код ниже:
namespace GoogleDrive
{
public partial class gDrive : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GoogleConnect.ClientId = "942196220502-k107l4mtn6n606d8m38pp2k6clfmbftd.apps.googleusercontent.com";
GoogleConnect.ClientSecret = "oJxTZ2Bw9QfOlrc7KgxsEf9o";
GoogleConnect.RedirectUri = Request.Url.AbsoluteUri.Split('?')[0];
GoogleConnect.API = EnumAPI.Drive;
if (!string.IsNullOrEmpty(Request.QueryString["code"]))
{
string code = Request.QueryString["code"];
string json = GoogleConnect.Fetch("me", code);
GoogleDriveFiles files = new JavaScriptSerializer().Deserialize<GoogleDriveFiles>(json);
gv1.DataSource = files.Items.Where(i => i.Labels.Trashed == false);
gv1.DataBind();
}
else if (Request.QueryString["error"] == "access_denied")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Access denied.')", true);
}
else
{
GoogleConnect.Authorize("https://www.googleapis.com/auth/drive.readonly");
}
}
public class GoogleDriveFiles
{
public List<GoogleDriveFile> Items { get; set; }
}
public class GoogleDriveFile
{
public string Id { get; set; }
public string Title { get; set; }
public string OriginalFilename { get; set; }
public string ThumbnailLink { get; set; }
public string IconLink { get; set; }
public string WebContentLink { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public GoogleDriveFileLabel Labels { get; set; }
public string alternateLink { get; set; }
public Boolean editable { get; set; }
}
public class GoogleDriveFileLabel
{
public bool Starred { get; set; }
public bool Hidden { get; set; }
public bool Trashed { get; set; }
public bool Restricted { get; set; }
public bool Viewed { get; set; }
}
}
}
Ниже код применим, чтобы получить первые 1000 записей.
namespace gDrive
{
class Program
{
static string[] Scopes = { DriveService.Scope.DriveReadonly };
static string ApplicationName = "Drive API .NET Quickstart";
static void Main(string[] args)
{
UserCredential credential;
gDriveTableAdapter gDrive = new gDriveTableAdapter();
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
//Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 1000;
listRequest.Fields = "nextPageToken, files(webViewLink, name)";
// List files.
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
.Files;
Console.WriteLine("Processing...\n");
if (files != null && files.Count > 0)
{
foreach (var file in files)
{
gDrive.InsertQuery(file.Name, file.WebViewLink);
}
Console.WriteLine(files.Count + " records fetched.");
}
else
{
Console.WriteLine("No files found.");
}
Console.Read();
}
}
}
[Этот примером страница] (https: // разработчики. google.com/drive/v3/web/quickstart/dotnet): 'listRequest.PageSize = 10;', читающий [здесь] (https://developers.google.com/drive/v3/reference/files/list) мы видим, что значение по умолчанию - 100, как вы видите. Вы можете установить его до 1000, как указано на этой второй странице. Вам, видимо, придется как-то использовать параметр 'pageToken', чтобы продолжить получать файлы после 1000. Показывать, что ваш код вместо ссылки на другую страницу будет более полезен. – Quantic
@quantic добавлено кодирование, PLS найти его – Aruna
Извините, я не знаю API Google Drive или как его использовать. Может быть, вам следует следовать примеру, который я связал, вместо того, который вы нашли, потому что моя новая и от самого Google. Можно ли оставить в своем сообщении «ClientId» и «ClientSecret»? – Quantic