C# WinForm调用Google Drive API报错:At least one client secrets should be set
解决Windows Forms中Google Drive API的"Client Secrets未设置"错误
嘿,我之前在做类似功能时也踩过这个坑!咱们一步步排查解决:
先确认你的JSON密钥文件类型正确
这个错误最常见的原因是你下载的不是**桌面应用(Installed App)**的客户端密钥。你需要回到Google Cloud控制台,重新创建凭证时选择「桌面应用」类型,再下载对应的JSON文件。打开这个JSON文件,里面必须包含"installed"字段,里面有client_id和client_secret这些关键信息——如果没有这个字段,说明你下错文件了。确保程序能找到你的JSON文件
你用的相对路径"GoogleDriveApi.json"在Windows Forms里,默认指向程序的运行目录(比如项目的bin/Debug文件夹),而不是你的项目根目录。解决办法有两个:- 右键项目里的
GoogleDriveApi.json文件 → 属性 → 「复制到输出目录」选择「始终复制」,这样编译时文件会自动拷贝到运行目录; - 改用绝对路径定位文件,比如:
string jsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GoogleDriveApi.json");
- 右键项目里的
修正后的代码示例
结合WinForms的特性,把Console输出改成MessageBox,同时确保路径正确:UserCredential credential; string jsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GoogleDriveApi.json"); using (var stream = new FileStream(jsonPath, FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { DriveService.Scope.DriveFile }, // 确保权限范围符合你的需求 "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; MessageBox.Show($"Credential file saved to: {credPath}"); }最后一招:重置凭证缓存
如果上面的步骤都试过还是不行,找到你的个人文件夹里的.credentials/drive-dotnet-quickstart.json文件删掉,然后重新运行程序,让它重新生成新的凭证缓存。
内容的提问来源于stack exchange,提问作者Yunus
相关产品推荐
相关产品推荐

