Montoya
Montoya

Reputation: 3049

C# Google Storage Client - Upload file - Fail if already exists

I am using the google storage c# client. I am uploading a file to a specific location.

Sample code:

private void UploadFile(string bucketName, string localPath,
    string objectName = null)
{
    var storage = StorageClient.Create();
    using (var f = File.OpenRead(localPath))
    {
        objectName = objectName ?? Path.GetFileName(localPath);
        storage.UploadObject(bucketName, objectName, null, f);
        Console.WriteLine($"Uploaded {objectName}.");
    }
}

When uploading a file to the same location more than once, the new version overwrites the old version.

I want the upload to fail and throw exception(because the file already exists). How can I do that?

Note: The obvious solution is to check if the file exists before uploading, but this does not cover me from race conditions.

Upvotes: 0

Views: 1607

Answers (2)

Samuel Romero
Samuel Romero

Reputation: 1263

Cloud Storage automatically overwrite an existing object in a bucket as it is described here

"If you upload a file with the same name as an existing object in your Cloud Storage bucket, the existing object is overwritten. To keep older versions of the object, enable Object Versioning."

As an alternative, I think you can check if the object exist getting the metadata. This other Stackoverflow question can help you as reference and this other GCP documentation shows you how to implement it using C#.

private void GetMetadata(string bucketName, string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    
}

Upvotes: 0

Related Questions