我正在使用以下代码使用DotNetZip nuget包将XML文件上传到Azure Blob存储帐户。
XmlDocument doc = new XmlDocument();
doc.Load(path);
string xmlContent = doc.InnerXml;
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
var cloudBlobClient = storageAccount.CreateCloudBlobClient();
var cloudBlobContainer = cloudBlobClient.GetContainerReference(container);
cloudBlobContainer.CreateIfNotExists();
using (var fs = File.Create("test.zip"))
{
using (var s = new ZipOutputStream(fs))
{
s.PutNextEntry("entry1.xml");
byte[] buffer = Encoding.ASCII.GetBytes(xmlContent);
s.Write(buffer, 0, buffer.Length);
fs.Position = 0;
//Get the blob ref
var blob = cloudBlobContainer.GetBlockBlobReference("test.zip");
blob.Properties.ContentEncoding = "zip"
blob.Properties.ContentType = "text/plain";
blob.Metadata["filename"] = "test.zip";
blob.UploadFromStream(fs);
}
}
此代码在我的容器中创建一个zip文件。但是当我下载并尝试打开它时,出现以下错误:“ Windows无法打开该文件夹。压缩(压缩)的文件夹无效”。但是可以将应用程序目录中保存的压缩文件解压缩,并包含我的xml文件。我在做什么错?
我能够重现您遇到的问题。本质上,问题在于,当您启动上载命令时,内容没有完全写在zip文件中。在我的测试中,本地磁盘上的zip文件大小为902字节,但是在上载时,文件流的大小仅为40字节,这就是问题所在。
我所做的是将两个功能分开,第一个功能只是创建文件,并从文件中读取其他内容并上传到存储中。这是我使用的代码:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
var cloudBlobClient = storageAccount.CreateCloudBlobClient();
var cloudBlobContainer = cloudBlobClient.GetContainerReference("test");
cloudBlobContainer.CreateIfNotExists();
using (var fs = File.Create("test.zip"))
{
using (var s = new ZipOutputStream(fs))
{
s.PutNextEntry("entry1.xml");
byte[] buffer = File.ReadAllBytes(@"Path\To\MyFile.txt");
s.Write(buffer, 0, buffer.Length);
//Get the blob ref
}
}
using (var fs = File.OpenRead("test.zip"))
{
var blob = cloudBlobContainer.GetBlockBlobReference("test.zip");
blob.Properties.ContentEncoding = "zip";
blob.Properties.ContentType = "text/plain";
blob.Metadata["filename"] = "test.zip";
fs.Position = 0;
blob.UploadFromStream(fs);
}