当前位置: 首页>>代码示例>>C#>>正文


C# CloudBlobContainer.CreateIfNotExistsAsync方法代码示例

本文整理汇总了C#中Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer.CreateIfNotExistsAsync方法的典型用法代码示例。如果您正苦于以下问题:C# CloudBlobContainer.CreateIfNotExistsAsync方法的具体用法?C# CloudBlobContainer.CreateIfNotExistsAsync怎么用?C# CloudBlobContainer.CreateIfNotExistsAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer的用法示例。


在下文中一共展示了CloudBlobContainer.CreateIfNotExistsAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CreateContainerAsync

 /// <summary>
 /// Creates a private container with the given name
 /// </summary>
 /// <param name="containerName"></param>
 /// <returns></returns>
 public async Task<bool> CreateContainerAsync(string containerName, bool isPublic)
 {
     // Create the container if it doesn't exist.
     blobContainer = blobClient.GetContainerReference(containerName);
     if (isPublic)
     {
         var returnData = await blobContainer.CreateIfNotExistsAsync();
         if (returnData)
             await blobContainer.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
         return returnData;
     }
     return await blobContainer.CreateIfNotExistsAsync();
 }
开发者ID:sudheeshv,项目名称:AzureStorage,代码行数:18,代码来源:BlobRepository.cs

示例2: 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;
      }
    }
开发者ID:DebugOfTheRoad,项目名称:BlobDemo,代码行数:28,代码来源:BlobStorageProvider.cs

示例3: Init

        /// <summary> Initialization function for this storage provider. </summary>
        /// <see cref="IProvider.Init"/>
        public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Log = providerRuntime.GetLogger("Storage.AzureBlobStorage");

            try
            {
                this.Name = name;
                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.");

                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().ConfigureAwait(false);

                Log.Info((int)AzureProviderErrorCode.AzureBlobProvider_InitProvider, "Init: Name={0} ServiceId={1} {2}", name, providerRuntime.ServiceId.ToString(), string.Join(" ", FormatPropertyMessage(config)));
                Log.Info((int)AzureProviderErrorCode.AzureBlobProvider_ParamConnectionString, "AzureBlobStorage Provider is using DataConnectionString: {0}", ConfigUtilities.PrintDataConnectionInfo(config.Properties["DataConnectionString"]));
            }
            catch (Exception ex)
            {
                Log.Error((int)AzureProviderErrorCode.AzureBlobProvider_InitProvider, ex.ToString(), ex);
                throw;
            }
        }
开发者ID:pedroreys,项目名称:orleans,代码行数:28,代码来源:AzureBlobStorage.cs

示例4: Setup

 /// <summary>
 /// 
 /// </summary>
 public void Setup()
 {
     Account = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureStorage"]);
     CloudBlobClient client = Account.CreateCloudBlobClient();
     Container = client.GetContainerReference(containerName);
     Container.CreateIfNotExistsAsync();
 }
开发者ID:ElizaReiGWCD,项目名称:ImageCandy,代码行数:10,代码来源:AzureFileStorage.cs

示例5: Init

 public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     try
     {
         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());
     }
 }
开发者ID:justinliew,项目名称:OrleansBlobStorageProvider,代码行数:15,代码来源:BlobStorageProvider.cs

示例6: FileHandler

        public FileHandler(CloudStorageAccount storageAccount, ImageTestContext context)
        {
            // Retrieve storage account from connection string.
            _storageAccount = storageAccount;
            // Create the blob client.
            _blobClient = _storageAccount.CreateCloudBlobClient();
            // Retrieve reference to a previously created container.
            _container = _blobClient.GetContainerReference("pictures");
            _container.CreateIfNotExistsAsync();

            _db = context;

            imageSizes = new List<ImageSize>
            {
                new ImageSize { Size = Sizes.thumb, width = 80 },
                new ImageSize { Size = Sizes.small, width = 360 },
                new ImageSize { Size = Sizes.medium, width = 640 },
                new ImageSize { Size = Sizes.large, width = 1024 }
            };
            
        }
开发者ID:s165519,项目名称:ASPNET5Examples,代码行数:21,代码来源:FileHandler.cs

示例7: CreateContainerIfNotExistsAsync

 /// <summary>
 /// Return a task that asynchronously create a container if it doesn't exist.
 /// </summary>
 /// <param name="container">CloudBlobContainer object</param>
 /// <param name="accessType">Blob container public access type</param>
 /// <param name="requestOptions">Blob request options</param>
 /// <param name="operationContext">Operation context</param>
 /// <param name="cmdletCancellationToken">Cancellation token</param>
 /// <returns>Return a task that asynchronously create a container if it doesn't exist.</returns>
 public Task<bool> CreateContainerIfNotExistsAsync(CloudBlobContainer container, BlobContainerPublicAccessType accessType, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken)
 {
     return container.CreateIfNotExistsAsync(accessType, requestOptions, operationContext, cancellationToken);
 }
开发者ID:NordPool,项目名称:azure-sdk-tools,代码行数:13,代码来源:StorageBlobManagement.cs

示例8: CallSasSamples

        /// <summary>
        /// Calls shared access signature samples for both containers and blobs.
        /// </summary>
        /// <param name="container">A CloudBlobContainer object.</param>
        /// <returns>A Task object.</returns>
        private static async Task CallSasSamples(CloudBlobContainer container)
        {
            const string BlobName1 = "sasBlob1.txt";
            const string BlobContent1 = "Blob created with an ad-hoc SAS granting write permissions on the container.";

            const string BlobName2 = "sasBlob2.txt";
            const string BlobContent2 = "Blob created with a SAS based on a stored access policy granting write permissions on the container.";

            const string BlobName3 = "sasBlob3.txt";
            const string BlobContent3 = "Blob created with an ad-hoc SAS granting create/write permissions to the blob.";

            const string BlobName4 = "sasBlob4.txt";
            const string BlobContent4 = "Blob created with a SAS based on a stored access policy granting create/write permissions to the blob.";

            string sharedAccessPolicyName = "sample-policy-" + DateTime.Now.Ticks.ToString();

            // Create the container if it does not already exist.
            await container.CreateIfNotExistsAsync();

            // Create a new shared access policy on the container.
            // The access policy may be optionally used to provide constraints for
            // shared access signatures on the container and the blob.
            await CreateSharedAccessPolicyAsync(container, sharedAccessPolicyName);

            // Generate an ad-hoc SAS URI for the container with write and list permissions.
            string adHocContainerSAS = GetContainerSasUri(container);

            // Test the SAS. The write and list operations should succeed, and 
            // the read and delete operations should fail with error code 403 (Forbidden).
            await TestContainerSASAsync(adHocContainerSAS, BlobName1, BlobContent1);

            // Generate a SAS URI for the container, using the stored access policy to set constraints on the SAS.
            string sharedPolicyContainerSAS = GetContainerSasUri(container, sharedAccessPolicyName);

            // Test the SAS. The write, read, list, and delete operations should all succeed.
            await TestContainerSASAsync(sharedPolicyContainerSAS, BlobName2, BlobContent2);

            // Generate an ad-hoc SAS URI for a blob within the container. The ad-hoc SAS has create, write, and read permissions.
            string adHocBlobSAS = GetBlobSasUri(container, BlobName3, null);
            
            // Test the SAS. The create, write, and read operations should succeed, and 
            // the delete operation should fail with error code 403 (Forbidden).
            await TestBlobSASAsync(adHocBlobSAS, BlobContent3);

            // Generate a SAS URI for a blob within the container, using the stored access policy to set constraints on the SAS.
            string sharedPolicyBlobSAS = GetBlobSasUri(container, BlobName4, sharedAccessPolicyName);
            
            // Test the SAS. The create, write, read, and delete operations should all succeed.
            await TestBlobSASAsync(sharedPolicyBlobSAS, BlobContent4);
        }
开发者ID:tamram,项目名称:storage-blob-dotnet-getting-started,代码行数:55,代码来源:Advanced.cs

示例9: InitializeAsync

 private async Task InitializeAsync()
 {
     _blobContainer = _blobClient.GetContainerReference(_containerName);
     if (await _blobContainer.CreateIfNotExistsAsync())
     {
         Logger.Info(
             "Created blob container {0} in account {1} for poison messages",
             _containerName,
             _storageAccount.BlobStorageUri);
     }
 }
开发者ID:smartpcr,项目名称:data-pipeline,代码行数:11,代码来源:AzureBlobPoisonMessageHandler.cs

示例10: BasicStorageBlockBlobOperationsWithAccountSASAsync

        /// <summary>
        /// Basic operations to work with block blobs
        /// </summary>
        /// <returns>Task<returns>
        private static async Task BasicStorageBlockBlobOperationsWithAccountSASAsync()
        {
            const string imageToUpload = "HelloWorld.png";
            string blockBlobContainerName = "demoblockblobcontainer-" + Guid.NewGuid();

            // Call GetAccountSASToken to get a sasToken based on the Storage Account Key
            string sasToken = GetAccountSASToken();
          
            // Create an AccountSAS from the SASToken
            StorageCredentials accountSAS = new StorageCredentials(sasToken);

            //Informational: Print the Account SAS Signature and Token
            Console.WriteLine();
            Console.WriteLine("Account SAS Signature: " + accountSAS.SASSignature);
            Console.WriteLine("Account SAS Token: " + accountSAS.SASToken);
            Console.WriteLine();
            
            // Create a container for organizing blobs within the storage account.
            Console.WriteLine("1. Creating Container using Account SAS");

            // Get the Container Uri  by passing the Storage Account and the container Name
            Uri ContainerUri = GetContainerSASUri(blockBlobContainerName);

            // Create a CloudBlobContainer by using the Uri and the sasToken
            CloudBlobContainer container = new CloudBlobContainer(ContainerUri, new StorageCredentials(sasToken));
            try
            {
                await container.CreateIfNotExistsAsync();
            }
            catch (StorageException)
            {
                Console.WriteLine("If you are running with the default configuration please make sure you have started the storage emulator. Press the Windows key and type Azure Storage to select and run it from the list of applications - then restart the sample.");
                Console.ReadLine();
                throw;
            }

            // To view the uploaded blob in a browser, you have two options. The first option is to use a Shared Access Signature (SAS) token to delegate 
            // access to the resource. See the documentation links at the top for more information on SAS. The second approach is to set permissions 
            // to allow public access to blobs in this container. Uncomment the line below to use this approach. Then you can view the image 
            // using: https://[InsertYourStorageAccountNameHere].blob.core.windows.net/democontainer/HelloWorld.png
            // await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

            // Upload a BlockBlob to the newly created container
            Console.WriteLine("2. Uploading BlockBlob");
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(imageToUpload);
            await blockBlob.UploadFromFileAsync(imageToUpload, FileMode.Open);

            // List all the blobs in the container 
            Console.WriteLine("3. List Blobs in Container");
            foreach (IListBlobItem blob in container.ListBlobs())
            {
                // Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory
                // Use blob.GetType() and cast to appropriate type to gain access to properties specific to each type
                Console.WriteLine("- {0} (type: {1})", blob.Uri, blob.GetType());
            }

            // Download a blob to your file system
            Console.WriteLine("4. Download Blob from {0}", blockBlob.Uri.AbsoluteUri);
            await blockBlob.DownloadToFileAsync(string.Format("./CopyOf{0}", imageToUpload), FileMode.Create);

            // Create a read-only snapshot of the blob
            Console.WriteLine("5. Create a read-only snapshot of the blob");
            CloudBlockBlob blockBlobSnapshot = await blockBlob.CreateSnapshotAsync(null, null, null, null);

            // Clean up after the demo 
            Console.WriteLine("6. Delete block Blob and all of its snapshots");
            await blockBlob.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, null, null, null);

            Console.WriteLine("7. Delete Container");
            await container.DeleteIfExistsAsync();

        }
开发者ID:BarryBurke,项目名称:storage-blob-dotnet-getting-started,代码行数:76,代码来源:Program.cs

示例11: TryCreateContainer

        private static async Task TryCreateContainer(CloudBlobContainer container, CancellationToken cancellationToken)
        {
            //
            // 2013-03-29
            //
            // HACK!
            //
            // "The magnitude of this hack compares favorably with that of the national debt" (c) Microsoft
            //

            while (true)
            {
                try
                {
                    await container.CreateIfNotExistsAsync(cancellationToken);
                    break;
                }
                catch (StorageException exception)
                {
                    RequestResult requestInformation = exception.RequestInformation;
                    var statusCode = (HttpStatusCode)requestInformation.HttpStatusCode;

                    if (statusCode != HttpStatusCode.Conflict)
                    {
                        throw;
                    }
                }
            }
        }
开发者ID:GusLab,项目名称:video-portal,代码行数:29,代码来源:FileSystem.cs

示例12: Archive

        private async Task Archive(CloudBlobContainer destinationContainer)
        {
            var cursorJObject = await GetJObject(destinationContainer, CursorBlobName);
            var cursorDateTime = cursorJObject[CursorDateTimeKey].Value<DateTime>();

            JobEventSourceLog.CursorData(cursorDateTime.ToString(DateTimeFormatSpecifier));

            JobEventSourceLog.GatheringPackagesToArchiveFromDB(PackageDatabase.DataSource, PackageDatabase.InitialCatalog);
            List<PackageRef> packages;
            using (var connection = await PackageDatabase.ConnectTo())
            {
                packages = (await connection.QueryAsync<PackageRef>(@"
			    SELECT pr.Id, p.NormalizedVersion AS Version, p.Hash, p.LastEdited, p.Published
			    FROM Packages p
			    INNER JOIN PackageRegistrations pr ON p.PackageRegistrationKey = pr.[Key]
			    WHERE Published > @cursorDateTime OR LastEdited > @cursorDateTime", new { cursorDateTime = cursorDateTime }))
                    .ToList();
            }
            JobEventSourceLog.GatheredPackagesToArchiveFromDB(packages.Count, PackageDatabase.DataSource, PackageDatabase.InitialCatalog);

            var archiveSet = packages
                .AsParallel()
                .Select(r => Tuple.Create(StorageHelpers.GetPackageBlobName(r.Id, r.Version), StorageHelpers.GetPackageBackupBlobName(r.Id, r.Version, r.Hash)))
                .ToList();

            //if (!WhatIf)
            {
                await destinationContainer.CreateIfNotExistsAsync();
            }

            if (archiveSet.Count > 0)
            {
                JobEventSourceLog.StartingArchive(archiveSet.Count);
                foreach (var archiveItem in archiveSet)
                {
                    await ArchivePackage(archiveItem.Item1, archiveItem.Item2, SourceContainer, destinationContainer);
                }

                var maxLastEdited = packages.Max(p => p.LastEdited);
                var maxPublished = packages.Max(p => p.Published);

                // Time is ever increasing after all, simply store the max of published and lastEdited as cursorDateTime
                var newCursorDateTime = maxLastEdited > maxPublished ? new DateTime(maxLastEdited.Value.Ticks, DateTimeKind.Utc) : new DateTime(maxPublished.Value.Ticks, DateTimeKind.Utc);
                var newCursorDateTimeString = newCursorDateTime.ToString(DateTimeFormatSpecifier);

                JobEventSourceLog.NewCursorData(newCursorDateTimeString);
                cursorJObject[CursorDateTimeKey] = newCursorDateTimeString;
                await SetJObject(destinationContainer, CursorBlobName, cursorJObject);
            }
        }
开发者ID:joyhui,项目名称:NuGet.Jobs,代码行数:50,代码来源:ArchivePackages.Job.cs

示例13: SetUnleasedStateAsync

 /// <summary>
 /// Puts the lease on the given container in an unleased state (either available or broken).
 /// </summary>
 /// <param name="container">The container with the lease.</param>
 internal static async Task SetUnleasedStateAsync(CloudBlobContainer container)
 {
     if (!await container.CreateIfNotExistsAsync())
     {
         OperationContext operationContext = new OperationContext();
         try
         {
             await container.BreakLeaseAsync(TimeSpan.Zero, null, null, operationContext);
         }
         catch (Exception)
         {
             if (operationContext.LastResult.ExtendedErrorInformation.ErrorCode == BlobErrorCodeStrings.LeaseAlreadyBroken ||
                 operationContext.LastResult.ExtendedErrorInformation.ErrorCode == BlobErrorCodeStrings.LeaseNotPresentWithLeaseOperation)
             {
             }
             else
             {
                 throw;
             }
         }
     }
 }
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:26,代码来源:LeaseTests.cs

示例14: WriteToBlob

        public static async Task WriteToBlob(CloudBlobContainer container, string content, string name)
        {
            await container.CreateIfNotExistsAsync();

            var blob = container.GetBlockBlobReference(name);
            Trace.TraceInformation(String.Format("Writing report to {0}", blob.Uri.AbsoluteUri));

            blob.Properties.ContentType = "application/json";
            await blob.UploadTextAsync(content);

            Trace.TraceInformation(String.Format("Wrote report to {0}", blob.Uri.AbsoluteUri));
        }
开发者ID:joyhui,项目名称:NuGet.Jobs,代码行数:12,代码来源:JobHelper.cs

示例15: CreateCloudBlobContainerAsync

 private async Task CreateCloudBlobContainerAsync()
 {
     if (_container == null && _containerName != null)
     {
         _container = _blobClient.GetContainerReference(_containerName);
         await _container.CreateIfNotExistsAsync();
     }
 }
开发者ID:Azure,项目名称:azure-iot-remote-monitoring,代码行数:8,代码来源:BlobStorageClient.cs


注:本文中的Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer.CreateIfNotExistsAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。