18

I am trying to load a JSON string (serialized with Newtonsoft.Json) without creating a temporary file.

I am serializing object in runtime using JsonConvert.SerializeObject(obj,settings) which returns a string.

Following Microsoft documentation I could do as it's illustrated below:

// Create a local file in the ./data/ directory for uploading and downloading
string localPath = "./data/";
string fileName = "quickstart" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);

// Write text to the file
await File.WriteAllTextAsync(localFilePath, "Hello, World!");

// Get a reference to a blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);

Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

// Open the file and upload its data
using FileStream uploadFileStream = File.OpenRead(localFilePath);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();

Although it works, I would have to create temporary file for each uploaded JSON file.

I tried this:

BlobServiceClient blobServiceClient = new BlobServiceClient("SECRET");

BlobContainerClient container = BlobServiceClient.GetBlobContainerClient("CONTAINER_NAME");

container.CreateIfNotExistsAsync().Wait();

container.SetAccessPolicy(Azure.Storage.Blobs.Models.PublicAccessType.Blob);

CloudBlockBlob cloudBlockBlob = new CloudBlockBlob(container.Uri);

var jsonToUplaod = JsonConvert.SerializeObject(persons, settings);

cloudBlockBlob.UploadTextAsync(jsonToUpload).Wait();

But, well...it doesn't have right to work as I am not specifing any actual file in the given container (I don't know where to do it).

Is there any way to upload a blob directly to a given container?

Thank You in advance.

1 Answer 1

40

The BlobClient class wants a Stream, so you can create a MemoryStream from your JSON string.
Try something like this:

BlobClient blob = container.GetBlobClient("YourBlobName");

using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonToUpload)))
{
    await blob.UploadAsync(ms);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Can you show this also in Python? I can't seem to find this anywhere & I have a similar issue.
I would recommend posting a new question for that, and put a Python tag on it. In your new question you can add a link back to this one for context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.