Subscribe to our new YouTube channel for FREE videos on ASP.NET family of technologies. Click here for more details. Information about our instructor-led online courses is available here.

Get list of files from Google Drive in ASP.NET Core

Google drive offers a convenient way to organize and store your files in cloud. It has a rich user web interface that can be used to work with the files and folders. At times, however, you need to deal with the files stored in Google drive through an ASP.NET Core application. Consider a situation where you want to import files from user's Google drive into your web application for certain processing. Now this requires that you get a list of files from the user's Google drive and manipulate them as and when necessary. To that end this article shows how to use Google Drive API in an ASP.NET Core application to get a list of files from the Google drive.

Before you create the ASP.NET Core application, you need to do some setup using the Google developers console as discussed below.

First, visit Google developer console here and create a new project using the following dialog:

Once the project is created click on t he Enable APIs and Services button at the top and search for Google Drive API

Then enable Google Drive API for the newly created project.

 

Next, click on the Credentials option from the left side menu.

Then click on the Create Credentials button at the top and select the type of credentials to be OAuth client ID

Follow the instructions to create OAuth 2.0 client ID. You require these details while connecting with a Google drive account.

This completes the basic setup required to start your development.

Now, create a new ASP.NET Core MVC application. Open the appsettings.json file and store OAuth 2.0 client IDs in it as shown below:

"GoogleDrive": {
  "ClientId": "your_client_id_here",
  "ClientSecret": "your_client_secret_here",
  "UserName": "User1"
}

Note that ClientId and ClientSecret keys are obtained from the project setup described earlier. The UserName key is a developer defined value that indicates currently signed in user of the web application. In a more realistic case it will come from ASP.NET Core Identity or similar authentication mechanism. Since here we don't have any authentication scheme as such, a value of User1 is used.

Next, add the Google.Apis.Drive.v3 NuGet package to the project as shown below: 

This NuGet package offers all the functionality to connect with Google drive and manipulate files.

Now add a model class to the Models folder named GoogleDriveFileEntr.

public class GoogleDriveFileEntry
{
    public string FileId { get; set; }
    public string FileName { get; set; }
}

As you can see the GoogleDriveFileEntry class contains two properties - FileId and FileName. For this example we are more interested in FileName. We will use FileId in the future examples.

Then open the HomeController and modify its constructor as shown below:

private IConfiguration config;

public HomeController(IConfiguration config)
{
    this.config = config;
    this.env = env;
}

The constructor accepts IConfiguration object and we will use it to access the configuration information from appsettings.json.

Now go to the Index() action and add the following code.

public IActionResult Index()
{
    var clientId = config.GetValue<string>
("GoogleDrive:ClientId");
    var clientSecret = config.GetValue<string>
("GoogleDrive:ClientSecret");
    var userName = config.GetValue<string>
("GoogleDrive:UserName");
}

This code retrieves the ClientId, ClientSecret, and UserName values stored in the appsettings.json file.

Based on the ClientId and ClientSecret values construct a ClientSecrets object as shown below:

var clientSecrets = new ClientSecrets()
{
    ClientId = clientId,
    ClientSecret = clientSecret
};

string[] scopes = new string[] {
    DriveService.Scope.Drive,
    DriveService.Scope.DriveFile
};

The above code also creates scopes array that indicates what kind of permissions you want for the user's Google drive. Drive and DriveFile indicate full access to perform file operations.

You can't simply go and access user's Google drive. You first need to request user's consent to grant you the access. This is done using the AuthorizeAsync() method as shown below:

var userCredential = GoogleWebAuthorizationBroker.
AuthorizeAsync       
    (clientSecrets,
    scopes,
    userName,
    CancellationToken.None).Result;

The AuthorizeAsync() method accepts ClientSecrets object created earlier, scopes array, and current user's name. This method opens a web page that asks for user's login credentials and permission to grant the access. The following figure shows that web page.

Notice that the AuthorizeAsync() call returns a UserCredential object that you use to create a DriveService object.

var driveService = new DriveService(new 
BaseClientService.Initializer()
{
    HttpClientInitializer = userCredential,
    ApplicationName = "Google Drive API Demo",
});

Once the DriveService is ready you can get a list of files from the user's Google drive. The code that accomplishes that task is shown below:

var googleDriveFiles = new 
List<GoogleDriveFileEntry>();
FilesResource.ListRequest listRequest = 
driveService.Files.List();
listRequest.PageSize = 1000;
FileList fileList = listRequest.Execute();

while (fileList.Files != null)
{
    foreach (File file in fileList.Files)
    {
        googleDriveFiles.Add(new 
GoogleDriveFileEntry()
        {
            FileId=file.Id,
            FileName=file.Name
        });
    }

    if (fileList.NextPageToken == null)
    {
        break;
    }
                
    listRequest.PageToken = 
fileList.NextPageToken;
    fileList = listRequest.Execute();
}

return View(googleDriveFiles);

Notice the code shown in bold letters. The List() method returns a ListRequest object that is used to fetch a list of files. The PageSize property of ListRequest object is set to 1000. The PageSize property indicates the number of files to fetch at a time default being 100. The Execute() method of ListRequest returns a FileList object that can be used to enumerate through a list of file entries.

The while loop that follows basically iterates through the file entries and fills them in the googleDriveFiles List. Each file entry has many pieces of metadata information but we pick just two Id and Name. The code also contains logic to handle multiple pages of file entries.

Finally, the googleDriveFiles List is passed to the Index view.

Now open the Index.cshtml and write the following code in it.

@model List<GoogleDriveFileEntry>

<table border="1" width="10%" cellpadding="6">
    <tr>
        <th>File ID</th>
        <th>File Name</th>
    </tr>
    @foreach(var item in Model)
    {
    <tr>
        <td>@item.FileId</td>
        <td>@item.FileName</td>
    </tr>
    }
</table>

This code simply iterates through a list of files and displays them in a table.

If you run the application and sign-in using valid credentials (and also grant the permission to access the Google drive) you will see a table of file entries. The following figure shows a sample run of the application.

In the next part of this article we will learn to perform some basic manipulation operations of the Google drive files.

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant, trainer, author, yoga mentor, and meditation teacher. He has been programming, meditating, and teaching for 24+ years. He conducts instructor-led online training courses in ASP.NET family of technologies for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get article updates : Facebook  Twitter  LinkedIn  YouTube

Posted On : 06 January 2020


Tags : ASP.NET ASP.NET Core MVC .NET Framework C# Visual Studio