Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 851
Cesar Avatar asked Oct 15 '25 16:10

Cesar


1 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.

like image 59
Shawn Hall Avatar answered Oct 18 '25 09:10

Shawn Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!