因此,我在C#中关注Google Drive API Rest Google´s step-by-step。我基本上想从我的控制台C#应用程序中列出我的Google云端硬盘中的文件。
我创建了Oauth2凭据,下载了json文件,导入到我的Visual Studio项目中,使用NuGet管理器安装了Google Drive API v3,复制并粘贴了C#代码(如下)。但是我在GoogleWebAuthorizationBroker.AuthorizeAsync()方法中不断收到错误{“访问被拒绝”}(在innerException中)。有人可以帮帮我吗?
我的C#代码:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Drive_API_Quickstart__2nd_attempt_
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-dotnet-quickstart.json
static string[] Scopes = { DriveService.Scope.DriveReadonly };
static string ApplicationName = "Drive API .NET Quickstart";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", 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,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 10;
listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
.Files;
Console.WriteLine("Files:");
if (files != null && files.Count > 0)
{
foreach (var file in files)
{
Console.WriteLine("{0} ({1})", file.Name, file.Id);
}
}
else
{
Console.WriteLine("No files found.");
}
Console.Read();
}
}
}
调试错误:
System.AggregateException was unhandled
HResult=-2146233088
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at Drive_API_Quickstart__2nd_attempt_.Program.Main(String[] args) in W:\Adriano\Visual Studio\Google Drive\Drive API Quickstart (2nd attempt)\Drive API Quickstart (2nd attempt)\Program.cs:line 34
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
ErrorCode=5
HResult=-2147467259
Message=Access is denied
NativeErrorCode=5
Source=System
StackTrace:
at System.Net.HttpListener.AddAllPrefixes()
at System.Net.HttpListener.Start()
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.StartListener()
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.<ReceiveCodeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.<AuthorizeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__1.MoveNext()
InnerException:
答案 0 :(得分:1)
您是否正确尝试过此实施授权?
您提到的document quickstart有关于身份验证的一些注意事项:
注释
授权信息存储在文件系统中,因此随后 执行不会提示授权。授权流程 在此示例中,它是为命令行应用程序设计的。对于 有关如何在Web应用程序中执行授权的信息,请参阅 图书馆OAuth 2.0指南的web applications section。
另外,请按照document about OAuth:
的步骤进行操作要查找OAuth 2.0凭据的重定向URI,请执行以下操作: 以下内容:
1。)在API控制台中打开“凭据”页面。
2.如果您尚未这样做,请点击创建凭据&gt;创建您的OAuth 2.0凭据。 OAuth客户端ID。
3.。)创建凭据后,通过单击OAuth 2.0中的客户端ID(对于Web应用程序)来查看或编辑重定向URL 客户ID部分。
您可能会错过这些步骤。您也可能拥有 client_secrets.json 的错误文件。请问您是如何实际下载该文件的?
答案 1 :(得分:1)
我遇到了与Windows桌面程序相同的问题。当我从调试器中搜索它时它没有工作。然后我使用&#34;以管理员身份运行&#34; 选项解决了问题。它弹出了谷歌帐户选择窗口。 这是我的代码。确保正确选择验证密钥。
void GoogleThread()
{
try
{
//Scopes for use with the Google Drive API
string[] scopes = new string[] {
DriveService.Scope.DriveFile};
var clientId = "Create auth0 Id and copy here"; // From https://console.developers.google.com
var clientSecret = ""; // From https://console.developers.google.com
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
GoogleWebAuthorizationBroker.Folder = "Drive.Sample";
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
},
scopes,
"Admin",
CancellationToken.None,
new FileDataStore("Daimto.GoogleDrive.Auth.Store")).Result;
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});
uploadFile(service, "d:\\bmjo\\EastManTemp.xml", "0B1HV_LVO8x0zSWFrRkE2LVFUQ2c");
}
catch (Exception exp)
{
MessageBox.Show(exp.Message, "Error");
}
}
// tries to figure out the mime type of the file.
private static string GetMimeType(string fileName)
{
string mimeType = "application/unknown";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
mimeType = regKey.GetValue("Content Type").ToString();
return mimeType;
}
public static File uploadFile(DriveService _service, string _uploadFile, string _parent)
{
if (System.IO.File.Exists(_uploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(_uploadFile);
body.Description = "File uploaded by Diamto Drive Sample";
body.MimeType = GetMimeType(_uploadFile);
body.Parents = new List<ParentReference>();// { new ParentReference() { Id = _parent } };
body.Parents.Add(new ParentReference() { Id = _parent });
// File's content.
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
request.Upload();
return request.ResponseBody;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else
{
Console.WriteLine("File does not exist: " + _uploadFile);
return null;
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(GoogleThread));
thread.Start();
}