如何使用C#从Google Cloud中的特定文件夹读取文件

时间:2019-12-15 04:19:09

标签: c# google-cloud-platform google-cloud-storage

以下代码仅适用于从存储桶中所有文件夹中读取所有对象。

string bucketName = "testbucket";

// Explicitly use service account credentials by specifying the private key file.
// The service account should have Object Manage permissions for the bucket.
GoogleCredential credential = null;
using (var jsonStream = new FileStream("credentials.json", FileMode.Open,
    FileAccess.Read, FileShare.Read))
{
    credential = GoogleCredential.FromStream(jsonStream);
}
var storageClient = StorageClient.Create(credential);

// List objects
foreach (var obj in storageClient.ListObjects(bucketName, ""))
{
    //Console.WriteLine(obj.Name);
    var fileStream = File.Create("Program-copy.xml");
    storageClient.DownloadObject(bucketName, obj.Name, fileStream);
    break;
}

1 个答案:

答案 0 :(得分:2)

您当前正在指定前缀"",该前缀确实会匹配所有对象。

如果要指定文件夹“ foo / bar”,则只需指定前缀foo/bar/

要确保您也不会在子目录中检索项目,则需要指定Delimiter选项。例如,您可以使用:

var options = new ListObjectsOptions { Delimiter = "/" };
var items = storageClient.ListObjects(bucketName, "foo/bar/", options);

如果要为子目录包括一个项目,但不包括该子目录的所有内容,请在选项中添加IncludeTrailingDelimeter = true