如何从谷歌驱动器下载文件并使用C#保存到本地文件夹

问题描述 投票:0回答:2

我需要从谷歌驱动器下载文件并使用C#保存到本地文件夹。我按照Google Developer API documentation中的说明完成了操作,但我收到的文件格式无效。请建议如何下载它。

我完成了:

downloadUrl = url of the file (eg: https://drive.google.com/uc?id=1ULNeKdDoCRmWgPPBW8-d1EGUZgqvA1Ul&export=download)<br/>
filename = some name with extension


private bool SaveToDir(string downloadUrl,string filename) {
string filePath = Server.MapPath("imports/");
bool resp = false;
DriveService ds = new DriveService();
Uri temp = new Uri(downloadUrl);
string fileId = HttpUtility.ParseQueryString(temp.Query).Get("id");
var req = ds.Files.Get(fileId.Trim());
var stream = new MemoryStream();
req.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress dp)=> {
switch (dp.Status)
{
 case Google.Apis.Download.DownloadStatus.Downloading:
      Message("downloading, please wait....");
      break;
 case Google.Apis.Download.DownloadStatus.Completed:
      using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                stream.WriteTo(file);
                Message("File Downloaded successfully.");
            }
      resp = true;
      break;
 case Google.Apis.Download.DownloadStatus.Failed:
      Message("Failed to Download.");
      resp = false;
      break;
 }
 };
 req.Download(stream);
c# .net google-api google-drive-sdk google-api-dotnet-client
2个回答
0
投票

如果文件类型是谷歌文档类型,那么你需要执行导出,你不能只使用下载URL qazxsw poi

link

0
投票
var fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";
var request = driveService.Files.Export(fileId, "application/pdf");
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.");
                break;
            }
        case DownloadStatus.Failed:
            {
                Console.WriteLine("Download failed.");
                break;
            }
    }
};
request.Download(stream);

请参考此 void SaveStream(System.IO.MemoryStream stream, string saveTo) { using (System.IO.FileStream file = new System.IO.FileStream(saveTo, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { stream.WriteTo(file); } } // code here SaveStream( dwnldstream, "C:\\Users\\thulfiqar\\Downloads\\photo.jpg"); 并注意代码中的“stream”对应于我的代码中的“dwnldstream”。

© www.soinside.com 2019 - 2024. All rights reserved.