'How to check if file exists in Google Cloud Storage using .NET and Google.Cloud.Storage.V1?

I would like to check if the file exists before trying to delete it as I want to avoid the exception. Removal method below - DeleteAssetAsync()

using Google.Apis.Auth.OAuth2;
using Google.Cloud.Storage.V1;

internal sealed class AssetsService
{
    private readonly GoogleCredential _googleCredential;
    private readonly StorageClient _storageClient;

    public AssetsService()
    {
        _googleCredential = GoogleCredential.FromFile("google.json");
        _storageClient = StorageClient.Create(_googleCredential);
    }

    public async Task DeleteAssetAsync()
    {
        await _storageClient.DeleteObjectAsync("gcp-assets-bucket", "file.txt");
    }
}

Exception

Google.Apis.Requests.RequestError No such object: gcp-assets-bucket/file.txt [404] Errors [ Message[No such object: gcp-assets-bucket/file.txt] Location[ - ] Reason[notFound] Domain[global] ]

The service storage has thrown an exception: Google.GoogleApiException: Google.Apis.Requests.RequestError No such object: gcp-assets-bucket/file.txt [404] Errors [ Message[No such object: gcp-assets-bucket/file.txt] Location[ - ] Reason[notFound] Domain[global] ]

I tried to download or get the file first and check if it is not null, but the downloading or getting method returns the same exception if it cannot find the file.

GetObject example

var googleAsset = await _storageClient.GetObjectAsync("gcp-assets-bucket", "file.txt");
if (googleAsset is not null)
{
    _storageClient.DeleteObjectAsync(googleAsset);
}

DownloadObject example

using var stream = File.OpenWrite("file.txt");
await _storageClient.DownloadObjectAsync("gcp-assets-bucket", "file.txt", stream);

Is there any way to check if file exists in Google Cloud Storage or get null if not exists without throwing an exception?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source