簡體   English   中英

C# Google Cloud Storage 獲取文件夾中的 ListObjects

[英]C# Google Cloud Storage Get ListObjects in Folders

我將所有應用程序信息存儲在 Google Cloud Storage 中。 我創建了一個存儲桶,在這個存儲桶中我有文件夾。 使用該代碼,我可以獲得所有文件夾的列表。

public static IList<uFolder> ListFolders(string bucketName)
{
     if (storageService == null)
     {
          CreateAuthorizedClient();
     }

     Objects objects = storageService.Objects.List(bucketName).Execute();
     if (objects.Items != null)
     {
          return objects.Items.
               Where(x => x.ContentType == "application/x-www-form-urlencoded;charset=UTF-8").
               Select(x => new uFolder(x.Name)).ToList();
      }
      return null;
}

但實際上這段代碼,將我所有的文件和文件夾放在我的存儲桶中。 所以我需要提取它們。 我的第一個問題,這種方法有捷徑嗎?

我的另一個也是最重要的問題是,如何才能獲取特定文件夾中的所有文件? 例如; 我的存儲桶名稱是 MyBucket,我想從“MyBucket/2/”獲取所有文件。 我該怎么做? 這是檢查文件的媒體鏈接或自鏈接的唯一方法嗎?

謝謝大家的回答。 祝你有美好的一天,干得好...

我認為您想要的是將列表請求的Delimiter屬性設置為/ 這將在您的層次結構的頂層返回一個分隔的結果。

如果想在你的谷歌雲存儲中獲取頂級文件夾,每個人都可以使用;

ObjectsResource.ListRequest request = storageService.Objects.List(CurrentBucket);
request.Delimiter = "/";
Google.Apis.Storage.v1.Data.Objects response = request.Execute();
if (response.Prefixes != null)
{
    return response.Prefixes.ToList();
}

如果想獲取特定文件夾內的文件夾;

ObjectsResource.ListRequest request = storageService.Objects.List(CurrentBucket);
request.Delimiter = "/";
request.Prefix = delimiter; //delimiter is any sub-folder name. E.g : "2010/"
Google.Apis.Storage.v1.Data.Objects response = request.Execute();
if (response.Prefixes != null)
{
    return response.Prefixes.ToList();
}

注意:我正在返回可達文件夾的前綴。

這是針對您的問題(您能用 C# 向我展示任何示例嗎?我在互聯網上找不到任何示例 - Umut Çömlekçioğlu)。請檢查 C# 中的代碼以上傳對象或獲取對象列表 -

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

    string file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Test.csv");
    File.WriteAllText(file, "test");

    GoogleCredential credential = null;
    BucketConnector bucketConnector = new BucketConnector();
    credential = bucketConnector.ConnectStream();
    var storageClient = StorageClient.Create(credential);
    //Upload object in google bucket 
    string folderPath = ConfigurationParameters.FOLDER_NAME_IN_BUCKET;
    using (FileStream file = File.OpenRead(localPath))
    {
        objectName = folderPath + Path.GetFileName(localPath);
        storage.UploadObject(bucketName, objectName, null, file);           
    }   
 // get list of object from google bucket and specific folder   
ListObjectsOptions listObjectsOptions = new ListObjectsOptions();
                listObjectsOptions.Delimiter = "/";
               foreach (var obj in storageClient.ListObjects(ConfigurationParameters.BUCKET_NAME ,ConfigurationParameters.FOLDER_NAME_IN_BUCKET , listObjectsOptions))
                {
                    string obj_name = obj.Name;
                 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM