首页 > 解决方案 > 如何在 C# 中创建 XML 文件并上传到 azure blob

问题描述

XDocument我使用 C#库创建了 XML 数据。我尝试将 XML 数据上传到 azure blob。下面是我的代码。

 using Microsoft.WindowsAzure.Storage;
 using Microsoft.WindowsAzure.Storage.Blob;
 using System.Xml.Linq;
 public CloudBlobClient blobClient {get;}

public AzureBlobServices(string storageAccountConnection)
{
 StorageAccountConnection = storageAccountConnection;
 storageAccount = CloudStorageAccount.Parse(StorageAccountConnection);
 blobClient = storageAccount.CreateCloudBlobClient();
}

     public async Task sampleFile()
     {
      XDocument doc = new XDocument( new XElement( "body", 
                                    new XElement( "level1", 
                                    new XElement( "level2", "text" ), 
                                    new XElement( "level2", "other text" ) ) ) );
            MemoryStream stream = new MemoryStream();
            doc.Save(stream);
            var container = blobClient.GetContainerReference("folder location");
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("Data/xml/Data.csv");
            await blockBlob.UploadFromStreamAsync(stream);
}

但是文件已上传,但文件中没有任何内容。代码有什么问题?

文件现在可用。添加后基于 Mario Vernari 答案
xmlStream.Position = 0; 在此处输入图像描述

标签: c#.net-core

解决方案


尝试重置流的位置:

MemoryStream stream = new MemoryStream();
doc.Save(stream);
stream.Position = 0;

推荐阅读