當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。