Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 694
Hope Avatar asked Jun 14 '12 13:06

Hope


People also ask

How do I automatically upload files to Azure Blob Storage?

Create Power Automate Desktop FlowGo to containers and create a new container. Open the container and on the and navigate to Shared access signature. Select add, create, and write permission, change the time if needed, and press Generate SAS token and URL. Copy the Blob SAS URL and save it as the variable in the flow.

Why do we need azure file share when we have blobs?

Azure Blob is an object storage solution. It allows you to store a large amount of unstructured data, whereas Azure files permit you to develop managed file share for the cloud. Moreover, Azure file share can also be mounted by the on premises deployment of Windows, Linux, and macOS.


1 Answers

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.

like image 60
sharptooth Avatar answered Oct 23 '22 11:10

sharptooth