本文整理汇总了C#中Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer类的典型用法代码示例。如果您正苦于以下问题:C# CloudBlobContainer类的具体用法?C# CloudBlobContainer怎么用?C# CloudBlobContainer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CloudBlobContainer类属于Microsoft.WindowsAzure.Storage.Blob命名空间,在下文中一共展示了CloudBlobContainer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ParallelUploadFile
public static void ParallelUploadFile(CloudBlobContainer blobContainer, string blobName, string filePath, string contentType = null)
{
var start = DateTime.Now;
Console.WriteLine("\nUpload file in parallel.");
CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(blobName);
// 2M blocks for demo
int blockLength = 2 * 1000 * 1024;
byte[] dataToUpload = File.ReadAllBytes(filePath);
int numberOfBlocks = (dataToUpload.Length / blockLength) + 1;
string[] blockIds = new string[numberOfBlocks];
Parallel.For(0, numberOfBlocks, x =>
{
var blockId = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
var currentLength = Math.Min(blockLength, dataToUpload.Length - (x * blockLength));
using (var memStream = new MemoryStream(dataToUpload, x * blockLength, currentLength))
{
blockBlob.PutBlock(blockId, memStream, null);
}
blockIds[x] = blockId;
Console.WriteLine("BlockId:{0}", blockId);
});
if (!String.IsNullOrEmpty(contentType)) { blockBlob.Properties.ContentType = contentType; }
blockBlob.PutBlockList(blockIds);
Console.WriteLine("URL:{0}, ETag:{1}", blockBlob.Uri, blockBlob.Properties.ETag);
var timespan = DateTime.Now - start;
Console.WriteLine("{0} seconds.", timespan.Seconds);
}
示例2: CopyContainer
public async Task CopyContainer(CloudBlobContainer sourceContainer, string destination)
{
var uri = new Uri(sourceContainer.Uri.AbsoluteUri.TrimEnd('/') + '/');
destination = Path.Combine(destination, sourceContainer.Name);
BlobContinuationToken continuationToken = null;
do
{
var segments = await sourceContainer.ListBlobsSegmentedAsync(prefix: null, useFlatBlobListing: true,
blobListingDetails: BlobListingDetails.Metadata, maxResults: MaxParallelDownloads,
currentToken: continuationToken, options: null, operationContext: null);
var tasks = new BlockingCollection<Task>(MaxParallelDownloads);
Parallel.ForEach(segments.Results.Cast<CloudBlockBlob>(), srcFile =>
{
var relativePath = uri.MakeRelativeUri(srcFile.Uri);
var destLocation = Path.Combine(destination, relativePath.OriginalString);
if (File.Exists(destLocation) && File.GetLastWriteTimeUtc(destLocation) == srcFile.Properties.LastModified)
{
// If the file looks unchanged, skip it.
return;
}
Directory.CreateDirectory(Path.GetDirectoryName(destLocation));
tasks.Add(srcFile.DownloadToFileAsync(destLocation, FileMode.Create));
});
await Task.WhenAll(tasks);
continuationToken = segments.ContinuationToken;
} while (continuationToken != null);
}
示例3: SetContainerPermission
protected void SetContainerPermission(CloudBlobContainer container, BlobContainerPublicAccessType perimssion)
{
container.SetPermissionsAsync(new BlobContainerPermissions
{
PublicAccess = perimssion
});
}
示例4: UploadFileToBlob
public static void UploadFileToBlob(string fileName, string containerSAS)
{
Console.WriteLine("Uploading {0} to {1}", fileName, containerSAS);
CloudBlobContainer container = new CloudBlobContainer(new Uri(containerSAS));
CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
blob.UploadFromStream(new FileStream(fileName, FileMode.Open, FileAccess.Read));
}
示例5: ListBlobs
public static void ListBlobs(CloudBlobContainer blobContainer, BlobListing blobListing, String prefix = null)
{
if (blobListing == BlobListing.Flat)
{
foreach (var blockBlob in blobContainer.ListBlobs(prefix: null, useFlatBlobListing: true))
{
Console.WriteLine("{0,-10} - {1}", @"Blob", ((CloudBlockBlob)blockBlob).Name);
Console.WriteLine("{0,-10} - {1}", String.Empty, blockBlob.Uri);
}
}
else if (blobListing == BlobListing.Hierarchical)
{
foreach (var blockBlob in blobContainer.ListBlobs(prefix: prefix, useFlatBlobListing: false))
{
if (blockBlob is CloudBlockBlob)
{
Console.WriteLine("{0,-10} - {1}", @"Blob", ((CloudBlockBlob)blockBlob).Name);
Console.WriteLine("{0,-10} - {1}", String.Empty, blockBlob.Uri);
}
else if (blockBlob is CloudBlobDirectory)
{
Console.WriteLine("{0,-10} - {1}", @"Directory", ((CloudBlobDirectory)blockBlob).Prefix);
Console.WriteLine("{0,-10} - {1}", String.Empty, blockBlob.Uri);
ListBlobs(blobContainer, BlobListing.Hierarchical, ((CloudBlobDirectory)blockBlob).Prefix);
}
}
}
}
示例6: CloudBlobDirectorySetupWithDelimiterAsync
private async Task<bool> CloudBlobDirectorySetupWithDelimiterAsync(CloudBlobContainer container, string delimiter = "/")
{
try
{
for (int i = 1; i < 3; i++)
{
for (int j = 1; j < 3; j++)
{
for (int k = 1; k < 3; k++)
{
String directory = "TopDir" + i + delimiter + "MidDir" + j + delimiter + "EndDir" + k + delimiter + "EndBlob" + k;
CloudPageBlob blob1 = container.GetPageBlobReference(directory);
await blob1.CreateAsync(0);
}
}
CloudPageBlob blob2 = container.GetPageBlobReference("TopDir" + i + delimiter + "Blob" + i);
await blob2.CreateAsync(0);
}
return true;
}
catch (Exception e)
{
throw e;
}
}
示例7: CreateBlobsTask
public static List<string> CreateBlobsTask(CloudBlobContainer container, int count, BlobType type)
{
string name;
List<string> blobs = new List<string>();
for (int i = 0; i < count; i++)
{
switch (type)
{
case BlobType.BlockBlob:
name = "bb" + Guid.NewGuid().ToString();
CloudBlockBlob blockBlob = container.GetBlockBlobReference(name);
blockBlob.PutBlockListAsync(new string[] { }).Wait();
blobs.Add(name);
break;
case BlobType.PageBlob:
name = "pb" + Guid.NewGuid().ToString();
CloudPageBlob pageBlob = container.GetPageBlobReference(name);
pageBlob.CreateAsync(0).Wait();
blobs.Add(name);
break;
}
}
return blobs;
}
示例8: CopyBlobData
/// <summary>
/// Initiates the SolCat Azure blob data sync.
/// </summary>
public static void CopyBlobData()
{
// Authentication Credentials for Azure Storage:
var credsSrc
= new StorageCredentials(
ConfigHelper.GetConfigValue("HubContainerName"),
ConfigHelper.GetConfigValue("HubContainerKey"));
var credsDest
= new StorageCredentials(
ConfigHelper.GetConfigValue("NodeContainerKey"),
ConfigHelper.GetConfigValue("NodeContainerKey"));
// Source Container: Hub (Development)
_srcContainer =
new CloudBlobContainer(
new Uri(ConfigHelper.GetConfigValue("HubContainerUri")),
credsSrc);
// Destination Container: Node (Production)
_destContainer =
new CloudBlobContainer(
new Uri(ConfigHelper.GetConfigValue("NodeContainerUri")),
credsDest);
// Set permissions on the container:
var permissions = new BlobContainerPermissions {PublicAccess = BlobContainerPublicAccessType.Blob};
_srcContainer.SetPermissions(permissions);
_destContainer.SetPermissions(permissions);
// Call the blob copy master method:
CopyBlobs(_srcContainer, _destContainer);
}
示例9: GetBlobs
public List<CloudBlockBlob> GetBlobs(CloudBlobContainer container, string filter = "")
{
return container.ListBlobs()
.OfType<CloudBlockBlob>()
.Where(b => String.IsNullOrEmpty(filter) || b.Name.Contains(filter))
.ToList();
}
示例10: BlobStorage
public BlobStorage(BlobSettings appSettings)
{
try
{
if (appSettings.ImageSize != null)
ResizeLayer = new ResizeLayer(appSettings.ImageSize, ResizeMode.Min);
UploadThumbnail = appSettings.UploadThumbnail;
StorageAccountName = appSettings.StorageAccountName;
StorageAccountAccessKey = appSettings.StorageAccountAccessKey;
// Create a blob client and retrieve reference to images container
BlobClient = StorageAccount.CreateCloudBlobClient();
Container = BlobClient.GetContainerReference(appSettings.ContainerName);
// Create the "images" container if it doesn't already exist.
if (Container.CreateIfNotExists())
{
// Enable public access on the newly created "images" container
Container.SetPermissions(
new BlobContainerPermissions
{
PublicAccess =
BlobContainerPublicAccessType.Blob
});
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
示例11: InitStorage
private static void InitStorage()
{
var credentials = new StorageCredentials(AppKeys.Storage_Account_Name, AppKeys.PrimaryAccessKey);
var storageAccount = new CloudStorageAccount(credentials, true);
var blobClient = storageAccount.CreateCloudBlobClient();
imagesContainer = blobClient.GetContainerReference("images");
}
示例12: AzureFileSystem
public AzureFileSystem(string containerName, string root, bool isPrivate, CloudStorageAccount storageAccount) {
// Setup the connection to custom storage accountm, e.g. Development Storage
_storageAccount = storageAccount;
ContainerName = containerName;
_root = String.IsNullOrEmpty(root) ? "": root + "/";
_absoluteRoot = Combine(Combine(_storageAccount.BlobEndpoint.AbsoluteUri, containerName), _root);
//using ( new HttpContextWeaver() )
{
BlobClient = _storageAccount.CreateCloudBlobClient();
// Get and create the container if it does not exist
// The container is named with DNS naming restrictions (i.e. all lower case)
Container = BlobClient.GetContainerReference(ContainerName);
Container.CreateIfNotExists();
Container.SetPermissions(isPrivate
? new BlobContainerPermissions
{PublicAccess = BlobContainerPublicAccessType.Off}
: new BlobContainerPermissions
{PublicAccess = BlobContainerPublicAccessType.Blob}); // deny listing
}
}
示例13: AzureImageUploader
public AzureImageUploader()
{
var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
_blobClient = storageAccount.CreateCloudBlobClient();
_container = FindOrCreateContainer(ContainerName);
_filecontainer = FindOrCreateContainer(FileContainerName);
}
示例14: Init
public async Task Init( string name, IProviderRuntime providerRuntime, IProviderConfiguration config )
{
Log = providerRuntime.GetLogger( this.GetType().Name );
try
{
ConfigureJsonSerializerSettings( config );
if( !config.Properties.ContainsKey( "DataConnectionString" ) )
{
throw new BadProviderConfigException(
"The DataConnectionString setting has not been configured in the cloud role. Please add a DataConnectionString setting with a valid Azure Storage connection string." );
}
else
{
var account = CloudStorageAccount.Parse( config.Properties[ "DataConnectionString" ] );
var blobClient = account.CreateCloudBlobClient();
var containerName = config.Properties.ContainsKey( "ContainerName" ) ? config.Properties[ "ContainerName" ] : "grainstate";
container = blobClient.GetContainerReference( containerName );
await container.CreateIfNotExistsAsync();
}
}
catch( Exception ex )
{
Log.Error( 0, ex.ToString(), ex );
throw;
}
}
示例15: Initialise
/// <summary>
/// Occurs when a storage provider operation has completed.
/// </summary>
//public event EventHandler<StorageProviderEventArgs> StorageProviderOperationCompleted;
#endregion
// Initialiser method
private void Initialise(string storageAccount, string containerName)
{
if (String.IsNullOrEmpty(containerName))
throw new ArgumentException("You must provide the base Container Name", "containerName");
ContainerName = containerName;
_account = CloudStorageAccount.Parse(storageAccount);
_blobClient = _account.CreateCloudBlobClient();
_container = _blobClient.GetContainerReference(ContainerName);
try
{
_container.FetchAttributes();
}
catch (StorageException)
{
Trace.WriteLine(string.Format("Create new container: {0}", ContainerName), "Information");
_container.Create();
// set new container's permissions
// Create a permission policy to set the public access setting for the container.
BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
// The public access setting explicitly specifies that the container is private,
// so that it can't be accessed anonymously.
containerPermissions.PublicAccess = BlobContainerPublicAccessType.Off;
//Set the permission policy on the container.
_container.SetPermissions(containerPermissions);
}
}