1
votes

I'm looking to at a way to create a folder inside a bucket using the following client library: https://cloud.google.com/storage/docs/json_api/v1/json-api-dotnet-samples

I've looked at the following thread, and it appears I need to use the simple method upload. Creating folder in bucket google cloud storage using php

I can't see any way of being able to specify a uploadtype, all requests appear to be uploadType=resumable.

Looking at the above post and a fiddler trace I need to use uploadType=media. Is there away to accomplish this?

3

3 Answers

5
votes

It is a bit more straighforward to do this in the latest version of the API. You still have to make sure that you check for the "/" as Salem has suggested.

     public void AddFolder(string folder)
        {
           StorageClient storageClient = StorageClient.Create();
           if (!FolderName.EndsWith("/"))
             FolderName += "/";         

          var content = Encoding.UTF8.GetBytes("");

           storageClient.UploadObject(bucketName, folder, "application/x-directory", new MemoryStream(content));

        }
1
votes

This worked for me! Don't know if it's the right way to do it, but there are not enough on this.

public void CreateDir(string FolderName)
    {
        if (!FolderName.EndsWith("/"))
            FolderName += "/";

        var uploadStream = new MemoryStream(Encoding.UTF8.GetBytes(""));
        Storage.Objects.Insert(
            bucket: BucketName,
            stream: uploadStream,
            contentType: "application/x-directory",
            body: new Google.Apis.Storage.v1.Data.Object() { Name = FolderName}
            ).Upload();
    }

EDIT: Just found out that you can directly upload the file to your destination objects, and if the directories/sub-directories don't exist the upload function will create them for you.

0
votes

All you need to do is put the folder(s) you want before the file name

using (MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(json)))
                        {
                            string fileName = $"/test/somefolder/{sourceId}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.json";
                            await gcpClient.UploadObjectAsync(gcpBucketName, fileName, null, ms);
                        }