首页 > 解决方案 > 将目录移动到 Google 存储桶

问题描述

我们如何将整个文件夹(文件夹内也有很多子目录)移动到谷歌云的 Bucket?任何人都可以帮助解决这个问题。

标签: c#google-cloud-storage

解决方案


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);
           }
       }
   } 

推荐阅读