How do I serialize a .NET object into Azure Blob S

2019-06-17 04:17发布

问题:

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?

回答1:

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.