我正在努力连接到谷歌驱动器,列出任何格式的每个文件,然后在我的硬盘上物理下载。我使用了谷歌API为我准备的方法。但我认为我工作的方式我只能访问每个文件的内容,所以我不能这样做。
你能帮我知道我需要做哪种配置吗?
public static Google.Apis.Drive.v2.Data.FileList ListFiles(DriveService service, FilesListOptionalParms optional = null)
{
try
{
if (service == null)
throw new ArgumentNullException("service");
var request = service.Files.List();
request = (FilesResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);
return request.Execute();
}
catch (Exception ex)
{
throw new Exception("Request Files.List failed.", ex);
}
}
我称这个方法为每个文件我想在我的电脑上下载:
FileList files_list = DriveListExample.ListFiles(service, null);
if (files_list.Items.Count != 0)
{
foreach (var file in files_list.Items)
{
DriveListExample.DownloadFile(service, file, DownloadDirectoryName);
Console.WriteLine("\"{0}\" ", file.Title + " downloaded completely!");
}
}
如果我可以访问每个文件的downloadUrl,我可以测试另一种下载方式。但它是null,这是我的下载方法:
public static void DownloadFile(DriveService服务,文件文件,字符串saveTo) {
var request = service.Files.Get(file.Id);
var stream = new System.IO.MemoryStream();
Console.WriteLine(file.FileExtension);
request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) =>
{
switch (progress.Status)
{
case DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
break;
}
case DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
SaveStream(stream, saveTo);
break;
}
case DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
break;
}
}
};
try
{
request.Download(stream);
}
catch (Exception ex)
{
Console.Write("Error: " + ex.Message);
}
}
此过程中的下载状态为“失败”。 我也检查了范围,我发现使用这些行只允许我下载我在这个应用程序中创建的文件:
private static readonly string[] Scopes = new[] { DriveService.Scope.DriveFile, DriveService.Scope.Drive };
但我需要在列出所有文件后,我可以下载每个文件。
您能帮我解决一下这个解决方案或其他工作代码吗?
答案 0 :(得分:1)
您需要使用有效的文件名并处理Google doc文件:
public static void DownloadFile(DriveService service, Google.Apis.Drive.v2.Data.File file, string saveTo)
{
var request = service.Files.Get(file.Id);
var stream = new System.IO.MemoryStream();
// Add a handler which will be notified on progress changes.
// It will notify on each chunk download and when the
// download is completed or failed.
request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) =>
{
switch (progress.Status)
{
case DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
break;
}
case DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
SaveStream(stream, saveTo + @"/" + file.Title);
break;
}
case DownloadStatus.Failed:
{
if (file.ExportLinks.Any())
SaveStream(new HttpClient().GetStreamAsync(file.ExportLinks.FirstOrDefault().Value).Result, saveTo + @"/" + file.Title);
Console.WriteLine("Download failed.");
break;
}
}
};
try
{
request.Download(stream);
}
catch (Exception ex)
{
Console.Write("Error: " + ex.Message);
}
}