如何使用C#及Google Apis V3 .Net版下载Google Drive二进制文件
.NET Google Drive API V3 正确下载文件的解决方案
我明白你现在的困扰——用.NET Google API V3下载Drive文件时踩了几个坑对吧?其实问题核心在于Google Drive里的文件分两种类型,下载逻辑完全不同,咱们一步步来解决:
先搞清楚两种文件类型的差异
Google Drive里的文件主要分两类:
- 普通上传文件:比如你上传的PDF、图片、压缩包等,这类文件有实际的二进制内容,直接下载即可。
- Google原生文档:比如Docs、Sheets、Slides等,这类文件是存储在Google云端的“在线文档”,没有直接的二进制文件,必须先导出成指定格式(比如PDF、Excel)才能下载。
正确的代码实现
下面是完整的代码示例,会自动区分文件类型并处理:
using Google.Apis.Drive.v3; using Google.Apis.Drive.v3.Data; using System.IO; using System.Collections.Generic; // 假设你已经初始化好DriveService实例:service string fileId = "你的目标文件ID"; // 获取文件基本信息 var fileRequest = service.Files.Get(fileId); fileRequest.Fields = "*"; var fileResponse = fileRequest.Execute(); // 判断是否为Google原生文档 bool isGoogleNativeFile = fileResponse.MimeType.StartsWith("application/vnd.google-apps."); if (!isGoogleNativeFile) { // 情况1:下载普通上传文件 using (var outputStream = new FileStream(@"C:\你的保存路径\文件名.ext", FileMode.Create, FileAccess.Write)) { // 直接调用Files.Get的Download方法 fileRequest.Download(outputStream); } } else { // 情况2:导出并下载Google原生文档 // 定义不同原生文档对应的导出格式MimeType var exportFormatMap = new Dictionary<string, string> { // Google Docs 导出为PDF {"application/vnd.google-apps.document", "application/pdf"}, // Google Sheets 导出为Excel(xlsx) {"application/vnd.google-apps.spreadsheet", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, // Google Slides 导出为PPTX {"application/vnd.google-apps.presentation", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, // Google Drawings 导出为PNG {"application/vnd.google-apps.drawing", "image/png"}, // 可根据需求添加更多格式 }; if (exportFormatMap.TryGetValue(fileResponse.MimeType, out string targetExportMimeType)) { var exportRequest = service.Files.Export(fileId, targetExportMimeType); using (var outputStream = new FileStream(@"C:\你的保存路径\导出文件名.pdf", FileMode.Create, FileAccess.Write)) { exportRequest.Download(outputStream); } } else { throw new System.Exception($"暂不支持导出此类型的Google文档:{fileResponse.MimeType}"); } }
你之前遇到的问题解析
Export方法报403错误:
你之前用了fileResponse.MimeType作为导出格式,但Google原生文档的MimeType(比如application/vnd.google-apps.document)并不是有效的导出格式,必须指定实际的目标格式(比如application/pdf),这才是Export方法能识别的参数。直接拼接URL下载得到登录页面:
服务账号的认证是通过Google API客户端自动处理的,直接访问拼接的URL不会带上服务账号的认证头,所以会被跳转到登录页面。必须通过API提供的方法(Download或Export.Download)来发起请求,客户端会自动注入认证信息。
额外注意事项
- 确保你的服务账号已经被授予目标文件的访问权限:要么把文件共享给服务账号的邮箱(格式一般是
[服务账号ID]@[项目ID].iam.gserviceaccount.com),要么目标文件所在的Drive是服务账号可以访问的(比如团队盘)。 - 确认你的项目已经启用了Google Drive API,并且服务账号拥有
Drive.Readonly或更高权限的OAuth2 scope。
内容的提问来源于stack exchange,提问作者TCNSDCA
相关产品推荐
相关产品推荐

