C# 如何在WPF安装的应用程序中从Google drive下载文件

C# 如何在WPF安装的应用程序中从Google drive下载文件,c#,google-drive-api,C#,Google Drive Api,我正在开发WPF应用程序,在这里我正在实现带有上传和下载功能的GoogleDriveAPI。上传工作正常,但我在下载文档时遇到了问题。我查看了谷歌文档中的代码 } 但是根据这份文件 "" 这表明“不再支持IAAuthenticator”,因此上述代码不起作用 我尝试使用UserCredential,但它抛出“远程服务器返回错误:(401)未经授权” 因此,请在WPF应用程序中提供相同的代码,或者如何从Google drive下载任何类型的文件。根据下载新Google.api.Auth nuget

我正在开发WPF应用程序,在这里我正在实现带有上传和下载功能的GoogleDriveAPI。上传工作正常,但我在下载文档时遇到了问题。我查看了谷歌文档中的代码

}

但是根据这份文件 "" 这表明“不再支持IAAuthenticator”,因此上述代码不起作用

我尝试使用UserCredential,但它抛出“远程服务器返回错误:(401)未经授权”


因此,请在WPF应用程序中提供相同的代码,或者如何从Google drive下载任何类型的文件。

根据下载新Google.api.Auth nuget包所需的文档。之后,按照以下步骤操作

  • 访问GoogleAPI控制台
  • 如果这是您的第一次,请单击“创建项目…”
  • 否则,单击左上角“Google API”徽标下的下拉列表,然后单击“其他项目”下的“创建…”
  • 单击“API访问”,然后单击“创建OAuth 2.0客户端ID…”
  • 输入产品名称并单击“下一步”
  • 选择“已安装的应用程序”,然后单击“创建客户端ID”
  • 在新创建的“已安装应用程序的客户端ID”中,将客户端ID和客户端机密复制到AdSenseSample.cs文件中
  • 激活项目的驱动器API
参考文献

完成这些步骤后,您可以下载包含以下代码的文件

private async Task Run()
    {
        GoogleWebAuthorizationBroker.Folder = "Drive.Sample";
        UserCredential credential;
        using (var stream = new System.IO.FileStream("client_secrets.json",
            System.IO.FileMode.Open, System.IO.FileAccess.Read))
        {
            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None);
        }

        // Create the service.
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Drive API Sample",
        });

        await UploadFileAsync(service);

        // uploaded succeeded
        Console.WriteLine("\"{0}\" was uploaded successfully", uploadedFile.Title);
        await DownloadFile(service, uploadedFile.DownloadUrl);
        await DeleteFile(service, uploadedFile);
    }


    private async Task DownloadFile(DriveService service, string url)
    {
        var downloader = new MediaDownloader(service);
        downloader.ChunkSize = DownloadChunkSize;
        // add a delegate for the progress changed event for writing to console on changes
        downloader.ProgressChanged += Download_ProgressChanged;

        // figure out the right file type base on UploadFileName extension
        var lastDot = UploadFileName.LastIndexOf('.');
        var fileName = DownloadDirectoryName + @"\Download" +
            (lastDot != -1 ? "." + UploadFileName.Substring(lastDot + 1) : "");
        using (var fileStream = new System.IO.FileStream(fileName,
            System.IO.FileMode.Create, System.IO.FileAccess.Write))
        {
            var progress = await downloader.DownloadAsync(url, fileStream);
            if (progress.Status == DownloadStatus.Completed)
            {
                Console.WriteLine(fileName + " was downloaded successfully");
            }
            else
            {
                Console.WriteLine("Download {0} was interpreted in the middle. Only {1} were downloaded. ",
                    fileName, progress.BytesDownloaded);
            }
        }
    }

您可以下载google drive API。

您还可以帮助我计算ProgressChanged事件中进度条的值吗。我正在尝试:void Download_ProgressChanged(idownloadprogressobj){prgrsVal=obj.bytesdoadded;}这里prgrsVal是绑定到devexpress的ProgressBarEdit控件的'Value'属性的我的属性。对于这一点,我希望在0-100之间有一个合适的百分比值。obj没有要下载的文件的总字节数,如果有,我可以很容易地计算出来。所以请帮帮我。@user3771143你可以这样做<代码>风险值百分比=(prgrsVal/file.size)*100这将为您提供一个介于0-100之间的值
private async Task Run()
    {
        GoogleWebAuthorizationBroker.Folder = "Drive.Sample";
        UserCredential credential;
        using (var stream = new System.IO.FileStream("client_secrets.json",
            System.IO.FileMode.Open, System.IO.FileAccess.Read))
        {
            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None);
        }

        // Create the service.
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Drive API Sample",
        });

        await UploadFileAsync(service);

        // uploaded succeeded
        Console.WriteLine("\"{0}\" was uploaded successfully", uploadedFile.Title);
        await DownloadFile(service, uploadedFile.DownloadUrl);
        await DeleteFile(service, uploadedFile);
    }


    private async Task DownloadFile(DriveService service, string url)
    {
        var downloader = new MediaDownloader(service);
        downloader.ChunkSize = DownloadChunkSize;
        // add a delegate for the progress changed event for writing to console on changes
        downloader.ProgressChanged += Download_ProgressChanged;

        // figure out the right file type base on UploadFileName extension
        var lastDot = UploadFileName.LastIndexOf('.');
        var fileName = DownloadDirectoryName + @"\Download" +
            (lastDot != -1 ? "." + UploadFileName.Substring(lastDot + 1) : "");
        using (var fileStream = new System.IO.FileStream(fileName,
            System.IO.FileMode.Create, System.IO.FileAccess.Write))
        {
            var progress = await downloader.DownloadAsync(url, fileStream);
            if (progress.Status == DownloadStatus.Completed)
            {
                Console.WriteLine(fileName + " was downloaded successfully");
            }
            else
            {
                Console.WriteLine("Download {0} was interpreted in the middle. Only {1} were downloaded. ",
                    fileName, progress.BytesDownloaded);
            }
        }
    }