c# - 将目录移动到 Google 存储桶
问题描述
我们如何将整个文件夹(文件夹内也有很多子目录)移动到谷歌云的 Bucket?任何人都可以帮助解决这个问题。
解决方案
C# 库的云存储客户端不支持上传文件夹,您必须创建一个函数(同步/异步)来获取文件夹内的所有文件/子文件夹并上传每个文件。
我在这个 Microsoft链接中找到了一个文件夹迭代器代码在我的代码示例中,我添加了 GCS 库来上传文件,不需要创建文件夹结构。
例如
// GCS dependencies
using Google.Apis.Storage.v1;
using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using Storage;
// GCS dependencies
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
System.IO.FileInfo[] files = null;
System.IO.DirectoryInfo[] subDirs = null;
// initialize the GCS client library
var storage = StorageClient.Create();
// use this variable to define the upload bucket, please use your bucket name
var bucketName= Myawesomebucket
try
{
files = root.GetFiles("*.*");
}
catch (UnauthorizedAccessException e)
{
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
}
if (files != null)
{
foreach (System.IO.FileInfo fi in files)
{
// If we
// want to open, delete or modify the file, then
// a try-catch block is required here to handle the case
// where the file has been deleted since the call to TraverseTree().
Console.WriteLine(fi.FullName);
// this section is used to upload files to GCS
// the object name includ folder/subfolder structure
objectName = objectName ?? Path.GetFileName(fi.FullPath);
// upload the object to the bucket
storage.UploadObject(bucketName, objectName, null, f);
Console.WriteLine($"Uploaded {objectName}.");
}
// Now find all the subdirectories under this directory.
subDirs = root.GetDirectories();
foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
// Resursive call for each subdirectory.
WalkDirectoryTree(dirInfo);
}
}
}
推荐阅读
- java - 在 Apache Beam 中写入不同的源
- dart - 任何获取 GoogleCredential 访问令牌的 Flutter 包
- javascript - 如何以百分比显示 HTML 表格数据
- java - Maven - 构建 jar 后文件丢失
- design-patterns - 重构代码以在 Rust 中实现组合的最佳方法是什么?
- php - Php Array Key Exist but it is impossible to access element giving
- sql - JSONB 转数组数据类型
- android - 如果我使用简单的适配器来提供列表视图并且列表视图包含文本视图和按钮,那么我该如何在特定位置执行操作?
- python - 尝试在 macOS 上安装 pandas 时遇到 Errno 2“没有这样的文件或目录”
- django - 我的数据库表中有一个 start_date 和 end_date,如何返回当前日期介于这两个值之间的所有记录?