0

I'm trying to connect to my GoogleDrive using C#. My code is:

    using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

public class GoogleDriveFiles
{
    public string Id { get; set; }
    public string Name { get; set; }
    public long? Size { get; set; }
    public long? Version { get; set; }
    public DateTime? CreatedTime { get; set; }
}

static string ApplicationName = "test";
static string[] Scopes = { CalendarService.Scope.Calendar };
string credentialsJsonFIle = "c:\\webroot\\docs\\googleDriveCredentials.json";

[Obsolete]
protected void Page_Load(object sender, EventArgs e)
{
    UserCredential credential;
    using (var stream = new FileStream(credentialsJsonFIle, FileMode.Open, FileAccess.Read))
    {
        // The file token.json stores the user's access and refresh tokens, and is created
        // automatically when the authorization flow completes for the first time.
        string credPath = @"\token.json";
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore(credPath, true)).Result;
    }
    // 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 = int.MaxValue;
    listRequest.Fields = "nextPageToken, files(id, name, parents, size, shared, fullFileExtension, fileExtension, version, createdTime)";

    IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
    
    Response.Write("Files:<br/>");
        
    FilesResource.ListRequest FileListRequest = service.Files.List();
    //get file list.
    List<GoogleDriveFiles> FileList = new List<GoogleDriveFiles>();
    string tempPath = Path.GetTempPath();

    if (files != null && files.Count > 0)
    {
        foreach (var file in files)
        {
            if (file.FileExtension == "pdf")
            {
                GoogleDriveFiles File = new GoogleDriveFiles
                {
                    Id = file.Id,
                    Name = file.Name,
                    Size = file.Size,
                    Version = file.Version,
                    CreatedTime = file.CreatedTime
                };
                FileList.Add(File);
                FilesResource.GetRequest request = service.Files.Get(file.Id);
                MemoryStream stream1 = new MemoryStream();
                string pathFile = System.IO.Path.Combine(tempPath, file.Name);

                request.Download(stream1);

                SaveStream(stream1, pathFile);
                service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });
            }
        }
    }
    else
    {
        Response.Write("No files found.<br/>");
    }
}

And I'm getting the following error message: The network location cannot be reached. For information about network troubleshooting, see Windows Help

At line: credential = GoogleWebAuthorizationBroker.AuthorizeAsync(

My stacktrace displays the following:

    [HttpListenerException (0x4d0): The network location cannot be reached. For information about network troubleshooting, see Windows Help]
   System.Net.HttpListener.AddAllPrefixes() +352
   System.Net.HttpListener.Start() +297
   Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.StartListener() +114
   Google.Apis.Auth.OAuth2.<ReceiveCodeAsync>d__13.MoveNext() +76
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__8.MoveNext() +479
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__4.MoveNext() +422
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__1.MoveNext() +286

[AggregateException: One or more errors occurred.]
   System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) +4323141
   System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) +12865987
   System.Threading.Tasks.Task`1.get_Result() +33
   TestGoogleDrive.Page_Load(Object sender, EventArgs e) in c:\Webroot\www.godigix.com\test\testGoogleDrive.aspx.cs:48
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +95
   System.Web.UI.Control.LoadRecursive() +59
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +678

Can someone help me? My json file path is correct and file exists at given path.

2
  • isnt Page_load used for asp.net core? A web application. Your code is designed for an installed appliation. Commented Jun 21, 2021 at 9:59
  • Are you trying to use your own account? Or are you trying to get permissions for a user's account?
    – Martí
    Commented Jun 21, 2021 at 11:56

2 Answers 2

1

protected void Page_Load(object sender, EventArgs e)

Implies to me that you are trying to create a web application GoogleWebAuthorizationBroker.AuthorizeAsync is designed for use installed applications only. It opens the consent screen on the machine its running on this being the webserver.

For asp .net core you would need to use dependency injection and then you you can load the

/// <summary>
/// Lists the authenticated user's Google Drive files.
/// Specifying the <see cref="GoogleScopedAuthorizeAttribute"> will guarantee that the code
/// executes only if the user is authenticated and has granted the scope specified in the attribute
/// to this application.
/// </summary>
/// <param name="auth">The Google authorization provider.
/// This can also be injected on the controller constructor.</param>
[GoogleScopedAuthorize(DriveService.ScopeConstants.DriveReadonly)]
public async Task<IActionResult> DriveFileList([FromServices] IGoogleAuthProvider auth)
{
    GoogleCredential cred = await auth.GetCredentialAsync();
    var service = new DriveService(new BaseClientService.Initializer
    {
        HttpClientInitializer = cred
    });
    var files = await service.Files.List().ExecuteAsync();
    var fileNames = files.Files.Select(x => x.Name).ToList();
    return View(fileNames);
}

I have a video on how to use ASP .net core with the Google Profile API it will show you how to configure the depends injection How to get a Google users profile information, with C#.

2
  • Hello and thank you, but there is any option to do not require human interaction?
    – Pimager
    Commented Jun 21, 2021 at 10:32
  • If you control the drive account you are trying to access, then you should go with a service account. youtu.be/UTTTtwb7x7g If its user data then you need their consent to access their drive account so you will need to go with Oauth2. Commented Jun 21, 2021 at 11:37
1

I faced the same problem. After downloading Google's OAuth Api for Windows Source Code and debugging it, could see this error was caused by System.Net.HttpListener. A simple google search led me to this answer

Solution: Run in elevated command prompt

netsh http add iplisten 127.0.0.1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.