简体   繁体   English

C# Google Storage Client - 上传文件 - 如果已经存在则失败

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

I am using the google storage c# client.我正在使用谷歌存储 c# 客户端。 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.注意:显而易见的解决方案是在上传之前检查文件是否存在,但这并不涵盖我的竞争条件。

Cloud Storage automatically overwrite an existing object in a bucket as it is describedhere因为它描述了一个水桶云存储自动覆盖现有对象这里

"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." “如果您上传与 Cloud Storage 存储桶中现有对象同名的文件,现有对象将被覆盖。要保留旧版本的对象,请启用对象版本控制。”

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#. 这个其他 Stackoverflow 问题可以帮助您作为参考, 这个其他 GCP 文档向您展示如何使用 C# 实现它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM