How do I serialize a .NET object into Azure Blob Storage without using a temporary file?
Asked Answered
E

2

7

I want to store a .NET object into Azure Blob Storage.

Currently I serialize it into an XML file using TextWriter (episodeList is the object I want serialized):

XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes Xmlattr = new XmlAttributes();
Xmlattr.XmlRoot = new XmlRootAttribute("EPISODES");
overrides.Add(typeof(List<EpisodeData>), Xmlattr);
XmlSerializer serializer = new XmlSerializer(typeof(List<EpisodeData>), overrides);
TextWriter textWriter = new StreamWriter(@"C:\movie.xml");
serializer.Serialize(textWriter, episodeList);
textWriter.Close();

and then upload the file into Blob Storage:

CloudBlobClient blobStorage = createOrGetReferenceOfBlobStorage(folderName);
string uniqueBlobName = string.Format("{0}/{1}", folderName, fileName);
CloudBlockBlob blob = clouBblockBlobPropertySetting(blobStorage, uniqueBlobName, ".txt");
using (StreamWriter writer = new StreamWriter(blob.OpenWrite()))
{
    writer.Write(content);
} 

Is it possible to somehow skip the temporary file so that the XML is directly uploaded into Azure Blob Storage?

Ebullient answered 14/6, 2012 at 13:8 Comment(1)
Is it possible to specify the bloob path instad of C:\movie.xmlEbullient
C
6

You could do the following. Create a MemoryStream instance and use XmlSerializer.Serialize(Stream stream) to serialize the object into the memory stream, then "rewind" the stream to beginning using Seek(). Then you call CloudBlob.UploadFromStream() to upload the stream contents to the blob.

Compatible answered 15/6, 2012 at 6:15 Comment(0)
R
0

You can use this example:

public async Task SaveToBlobDirectlyAsync(string blobName, object data)
{
    var blob = await GetBlockBlobAsync(blobName); // your method to get blob instance

    using (var memoryStream = new MemoryStream())
    {
        using (var streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8))
        using (var jsonWriter = new JsonTextWriter(streamWriter))
        {
            var serializer = new JsonSerializer();
            serializer.Serialize(jsonWriter, data);

            jsonWriter.Flush();
            memoryStream.Position = 0;

            await blob.UploadFromStreamAsync(memoryStream);
        }
    }
}
Reflexive answered 10/9 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.