I am trying to upload a file to Windows Azure blob storage. From my understanding, you can upload files into something similar to a subdirectory. I want to upload a file to a blob such that the file essentially resides in /TestContainer/subDirectory1/subDirectory2/file.png
// 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);
How do I upload a file with a directory structure? The link here mentions there's a way to do it. However, it doesn't show you how to do it.
Thank you!
There are a couple of ways. The easier way is to just use /
characters as @makerofthings7 already mentioned. You can also use a CloudBlobDirectory
object if you prefer. Here's an example showing both.
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);
}
I believe all you have to do is include the subdirectories in the blob name like /my/sub/directory/file.txt
Directories don't really exist outside of the container name and the strings delimited by a /
character in the file name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With