C#与谷歌驱动器API:{“访问被拒绝”}
因此,我将在C#中为Google Drive API Rest介绍以下内容。我基本上想从控制台C#应用程序中列出我在谷歌硬盘中的文件 我创建了Oauth2凭据,下载了json文件,导入到我的VisualStudio项目中,使用NuGet manager安装了Google Drive API v3,复制并粘贴了C#代码(见下文)。但是我在GoogleWebAuthorizationBroker.AuthorizationAsync()方法中不断收到错误{“拒绝访问”}(在innerException中)。有人能帮我吗 我的C#代码:C#与谷歌驱动器API:{“访问被拒绝”},c#,json,visual-studio,google-drive-api,google-oauth,C#,Json,Visual Studio,Google Drive Api,Google Oauth,因此,我将在C#中为Google Drive API Rest介绍以下内容。我基本上想从控制台C#应用程序中列出我在谷歌硬盘中的文件 我创建了Oauth2凭据,下载了json文件,导入到我的VisualStudio项目中,使用NuGet manager安装了Google Drive API v3,复制并粘贴了C#代码(见下文)。但是我在GoogleWebAuthorizationBroker.AuthorizationAsync()方法中不断收到错误{“拒绝访问”}(在innerExceptio
使用Google.api.Auth.OAuth2;
使用Google.api.Drive.v3;
使用Google.api.Drive.v3.Data;
使用Google.api.Services;
使用Google.api.Util.Store;
使用制度;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
使用系统文本;
使用系统线程;
使用System.Threading.Tasks;
命名空间驱动器\u API\u快速启动\u第二次尝试_
{
班级计划
{
//如果修改这些作用域,请删除以前保存的凭据
//位于~/.credentials/drive-dotnet-quickstart.json
静态字符串[]范围={DriveService.Scope.DriveReadonly};
静态字符串ApplicationName=“Drive API.NET Quickstart”;
静态void Main(字符串[]参数)
{
用户凭证;
使用(var)流=
新的文件流(“client_secret.json”、FileMode.Open、FileAccess.Read))
{
字符串credPath=System.Environment.GetFolderPath(
系统、环境、专用文件夹、个人);
credPath=Path.Combine(credPath,“.credentials/drive dotnet quickstart.json”);
凭证=GoogleWebAuthorizationBroker.AuthorizationAsync(
GoogleClientSecrets.Load(stream.Secrets),
范围,
“用户”,
取消令牌。无,
新文件数据存储(credPath,true))。结果;
Console.WriteLine(“凭证文件保存到:”+credPath);
}
//创建驱动器API服务。
var service=new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer=凭证,
ApplicationName=ApplicationName,
});
//定义请求的参数。
fileResource.ListRequest ListRequest=service.Files.List();
listRequest.PageSize=10;
listRequest.Fields=“nextPageToken,files(id,name)”;
//列出文件。
IList files=listRequest.Execute()
.档案;
Console.WriteLine(“文件:”);
if(files!=null&&files.Count>0)
{
foreach(文件中的var文件)
{
Console.WriteLine(“{0}({1})”,file.Name,file.Id);
}
}
其他的
{
WriteLine(“未找到任何文件”);
}
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:
System.AggregateException未处理
HResult=-2146233088
消息=发生了一个或多个错误。
Source=mscorlib
堆栈跟踪:
位于System.Threading.Tasks.Task.ThrowifeException(布尔值IncludeTaskCanceledException)
位于System.Threading.Tasks.Task`1.GetResultCore(布尔waitCompletionNotification)
在System.Threading.Tasks.Task`1.get_Result()中
在W:\Adriano\visualstudio\Google Drive\Drive API Quickstart(第二次尝试)\Drive API Quickstart(第二次尝试)\Program.cs中的Drive\API\Quickstart\uu第二次尝试\uu.Program.Main(字符串[]args)处
位于System.AppDomain.\u nExecuteAssembly(RuntimeAssembly程序集,字符串[]args)
位于System.AppDomain.ExecuteAssembly(字符串汇编文件、证据汇编安全性、字符串[]args)
在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()上
位于System.Threading.ThreadHelper.ThreadStart\u上下文(对象状态)
位于System.Threading.ExecutionContext.RunInternal(ExecutionContext ExecutionContext、ContextCallback回调、对象状态、布尔值preserveSyncCtx)
在System.Threading.ExecutionContext.Run(ExecutionContext ExecutionContext,ContextCallback回调,对象状态,布尔保存SyncCTX)
在System.Threading.ExecutionContext.Run(ExecutionContext ExecutionContext,ContextCallback回调,对象状态)
位于System.Threading.ThreadHelper.ThreadStart()处
内部异常:
错误代码=5
HResult=-2147467259
消息=访问被拒绝
NativeErrorCode=5
来源=系统
堆栈跟踪:
在System.Net.HttpListener.AddAllPrefixes()中
在System.Net.HttpListener.Start()中
在Google.api.Auth.OAuth2.LocalServerCodeReceiver.StartListener()上
在Google.api.Auth.OAuth2.LocalServerCodeReceiver.d__8.MoveNext()上
---来自引发异常的上一个位置的堆栈结束跟踪---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中
在Google.api.Auth.OAuth2.AuthorizationCodeInstalledApp.d_u8.MoveNext()上
---来自引发异常的上一个位置的堆栈结束跟踪---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中
在Google.api.Auth.OAuth2.GoogleWebAuthorizationBroker.d_u4.MoveNext()上
---来自引发异常的上一个位置的堆栈结束跟踪---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中
在Google.api.Auth.OAuth2。
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:
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();
}