2013-01-14 64 views
2

我想將文件上傳到Windows Azure blob存儲。根據我的理解,您可以將文件上傳到類似於子目錄的文件中。我要上傳文件到BLOB使得文件基本上是駐留在/TestContainer/subDirectory1/subDirectory2/file.png在Windows Azure Blob存儲中使用子目錄

// Setup the Windows Aure blob client 
CloudStorageAccount storageAccount = CloudStorageAccount.FromConfigurationSetting("BlobStorage"); 
CloudBlobClient client = storageAccount.CreateCloudBlobClient(); 

// Retrieve the TestContainer container from blob storage 
CloudBlobContainer container = client.GetContainerReference("TestContainer"); 
if (container.CreateIfNotExist()) 
    container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); 

// Setup the blob 
CloudBlob blob = container.GetBlobReference(""); 

// Create the meta data for the blob 
NameValueCollection metadata = new NameValueCollection(); 
metadata["id"] = fileID.ToString(); 
blob.Metadata.Add(metadata); 

// Store the blob 
byte[] bytes = GetFileBytes(); 
blob.UploadByteArray(bytes); 

如何上傳與目錄結構的文件?鏈接here提到有辦法做到這一點。但是,它並沒有告訴你如何去做。

謝謝!

回答

8

有幾種方法。更簡單的方法是僅使用/字符作爲已提及的@ makerofthings7。如果您願意,也可以使用CloudBlobDirectory對象。這是一個顯示兩者的例子。

CloudBlobContainer testContainer = blobClient.GetContainerReference("testcontainer"); 

//Upload using a CloudBlobDirectory object 
var dir = testContainer.GetDirectoryReference("UsingCloudDirectory/foo/bar/baz/"); 
var blobRef = dir.GetBlockBlobReference("BlobByDir.bin"); 

using (MemoryStream ms = new MemoryStream(new byte[] { 0x0 })) 
{ 
    blobRef.UploadFromStream(ms); 
} 

//Upload using the filename without a CloudBlobDirectory 
var blobRef2 = testContainer.GetBlockBlobReference("UsingBlobName/foo/bar/baz/BlobByName.bin"); 
using (MemoryStream ms = new MemoryStream(new byte[] { 0x0 })) 
{ 
    blobRef2.UploadFromStream(ms); 
} 
1

我相信所有你需要做的是包括在BLOB名稱的子目錄像/my/sub/directory/file.txt

目錄裏實際不存在的容器名稱之外,並通過在文件名/字符分隔的字符串。