使用C#从Google驱动器下载文件

时间:2018-06-28 05:48:11

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

我正在尝试通过C#从Google驱动器下载文件。但是,每次我运行用于下载文件的代码,但都无法下载时。 这是我的下载代码:

private static void DownloadFile(Google.Apis.Drive.v3.DriveService driveService)
        {

            var fileId = "//my file id for file on drive";
            var request = driveService.Files.Get(fileId);
            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) =>
                {
                    try
                    {


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

                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                };
            request.Download(stream);

        }

1 个答案:

答案 0 :(得分:0)

使用webContentLink代替下载内容,或者在File Get方法中返回Download Url。您只需使用该链接即可下载文件。

有关更多信息,请检查File Resource Object.