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

时间:2018-02-16 07:06:40

标签: c# .net google-api google-drive-api google-api-dotnet-client

我需要从Google驱动器下载文件并使用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);

3 个答案:

答案 0 :(得分:0)

如果文件类型是Google文档类型,那么您需要预先导出导出,而您只能使用downloadurl link

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);

答案 1 :(得分:0)

    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");

请参阅此tutorial,并请注意,您代码中的“流”与我代码中的“ dwnldstream”相对应。

答案 2 :(得分:0)

我认为流程是这样的:

  1. 将文件导出为pdf;
  2. 将pdf保存在服务器的文件夹中,
  3. 本地下载pdf。

第一

public static void ExportFileToPdf(string fileId, string newFileName)
    {
        DriveService service = (DriveService)GetService();

        string FolderPath = HostingEnvironment.MapPath("~/Myfolder/");

        // F: effettua la richiesta
        FilesResource.ExportRequest request = service.Files.Export(fileId, "application/pdf");

        string FilePath = Path.Combine(FolderPath, newFileName);

        string fPath = FilePath;

        MemoryStream outputStream = new MemoryStream();

        request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) =>
         {
             switch (progress.Status)
             {
                 case DownloadStatus.Downloading:
                     {
                         Console.WriteLine(progress.BytesDownloaded);
                         break;
                     }
                 case DownloadStatus.Completed:
                     {
                         Console.WriteLine("Download complete.");
                         SaveStream(outputStream, fPath);
                         break;
                     }
                 case DownloadStatus.Failed:
                     {
                         Console.WriteLine("Download failed.");
                         break;
                     }
             }

         };

        request.Download(outputStream);

        DownloadFile("~/Myfolder/", newFileName);
    }

第二

        private static void SaveStream(MemoryStream stream, string FilePath)
    {
        using (FileStream file = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite))
        {
            stream.WriteTo(file);
        }

    }

第三

        private static void DownloadFile(string folderName, string fileName)
    {
        HttpResponse response = HttpContext.Current.Response;

        response.ClearContent();

        response.Clear();

        response.ContentType = "application/pdf";

        response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");

        response.TransmitFile(HostingEnvironment.MapPath(folderName+fileName));

        response.Flush();

        response.End();
    }

如果我们需要下载诸如收据或发票之类的重要文档,我们还可以实现控件来验证文件是否已存在于服务器中,而不是继续进行pdf导出。