简体   繁体   English

如何使用 C# 检查 Google Cloud Storage 中是否存在对象?

[英]How to check of object exists in Google Cloud Storage using C#?

有谁知道如何通过 C# 检查 Google Cloud Storage 存储桶中是否存在对象?

You can use Google.Cloud.Storage.V1 library您可以使用 Google.Cloud.Storage.V1

using Google.Cloud.Storage.V1;

public class StorageClass 
{
    public bool IsObjectExist(string bucketName, string objectname)
    {
        var client = StorageClient.Create();
        return client.GetObject(bucketName, objectname) != null ? true : false;
    }
}

To test for the existence of an object without generating an exception when it isn't found, use the ListObjects() method.要在未找到对象时测试对象是否存在而不生成异常,请使用 ListObjects() 方法。

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.此代码使用 Google.Cloud.Storage.V1 版本 3.7.0 在 .net6 控制台应用程序中进行了测试。

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

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