How to check of object exists in Google Cloud Storage using C#?

Viewed 740

Does anyone know how to check if an object exists inside a Google Cloud Storage bucket via C#?

2 Answers

To test for the existence of an object without generating an exception when it isn't found, use the ListObjects() method.

The documentation on the prefix argument is a little misleading.

Only objects with names that start with this string will be returned.

In fact, the full object name can be used and will result in positive matches.

using( var client = StorageClient.Create() )
{
    var results = client.ListObjects( "bucketname", "test.jpg" );
    var exists = results?.Count() > 0;
    return exists;
}

I believe protecting results w/ the nullable test is unnecessary. Even when I get no results with this code results is still not null. That said, I feel safer with that added protection since we are explicitly trying to avoid a try/catch.

Obviously this code could be shortened, but I wanted to demonstrate each step of the process for clarity.

This code was tested in a .net6 Console App using Google.Cloud.Storage.V1 version 3.7.0.

You can use Google.Cloud.Storage.V1 library

using Google.Cloud.Storage.V1;

public class StorageClass 
{
    public bool IsObjectExist(string bucketName, string objectname)
    {
        var client = StorageClient.Create();
        return client.GetObject(bucketName, objectname) != null ? true : false;
    }
}
Related