Reputation: 3049
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
Reputation: 826
You can prevent the overwrite using ifGenerationMatch(0)
:
https://cloud.google.com/storage/docs/json_api/v1/objects/insert#parameters
I am not a C# expert, but I think in C# this is available via the UploadObjectOptions
:
Specifically:
Upvotes: 1
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