當前位置: 首頁>>代碼示例>>C#>>正文


C# CloudBlobContainer.ListBlobsSegmentedAsync方法代碼示例

本文整理匯總了C#中Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer.ListBlobsSegmentedAsync方法的典型用法代碼示例。如果您正苦於以下問題:C# CloudBlobContainer.ListBlobsSegmentedAsync方法的具體用法?C# CloudBlobContainer.ListBlobsSegmentedAsync怎麽用?C# CloudBlobContainer.ListBlobsSegmentedAsync使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer的用法示例。


在下文中一共展示了CloudBlobContainer.ListBlobsSegmentedAsync方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: ReadTrafficReportsAsync

        private static async Task<int> ReadTrafficReportsAsync(CloudBlobContainer container, int maxEvents)
        {
            var count = 0;

            BlobContinuationToken dirToken = null;
            do
            {
                var dirResult = await container.ListBlobsSegmentedAsync(dirToken);
                dirToken = dirResult.ContinuationToken;
                foreach (var dirItem in dirResult.Results)
                {
                    if (dirItem is CloudBlobDirectory)
                    {
                        var dir = dirItem as CloudBlobDirectory;
                        BlobContinuationToken blobToken = null;
                        var blobResult = await dir.ListBlobsSegmentedAsync(blobToken);
                        foreach (var blobItem in blobResult.Results)
                        {
                            if (blobItem is CloudBlockBlob)
                            {
                                var blob = blobItem as CloudBlockBlob;
                                var content = await blob.DownloadTextAsync();
                                count++;
                                using (var writer = new StreamWriter(string.Format("{0:D5}.xml", count)))
                                {
                                    await writer.WriteAsync(content);
                                }
                                Console.WriteLine(count);
                                if (count >= maxEvents)
                                    break;
                            }
                        }
                    }
                    if (count >= maxEvents)
                        break;
                }
            } while (dirToken != null && count < maxEvents);
            return count;
        }
開發者ID:object,項目名稱:VisualizeAllTheThings,代碼行數:39,代碼來源:Program.cs

示例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);
        }
開發者ID:pranavkm,項目名稱:AzureBlobTransfer,代碼行數:32,代碼來源:BlobTransferManager.cs

示例3: TestAccessAsync

        private static async Task TestAccessAsync(BlobContainerPublicAccessType accessType, CloudBlobContainer container, CloudBlob inputBlob)
        {
            StorageCredentials credentials = new StorageCredentials();
            container = new CloudBlobContainer(container.Uri, credentials);
            CloudPageBlob blob = new CloudPageBlob(inputBlob.Uri, credentials);
            OperationContext context = new OperationContext();
            BlobRequestOptions options = new BlobRequestOptions();

            if (accessType.Equals(BlobContainerPublicAccessType.Container))
            {
                await blob.FetchAttributesAsync();
                await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, null, options, context);
                await container.FetchAttributesAsync();
            }
            else if (accessType.Equals(BlobContainerPublicAccessType.Blob))
            {
                await blob.FetchAttributesAsync();
                await TestHelper.ExpectedExceptionAsync(
                    async () => await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, null, options, context),
                    context,
                    "List blobs while public access does not allow for listing",
                    HttpStatusCode.NotFound);
                await TestHelper.ExpectedExceptionAsync(
                    async () => await container.FetchAttributesAsync(null, options, context),
                    context,
                    "Fetch container attributes while public access does not allow",
                    HttpStatusCode.NotFound);
            }
            else
            {
                await TestHelper.ExpectedExceptionAsync(
                    async () => await blob.FetchAttributesAsync(null, options, context),
                    context,
                    "Fetch blob attributes while public access does not allow",
                    HttpStatusCode.NotFound);
                await TestHelper.ExpectedExceptionAsync(
                    async () => await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, null, options, context),
                    context,
                    "List blobs while public access does not allow for listing",
                    HttpStatusCode.NotFound);
                await TestHelper.ExpectedExceptionAsync(
                    async () => await container.FetchAttributesAsync(null, options, context),
                    context,
                    "Fetch container attributes while public access does not allow",
                    HttpStatusCode.NotFound);
            }
        }
開發者ID:Gajendra-Bahakar,項目名稱:azure-storage-net,代碼行數:47,代碼來源:CloudBlobContainerTest.cs

示例4: ListBlobsSegmentedAsync

 /// <summary>
 /// List the blobs segmented in specified containers
 /// </summary>
 /// <param name="container">A cloudblobcontainer object</param>
 /// <param name="prefix">Blob prefix</param>
 /// <param name="useFlatBlobListing">Use flat blob listing(whether treat "container/" as directory)</param>
 /// <param name="blobListingDetails">Blob listing details</param>
 /// <param name="options">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 public Task<BlobResultSegment> ListBlobsSegmentedAsync(CloudBlobContainer container, string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, int? maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
 {
     return container.ListBlobsSegmentedAsync(prefix, useFlatBlobListing, blobListingDetails, maxResults, currentToken, options, operationContext, cancellationToken);
 }
開發者ID:NordPool,項目名稱:azure-sdk-tools,代碼行數:13,代碼來源:StorageBlobManagement.cs

示例5: ListBlobsHierarchicalListingAsync

        /// <summary>
        /// Lists blobs in the specified container using a hierarchical listing, and calls this method recursively to return the contents of each 
        /// virtual directory. Reads the properties on each blob or virtual directory returned and writes them to the console window.
        /// </summary>
        /// <param name="container">A CloudBlobContainer object.</param>
        /// <param name="prefix">The blob prefix.</param>
        /// <returns>A Task object.</returns>
        private static async Task ListBlobsHierarchicalListingAsync(CloudBlobContainer container, string prefix)
        {
            // List blobs in segments.
            Console.WriteLine("List blobs (hierarchical listing):");
            Console.WriteLine();

            // Enumerate the result segment returned.
            BlobContinuationToken continuationToken = null;
            BlobResultSegment resultSegment = null;

            try
            {
                // Call ListBlobsSegmentedAsync recursively and enumerate the result segment returned, while the continuation token is non-null.
                // When the continuation token is null, the last segment has been returned and execution can exit the loop.
                // Note that blob snapshots cannot be listed in a hierarchical listing operation.
                do
                {
                    resultSegment = await container.ListBlobsSegmentedAsync(prefix, false, BlobListingDetails.Metadata, null, null, null, null);

                    foreach (var blobItem in resultSegment.Results)
                    {
                        Console.WriteLine("************************************");
                        Console.WriteLine(blobItem.Uri);

                        // A hierarchical listing returns both virtual directories and blobs.
                        // Call recursively with the virtual directory prefix to enumerate the contents of each virtual directory.
                        if (blobItem is CloudBlobDirectory)
                        {
                            PrintVirtualDirectoryProperties((CloudBlobDirectory)blobItem);
                            CloudBlobDirectory dir = blobItem as CloudBlobDirectory;
                            await ListBlobsHierarchicalListingAsync(container, dir.Prefix);
                        }
                        else
                        {
                            // Write out blob properties and metadata.
                            PrintBlobPropertiesAndMetadata((CloudBlob)blobItem);
                        }
                    }

                    Console.WriteLine();

                    // Get the continuation token, if there are additional segments of results.
                    continuationToken = resultSegment.ContinuationToken;

                } while (continuationToken != null);
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
開發者ID:tamram,項目名稱:storage-blob-dotnet-getting-started,代碼行數:60,代碼來源:Advanced.cs

示例6: ListBlobsFlatListingAsync

        /// <summary>
        /// Lists blobs in the specified container using a flat listing, with an optional segment size specified, and writes 
        /// their properties and metadata to the console window.
        /// The flat listing returns a segment containing all of the blobs matching the listing criteria.
        /// In a flat listing, blobs are not organized by virtual directory.
        /// </summary>
        /// <param name="container">A CloudBlobContainer object.</param>
        /// <param name="segmentSize">The size of the segment to return in each call to the listing operation.</param>
        /// <returns>A Task object.</returns>
        private static async Task ListBlobsFlatListingAsync(CloudBlobContainer container, int? segmentSize)
        {
            // List blobs to the console window.
            Console.WriteLine("List blobs in segments (flat listing):");
            Console.WriteLine();

            int i = 0;
            BlobContinuationToken continuationToken = null;
            BlobResultSegment resultSegment = null;

            try
            {
                // Call ListBlobsSegmentedAsync and enumerate the result segment returned, while the continuation token is non-null.
                // When the continuation token is null, the last segment has been returned and execution can exit the loop.
                do
                {
                    // This overload allows control of the segment size. You can return all remaining results by passing null for the maxResults parameter, 
                    // or by calling a different overload.
                    // Note that requesting the blob's metadata as part of the listing operation 
                    // populates the metadata, so it's not necessary to call FetchAttributes() to read the metadata.
                    resultSegment = await container.ListBlobsSegmentedAsync(string.Empty, true, BlobListingDetails.Metadata, segmentSize, continuationToken, null, null);
                    if (resultSegment.Results.Count() > 0)
                    {
                        Console.WriteLine("Page {0}:", ++i);
                    }

                    foreach (var blobItem in resultSegment.Results)
                    {
                        Console.WriteLine("************************************");
                        Console.WriteLine(blobItem.Uri);

                        // A flat listing operation returns only blobs, not virtual directories.
                        // Write out blob properties and metadata.
                        if (blobItem is CloudBlob)
                        {
                            PrintBlobPropertiesAndMetadata((CloudBlob)blobItem);
                        }
                    }

                    Console.WriteLine();

                    // Get the continuation token.
                    continuationToken = resultSegment.ContinuationToken;

                } while (continuationToken != null);
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
開發者ID:tamram,項目名稱:storage-blob-dotnet-getting-started,代碼行數:62,代碼來源:Advanced.cs

示例7: ProcessContainerAsync

        private async Task<int> ProcessContainerAsync(CloudBlobContainer container, MemoryStream[] buffers, int maxParallelSize)
        {
            Log($"Processing container `{container.Name}`", 0);

            var count = 0;
            BlobResultSegment blobListSegment = null;
            Func<bool> hasMoreSegments = () => blobListSegment?.ContinuationToken != null;

            do
            {
                blobListSegment = await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.None, null, blobListSegment?.ContinuationToken, null, null, CancellationToken.None);

                var blobs = blobListSegment.Results.OfType<CloudBlob>()
                    .Where(blob => !(BlobFilter?.Invoke(blob) == false))
                    .ToList();

                Log($"Fetched {(!hasMoreSegments() ? "final" : "partial")} listing of {blobs.Count} blobs", 0);

                if (buffers.Length > 0)
                {
                    using (var queue = new BlockingCollection<Func<MemoryStream, Task<CloudBlob>>>())
                    {
                        var sequentialBlobs = new List<CloudBlob>();

                        foreach (var blob in blobs)
                        {
                            AddBlobToQueue(blob, queue, sequentialBlobs, maxParallelSize);
                        }

                        queue.CompleteAdding();

                        Log($"Transfering {sequentialBlobs.Count} blobs sequentially and {queue.Count} blobs in parallel", 1);

                        var pool = Enumerable.Range(0, buffers.Length)
                            .Select(id => Worker(queue, buffers[id]))
                            .ToList();

                        foreach (var blob in sequentialBlobs)
                        {
                            using (await ArchiveStreamLock.LockAsync())
                            {
                                await WriteEntryAsync(blob);
                            }
                        }

                        await Task.WhenAll(pool);
                    }
                }
                else
                {
                    foreach (var blob in blobs)
                    {
                        await WriteEntryAsync(blob);
                    }
                }

                count += blobs.Count;

            } while (hasMoreSegments());

            return count;
        }
開發者ID:glueckkanja,項目名稱:azure-blob-to-archive,代碼行數:62,代碼來源:CommonCore.cs

示例8: GetLogBlobsToReplay

        private static async Task<List<CloudBlockBlob>> GetLogBlobsToReplay(CloudBlobContainer container, string containerRoot, DateTimeOffset fromDate, DateTimeOffset untilDate)
        {
            // Get the log file blobs that should be replayed
            var blobsToReplay = new List<CloudBlockBlob>();
            BlobContinuationToken continuationToken = null;
            do
            {
                var segment = await container.ListBlobsSegmentedAsync(containerRoot,
                    useFlatBlobListing: true,
                    blobListingDetails: BlobListingDetails.Metadata,
                    maxResults: null,
                    currentToken: continuationToken,
                    options: null,
                    operationContext: null);

                continuationToken = segment.ContinuationToken;

                foreach (var blob in segment.Results)
                {
                    var cloudBlockBlob = blob as CloudBlockBlob;
                    if (cloudBlockBlob != null && cloudBlockBlob.Properties.LastModified.HasValue)
                    {
                        // Check if the blob timestamp falls within our prefix range
                        var timestamp = cloudBlockBlob.Properties.LastModified.Value;
                        if (timestamp >= fromDate && timestamp <= untilDate)
                        {
                            blobsToReplay.Add(cloudBlockBlob);
                        }
                    }
                }
            } while (continuationToken != null);
            return blobsToReplay;
        }
開發者ID:NuGet,項目名稱:Entropy,代碼行數:33,代碼來源:RunCommand.cs

示例9: TestAccessTask

        private static void TestAccessTask(BlobContainerPublicAccessType accessType, CloudBlobContainer container, CloudBlob inputBlob)
        {
            StorageCredentials credentials = new StorageCredentials();
            container = new CloudBlobContainer(container.Uri, credentials);
            CloudPageBlob blob = new CloudPageBlob(inputBlob.Uri, credentials);

            if (accessType.Equals(BlobContainerPublicAccessType.Container))
            {
                blob.FetchAttributesAsync().Wait();
                BlobContinuationToken token = null;
                do
                {
                    BlobResultSegment results = container.ListBlobsSegmented(token);
                    results.Results.ToArray();
                    token = results.ContinuationToken;
                }
                while (token != null);
                container.FetchAttributesAsync().Wait();
            }
            else if (accessType.Equals(BlobContainerPublicAccessType.Blob))
            {
                blob.FetchAttributesAsync().Wait();

                TestHelper.ExpectedExceptionTask(
                    container.ListBlobsSegmentedAsync(null),
                    "List blobs while public access does not allow for listing",
                    HttpStatusCode.NotFound);
                TestHelper.ExpectedExceptionTask(
                    container.FetchAttributesAsync(),
                    "Fetch container attributes while public access does not allow",
                    HttpStatusCode.NotFound);
            }
            else
            {
                TestHelper.ExpectedExceptionTask(
                    blob.FetchAttributesAsync(),
                    "Fetch blob attributes while public access does not allow",
                    HttpStatusCode.NotFound);
                TestHelper.ExpectedExceptionTask(
                    container.ListBlobsSegmentedAsync(null),
                    "List blobs while public access does not allow for listing",
                    HttpStatusCode.NotFound);
                TestHelper.ExpectedExceptionTask(
                    container.FetchAttributesAsync(),
                    "Fetch container attributes while public access does not allow",
                    HttpStatusCode.NotFound);
            }
        }
開發者ID:Gajendra-Bahakar,項目名稱:azure-storage-net,代碼行數:48,代碼來源:CloudBlobContainerTest.cs

示例10: TransferBlobs

        private async Task<IEnumerable<IListBlobItem>> TransferBlobs(
            bool rename, 
            CloudBlobContainer fromContainer,
            CloudBlobContainer toContainer,
            CancellationToken cancellationToken)
        {
            var requestOptions = new BlobRequestOptions()
            {
                RetryPolicy = new LinearRetry(TimeSpan.FromSeconds(2), 5)
            };

            var leaseId = Guid.NewGuid().ToString();
            var leaseResult = string.Empty;
            var autoEvent = new AutoResetEvent(false);
            var waitEvent = new AutoResetEvent(false);

            var leaseTimer = new Timer(
                async s =>
                {
                    try
                    {
                        if (string.IsNullOrEmpty(leaseResult))
                        {
                            leaseResult =
                                await
                                fromContainer.AcquireLeaseAsync(
                                    TimeSpan.FromSeconds(60),
                                    leaseId,
                                    null,
                                    requestOptions,
                                    null,
                                    cancellationToken);
                            waitEvent.Set();
                        }
                        else
                        {
                            await
                                fromContainer.RenewLeaseAsync(
                                    AccessCondition.GenerateLeaseCondition(leaseId),
                                    requestOptions,
                                    null,
                                    cancellationToken);
                        }

                    }
                    catch (StorageException exception)
                    {
                        if (exception.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict)
                        {
                            this.logger.LogInformation("Staging container already has a lease.");
                        }
                    }
                },
                autoEvent,
                TimeSpan.FromSeconds(0),
                TimeSpan.FromSeconds(50));
            waitEvent.WaitOne();

            try
            {
                BlobContinuationToken token = null;
                var blobList = new List<CopySpec>();
                do
                {
                    var result = await fromContainer.ListBlobsSegmentedAsync(token, cancellationToken);
                    token = result.ContinuationToken;
                    blobList.AddRange(result.Results.OfType<CloudBlob>().Select(b => new CopySpec() {SourceBlob = b}));

                } while (token != null);

                // Copy
                var copiedBlobList = new List<CopySpec>();
                foreach (var blob in blobList)
                {
                    var srcBlobName = blob.SourceBlob.Uri.Segments[2];
                    var blobName = rename
                                       ? $"{Path.GetFileNameWithoutExtension(srcBlobName)}{Guid.NewGuid().ToString().Replace("-", "")}{Path.GetExtension(srcBlobName)}"
                                       : srcBlobName;
                    var destBlobRef = toContainer.GetBlobReference(blobName);
                    blob.DestBlob = destBlobRef;
                    try
                    {
                        await
                            destBlobRef.StartCopyAsync(
                                blob.SourceBlob.Uri,
                                AccessCondition.GenerateEmptyCondition(),
                                AccessCondition.GenerateEmptyCondition(),
                                requestOptions,
                                null,
                                cancellationToken);
                        copiedBlobList.Add(blob);
                    }
                    catch (Exception e)
                    {
                        this.logger.LogError($"Error while copying {blobName}. {e.ToString()}");
                    }
                }

                this.logger.LogInformation($"Started copying {copiedBlobList.Count} blobs");

//.........這裏部分代碼省略.........
開發者ID:Ercenk,項目名稱:toprak,代碼行數:101,代碼來源:ImageRepository.cs

示例11: ListBlobsAsync

        private async Task<IEnumerable<IListBlobItem>> ListBlobsAsync(CloudBlobContainer blobContainer, string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails = BlobListingDetails.None)
        {
            BlobContinuationToken continuationToken = null;
            List<IListBlobItem> results = new List<IListBlobItem>();
            do {
                var response = await blobContainer
                    .ListBlobsSegmentedAsync(prefix, useFlatBlobListing, blobListingDetails, null, continuationToken, null, null)
                    .ConfigureAwait(false);

                continuationToken = response.ContinuationToken;
                results.AddRange(response.Results);
            }
            while (continuationToken != null);

            return results;
        }
開發者ID:VeselovAndrey,項目名稱:FileWarehouse,代碼行數:16,代碼來源:AzureBlobStorageContainer.cs

示例12: BasicStorageBlockBlobOperationsWithAccountSASAsync

        /// <summary>
        /// Basic operations to work with block blobs
        /// </summary>
        /// <returns>A Task object.</returns>
        private static async Task BasicStorageBlockBlobOperationsWithAccountSASAsync()
        {
            const string ImageToUpload = "HelloWorld.png";
            string containerName = ContainerPrefix + Guid.NewGuid();

            // Get an account SAS token.
            string sasToken = GetAccountSASToken();

            // Use the account SAS token to create authentication credentials.
            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();

            // Get the URI for the container.
            Uri containerUri = GetContainerUri(containerName);

            // Get a reference to a container using the URI and the SAS token.
            CloudBlobContainer container = new CloudBlobContainer(containerUri, accountSAS);

            try
            {
                // Create a container for organizing blobs within the storage account.
                Console.WriteLine("1. Creating Container using Account SAS");

                await container.CreateIfNotExistsAsync();
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.ToString());
                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;
            }

            try
            {
                // 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);

                // List all the blobs in the container 
                Console.WriteLine("3. List Blobs in Container");
                BlobContinuationToken token = null;
                do
                {
                    BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(token);
                    token = resultSegment.ContinuationToken;
                    foreach (IListBlobItem blob in resultSegment.Results)
                    {
                        // Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory
                        Console.WriteLine("{0} (type: {1}", blob.Uri, blob.GetType());
                    }
                }
                while (token != null);

                // 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);

                // Delete the blob and its snapshots.
                Console.WriteLine("6. Delete block Blob and all of its snapshots");
                await blockBlob.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, null, null, null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
            finally
            {
                // Clean up after the demo.
                // Note that it is not necessary to delete all of the blobs in the container first; they will be deleted
                // with the container. 
                Console.WriteLine("7. Delete Container");
                await container.DeleteIfExistsAsync();
            }
        }
開發者ID:tamram,項目名稱:storage-blob-dotnet-getting-started,代碼行數:97,代碼來源:GettingStarted.cs

示例13: ListBlobs

        private IAsyncEnumerable<ICloudBlob> ListBlobs(CloudBlobContainer container, string prefix, BlobListingDetails options)
        {
            // Clean up the prefix if required
            prefix = prefix == null ? null : SafePath.MakeSafeFilePath(prefix);

            return AsyncEnumerableEx.Create<ICloudBlob>(async (y) =>
            {
                BlobContinuationToken token = new BlobContinuationToken();

                try
                {
                    do
                    {
                        var segment = await container.ListBlobsSegmentedAsync(prefix, true, options, null, token, null, null, y.CancellationToken).ConfigureAwait(false);
                        LeoTrace.WriteLine("Listed blob segment for prefix: " + prefix);

                        foreach (var blob in segment.Results.OfType<ICloudBlob>())
                        {
                            await y.YieldReturn(blob).ConfigureAwait(false);
                        }

                        token = segment.ContinuationToken;
                    }
                    while (token != null && !y.CancellationToken.IsCancellationRequested);
                }
                catch (StorageException e)
                {
                    if (e.RequestInformation.HttpStatusCode != 404)
                    {
                        throw e.Wrap(container.Name + "_" + (prefix ?? string.Empty) + "*");
                    }
                }
            });
        }
開發者ID:KalixHealth,項目名稱:Kalix.Leo,代碼行數:34,代碼來源:AzureStore.cs

示例14: UseContainerSAS


//.........這裏部分代碼省略.........
				CloudBlockBlob blob = container.GetBlockBlobReference("xamarinblob_" + date + ".txt");
				string data = await blob.DownloadTextAsync();

				Debug.WriteLine("Read operation succeeded for SAS " + sas);
				Debug.WriteLine("Blob contents: " + data);

				output.Text = "READ BACK FROM SERVER:" 
					+ Environment.NewLine + Environment.NewLine 
					+ data;
			}
			catch (Exception e)
			{
				Debug.WriteLine("Additional error information: " + e.Message);
				Debug.WriteLine("Read operation failed for SAS " + sas);
				Debug.WriteLine("");
			}

			try
			{
				//Delete operation: Delete a blob in the container.
				CloudBlockBlob blob = container.GetBlockBlobReference("xamarinblob_" + date + ".txt");
				//CloudBlockBlob blob = container.GetBlockBlobReference("sasblob_” + date + “.txt");
				/*
Additional error information: <?xml version="1.0" encoding="utf-16"?><!--An exception has occurred. For more information please deserialize this message via RequestResult.TranslateFromExceptionMessage.-->
<RequestResult>
  <HTTPStatusCode>404</HTTPStatusCode>
  <HttpStatusMessage>The specified blob does not exist.</HttpStatusMessage>
  <TargetLocation>Primary</TargetLocation>
  <ServiceRequestID>26b235cb-0001-0009-345d-873767000000</ServiceRequestID>
  <ContentMd5 />
  <Etag />
  <RequestDate>Tue, 05 May 2015 10:58:59 GMT</RequestDate>
  <StartTime>Tue, 05 May 2015 17:58:59 GMT</StartTime>
  <EndTime>Tue, 05 May 2015 17:58:59 GMT</EndTime>
  <Error>
    <Code>BlobNotFound</Code>
    <Message>The specified blob does not exist.
RequestId:26b235cb-0001-0009-345d-873767000000
Time:2015-05-05T17:58:59.2841607Z</Message>
  </Error>
  <ExceptionInfo>
    <Type />
    <HResult>-2147467259</HResult>
    <Message>The specified blob does not exist.</Message>
    <Source>Microsoft.WindowsAzure.Storage</Source>
    <StackTrace>  at Microsoft.WindowsAzure.Storage.Shared.Protocol.HttpResponseParsers.ProcessExpectedStatusCodeNoException[NullType] (HttpStatusCode expectedStatusCode, HttpStatusCode actualStatusCode, Microsoft.WindowsAzure.Storage.Core.NullType retVal, Microsoft.WindowsAzure.Storage.Core.Executor.StorageCommandBase`1 cmd, System.Exception ex) [0x00004] in &lt;filename unknown&gt;:0 
  at Microsoft.WindowsAzure.Storage.Shared.Protocol.HttpResponseParsers.ProcessExpectedStatusCodeNoException[NullType] (HttpStatusCode expectedStatusCode, System.Net.Http.HttpResponseMessage resp, Microsoft.WindowsAzure.Storage.Core.NullType retVal, Microsoft.WindowsAzure.Storage.Core.Executor.StorageCommandBase`1 cmd, System.Exception ex) [0x00011] in &lt;filename unknown&gt;:0 
  at Microsoft.WindowsAzure.Storage.Blob.CloudBlob+&lt;&gt;c__DisplayClass77.&lt;GetBlobImpl&gt;b__75 (Microsoft.WindowsAzure.Storage.Core.Executor.RESTCommand`1 cmd, System.Net.Http.HttpResponseMessage resp, System.Exception ex, Microsoft.WindowsAzure.Storage.OperationContext ctx) [0x00014] in &lt;filename unknown&gt;:0 
  at Microsoft.WindowsAzure.Storage.Core.Executor.Executor+&lt;ExecuteAsyncInternal&gt;d__0`1[Microsoft.WindowsAzure.Storage.Core.NullType].MoveNext () [0x0059a] in &lt;filename unknown&gt;:0 </StackTrace>
  </ExceptionInfo>
</RequestResult>
				*/

				// await blob.DeleteAsync();
				//Debug.WriteLine("Delete operation succeeded for SAS " + sas);
				//Debug.WriteLine("");
			}
			catch (Exception e)
			{
				Debug.WriteLine("Delete operation failed for SAS " + sas);
				Debug.WriteLine("Additional error information: " + e.Message);
				//Debug.WriteLine("");
			}

			try {
				output.Text += Environment.NewLine + Environment.NewLine;
				// List blobs
				// 
				//http://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs/#list-the-blobs-in-a-container
				BlobContinuationToken continuationToken = null;
				var x = await container.ListBlobsSegmentedAsync(continuationToken);
				foreach (IListBlobItem item in x.Results)
				{
					if (item.GetType() == typeof(CloudBlockBlob))
					{
						CloudBlockBlob blob = (CloudBlockBlob)item;
						Debug.WriteLine("Block blob of length {0}: {1}", blob.Properties.Length, blob.Uri);
						output.Text += blob.Uri + Environment.NewLine;
					}
					else if (item.GetType() == typeof(CloudPageBlob))
					{
						CloudPageBlob pageBlob = (CloudPageBlob)item;
						Debug.WriteLine("Page blob of length {0}: {1}", pageBlob.Properties.Length, pageBlob.Uri);
						output.Text += pageBlob.Uri + Environment.NewLine;
					}
					else if (item.GetType() == typeof(CloudBlobDirectory))
					{
						CloudBlobDirectory directory = (CloudBlobDirectory)item;
						Debug.WriteLine("Directory: {0}", directory.Uri);
						output.Text += directory.Uri + Environment.NewLine;
					}
				}
			}
			catch (Exception e)
			{
				Debug.WriteLine("Delete operation failed for SAS " + sas);
				Debug.WriteLine("Additional error information: " + e.Message);
				//Debug.WriteLine("");
			}
		}
開發者ID:King-of-Spades,項目名稱:xamarin-samples,代碼行數:101,代碼來源:Blob.xaml.cs

示例15: ListBlobsAsync

        public async Task<List<IListBlobItem>> ListBlobsAsync(CloudBlobContainer container)
        {
            BlobContinuationToken continuationToken = null;
            var results = new List<IListBlobItem>();

            do
            {
                var response = await container.ListBlobsSegmentedAsync(continuationToken);
                continuationToken = response.ContinuationToken;
                results.AddRange(response.Results);
            }
            while (continuationToken != null);

            return results;
        }
開發者ID:CatalystCode,項目名稱:bb9-oxford,代碼行數:15,代碼來源:MainPage.xaml.cs


注:本文中的Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer.ListBlobsSegmentedAsync方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。