Does anyone know how to check if an object exists inside a Google Cloud Storage bucket via C#?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With