├── .gitignore ├── LICENSE ├── README.md ├── v11 ├── Program.cs └── storage-blobs-dotnet-quickstart.csproj └── v12 ├── Program.cs └── storage-blobs-dotnet-quickstart.csproj /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | 30 | # Visual Studio Code/options directory 31 | .vscode/ 32 | 33 | # Uncomment if you have tasks that create the project's static files in wwwroot 34 | #wwwroot/ 35 | 36 | # MSTest test Results 37 | [Tt]est[Rr]esult*/ 38 | [Bb]uild[Ll]og.* 39 | 40 | # NUNIT 41 | *.VisualState.xml 42 | TestResult.xml 43 | 44 | # Build Results of an ATL Project 45 | [Dd]ebugPS/ 46 | [Rr]eleasePS/ 47 | dlldata.c 48 | 49 | # .NET Core 50 | project.lock.json 51 | project.fragment.lock.json 52 | artifacts/ 53 | **/Properties/launchSettings.json 54 | 55 | *_i.c 56 | *_p.c 57 | *_i.h 58 | *.ilk 59 | *.meta 60 | *.obj 61 | *.pch 62 | *.pdb 63 | *.pgc 64 | *.pgd 65 | *.rsp 66 | *.sbr 67 | *.tlb 68 | *.tli 69 | *.tlh 70 | *.tmp 71 | *.tmp_proj 72 | *.log 73 | *.vspscc 74 | *.vssscc 75 | .builds 76 | *.pidb 77 | *.svclog 78 | *.scc 79 | 80 | # Chutzpah Test files 81 | _Chutzpah* 82 | 83 | # Visual C++ cache files 84 | ipch/ 85 | *.aps 86 | *.ncb 87 | *.opendb 88 | *.opensdf 89 | *.sdf 90 | *.cachefile 91 | *.VC.db 92 | *.VC.VC.opendb 93 | 94 | # Visual Studio profiler 95 | *.psess 96 | *.vsp 97 | *.vspx 98 | *.sap 99 | 100 | # TFS 2012 Local Workspace 101 | $tf/ 102 | 103 | # Guidance Automation Toolkit 104 | *.gpState 105 | 106 | # ReSharper is a .NET coding add-in 107 | _ReSharper*/ 108 | *.[Rr]e[Ss]harper 109 | *.DotSettings.user 110 | 111 | # JustCode is a .NET coding add-in 112 | .JustCode 113 | 114 | # TeamCity is a build add-in 115 | _TeamCity* 116 | 117 | # DotCover is a Code Coverage Tool 118 | *.dotCover 119 | 120 | # Visual Studio code coverage results 121 | *.coverage 122 | *.coveragexml 123 | 124 | # NCrunch 125 | _NCrunch_* 126 | .*crunch*.local.xml 127 | nCrunchTemp_* 128 | 129 | # MightyMoose 130 | *.mm.* 131 | AutoTest.Net/ 132 | 133 | # Web workbench (sass) 134 | .sass-cache/ 135 | 136 | # Installshield output folder 137 | [Ee]xpress/ 138 | 139 | # DocProject is a documentation generator add-in 140 | DocProject/buildhelp/ 141 | DocProject/Help/*.HxT 142 | DocProject/Help/*.HxC 143 | DocProject/Help/*.hhc 144 | DocProject/Help/*.hhk 145 | DocProject/Help/*.hhp 146 | DocProject/Help/Html2 147 | DocProject/Help/html 148 | 149 | # Click-Once directory 150 | publish/ 151 | 152 | # Publish Web Output 153 | *.[Pp]ublish.xml 154 | *.azurePubxml 155 | # TODO: Comment the next line if you want to checkin your web deploy settings 156 | # but database connection strings (with potential passwords) will be unencrypted 157 | *.pubxml 158 | *.publishproj 159 | 160 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 161 | # checkin your Azure Web App publish settings, but sensitive information contained 162 | # in these scripts will be unencrypted 163 | PublishScripts/ 164 | 165 | # NuGet Packages 166 | *.nupkg 167 | # The packages folder can be ignored because of Package Restore 168 | **/packages/* 169 | # except build/, which is used as an MSBuild target. 170 | !**/packages/build/ 171 | # Uncomment if necessary however generally it will be regenerated when needed 172 | #!**/packages/repositories.config 173 | # NuGet v3's project.json files produces more ignorable files 174 | *.nuget.props 175 | *.nuget.targets 176 | 177 | # Microsoft Azure Build Output 178 | csx/ 179 | *.build.csdef 180 | 181 | # Microsoft Azure Emulator 182 | ecf/ 183 | rcf/ 184 | 185 | # Windows Store app package directories and files 186 | AppPackages/ 187 | BundleArtifacts/ 188 | Package.StoreAssociation.xml 189 | _pkginfo.txt 190 | 191 | # Visual Studio cache files 192 | # files ending in .cache can be ignored 193 | *.[Cc]ache 194 | # but keep track of directories ending in .cache 195 | !*.[Cc]ache/ 196 | 197 | # Others 198 | ClientBin/ 199 | ~$* 200 | *~ 201 | *.dbmdl 202 | *.dbproj.schemaview 203 | *.jfm 204 | *.pfx 205 | *.publishsettings 206 | orleans.codegen.cs 207 | 208 | # Since there are multiple workflows, uncomment next line to ignore bower_components 209 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 210 | #bower_components/ 211 | 212 | # RIA/Silverlight projects 213 | Generated_Code/ 214 | 215 | # Backup & report files from converting an old project file 216 | # to a newer Visual Studio version. Backup files are not needed, 217 | # because we have git ;-) 218 | _UpgradeReport_Files/ 219 | Backup*/ 220 | UpgradeLog*.XML 221 | UpgradeLog*.htm 222 | 223 | # SQL Server files 224 | *.mdf 225 | *.ldf 226 | *.ndf 227 | 228 | # Business Intelligence projects 229 | *.rdl.data 230 | *.bim.layout 231 | *.bim_*.settings 232 | 233 | # Microsoft Fakes 234 | FakesAssemblies/ 235 | 236 | # GhostDoc plugin setting file 237 | *.GhostDoc.xml 238 | 239 | # Node.js Tools for Visual Studio 240 | .ntvs_analysis.dat 241 | node_modules/ 242 | 243 | # Typescript v1 declaration files 244 | typings/ 245 | 246 | # Visual Studio 6 build log 247 | *.plg 248 | 249 | # Visual Studio 6 workspace options file 250 | *.opt 251 | 252 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 253 | *.vbw 254 | 255 | # Visual Studio LightSwitch build output 256 | **/*.HTMLClient/GeneratedArtifacts 257 | **/*.DesktopClient/GeneratedArtifacts 258 | **/*.DesktopClient/ModelManifest.xml 259 | **/*.Server/GeneratedArtifacts 260 | **/*.Server/ModelManifest.xml 261 | _Pvt_Extensions 262 | 263 | # Paket dependency manager 264 | .paket/paket.exe 265 | paket-files/ 266 | 267 | # FAKE - F# Make 268 | .fake/ 269 | 270 | # JetBrains Rider 271 | .idea/ 272 | *.sln.iml 273 | 274 | # CodeRush 275 | .cr/ 276 | 277 | # Python Tools for Visual Studio (PTVS) 278 | __pycache__/ 279 | *.pyc 280 | 281 | # Cake - Uncomment if you are using it 282 | # tools/** 283 | # !tools/packages.config 284 | 285 | # Telerik's JustMock configuration file 286 | *.jmconfig 287 | 288 | # BizTalk build output 289 | *.btp.cs 290 | *.btm.cs 291 | *.odx.cs 292 | *.xsd.cs 293 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | languages: 4 | - csharp 5 | products: 6 | - azure 7 | - azure-storage 8 | - dotnet 9 | description: "How to upload and download blobs from Azure Blob Storage with .NET." 10 | urlFragment: upload-download-blobs-net 11 | --- 12 | 13 | # How to upload and download blobs from Azure Blob Storage with .NET 14 | 15 | ## SDK Versions 16 | In this sample, you will find the following folders: 17 | * **v11** - references Storage Blob SDK v11 18 | * **v12** - references Storage Blob SDK v12 19 | 20 | ## Prerequisites 21 | 22 | To complete this tutorial: 23 | 24 | * Install .NET Core latest version for [Linux] or [Windows] 25 | 26 | If you don't have an Azure subscription, create a [free account] before you begin. 27 | 28 | ### Create a Storage Account using the Azure Portal 29 | 30 | Step 1 : Create a new general-purpose Storage Account to use for this tutorial. 31 | 32 | * Go to the [Azure Portal] and log in using your Azure account. 33 | * Select **New** > **Storage** > **Storage account**. 34 | * Select your Subscription. 35 | * For `Resource group`, create a new one and give it a unique name. 36 | * Enter a name for your storage Account. 37 | * Select the `Location` to use for your Storage Account. 38 | * Set `Account kind` to **StorageV2(general purpose v2)**. 39 | * Set `Performance` to **Standard**. 40 | * Set `Replication` to **Locally-redundant storage (LRS)**. 41 | * Set `Secure transfer required` to **Disabled**. 42 | * Check **Review + create** and click **Create** to create your Storage Account. 43 | 44 | Step 2 : Copy and save Connection string. 45 | 46 | After your Storage Account is created. Click on it to open it. 47 | Select **Settings** > **Access keys** > **Key1/key**, copy the associated **Connection string** to the clipboard, then paste it into a text editor for later use. 48 | 49 | ### Put the connection string in an environment variable 50 | 51 | This solution requires a connection string be stored in an environment variable securely on the machine running the sample. Follow one of the examples below depending on your operating system to create the environment variable. If using Windows close your open IDE or shell and restart it to be able to read the environment variable. 52 | 53 | Linux 54 | 55 | ```bash 56 | export AZURE_STORAGE_CONNECTIONSTRING="" 57 | ``` 58 | 59 | Windows 60 | 61 | ```cmd 62 | setx AZURE_STORAGE_CONNECTIONSTRING "" 63 | ``` 64 | 65 | At this point, you can run this application. It creates its own file to upload and download, and then cleans up after itself by deleting everything at the end. 66 | 67 | ## Run the application 68 | First, clone the repository on your machine: 69 | 70 | ```bash 71 | git clone https://github.com/Azure-Samples/azure-sdk-for-net-storage-blob-upload-download.git 72 | ``` 73 | 74 | Then, switch to the appropriate folder: 75 | ```bash 76 | cd v11 77 | ``` 78 | or 79 | ```bash 80 | cd v12 81 | ``` 82 | 83 | Finally, run the application with the `dotnet run` command. 84 | 85 | ```console 86 | dotnet run 87 | ``` 88 | 89 | ## This sample shows how to do following operations of Storage Blobs 90 | - Create a Storage Account using the Azure Portal. 91 | - Create a container. 92 | - Upload a file to block blob. 93 | - List blobs. 94 | - Download a blob to file. 95 | - Delete a blob. 96 | - Delete the container. 97 | 98 | ## More information 99 | 100 | The [Azure Storage documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples. 101 | 102 | This project has adopted the [Microsoft Open Source Code of Conduct]. 103 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments. 104 | 105 | 106 | [Linux]: https://dotnet.microsoft.com/download 107 | [Windows]: https://dotnet.microsoft.com/download 108 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F 109 | [Azure Portal]: https://portal.azure.com 110 | [Azure Storage documentation]: https://docs.microsoft.com/azure/storage/ 111 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/ 112 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/ 113 | [opencode@microsoft.com]: mailto:opencode@microsoft.com 114 | -------------------------------------------------------------------------------- /v11/Program.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | //MIT License 3 | 4 | //Copyright(c) 2017 Microsoft Corporation. All rights reserved. 5 | 6 | //Permission is hereby granted, free of charge, to any person obtaining a copy 7 | //of this software and associated documentation files (the "Software"), to deal 8 | //in the Software without restriction, including without limitation the rights 9 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | //copies of the Software, and to permit persons to whom the Software is 11 | //furnished to do so, subject to the following conditions: 12 | 13 | //The above copyright notice and this permission notice shall be included in all 14 | //copies or substantial portions of the Software. 15 | 16 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | //SOFTWARE. 23 | //------------------------------------------------------------------------------ 24 | 25 | using System; 26 | using System.IO; 27 | using System.Threading.Tasks; 28 | using Microsoft.Azure.Storage; 29 | using Microsoft.Azure.Storage.Blob; 30 | 31 | namespace Storage.Blobs.Dotnet.Quickstart.V11 32 | { 33 | /// 34 | /// Azure Storage Quickstart Sample - Demonstrate how to upload, list, download, and delete blobs. 35 | /// 36 | /// Note: This sample uses the .NET asynchronous programming model to demonstrate how to call Blob storage using the 37 | /// storage client library's asynchronous API's. When used in production applications, this approach enables you to improve the 38 | /// responsiveness of your application. Calls to Blob storage are prefixed by the await keyword. 39 | /// 40 | /// Documentation References: 41 | /// - Azure Storage client library for .NET - https://docs.microsoft.com/dotnet/api/overview/azure/storage?view=azure-dotnet 42 | /// - Asynchronous Programming with Async and Await - https://docs.microsoft.com/en-us/dotnet/csharp/async 43 | /// 44 | 45 | public static class Program 46 | { 47 | public static async Task Main() 48 | { 49 | Console.WriteLine("Azure Blob Storage - .NET quickstart sample"); 50 | Console.WriteLine(); 51 | await OperateBlobAsync(); 52 | 53 | Console.WriteLine("Press enter to exit the sample application."); 54 | Console.ReadLine(); 55 | } 56 | 57 | private static async Task OperateBlobAsync() 58 | { 59 | CloudBlobContainer cloudBlobContainer = null; 60 | string sourceFile = null; 61 | string destinationFile = null; 62 | 63 | // Retrieve the connection string for use with the application. The storage connection string is stored 64 | // in an environment variable on the machine running the application called AZURE_STORAGE_CONNECTIONSTRING. 65 | // If the environment variable is created after the application is launched in a console or with Visual 66 | // Studio, the shell needs to be closed and reloaded to take the environment variable into account. 67 | string storageConnectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTIONSTRING"); 68 | 69 | // Check whether the connection string can be parsed. 70 | if (!CloudStorageAccount.TryParse(storageConnectionString, out CloudStorageAccount storageAccount)) 71 | { 72 | Console.WriteLine( 73 | "A connection string has not been defined in the system environment variables. " + 74 | "Add a environment variable named 'storageconnectionstring' with your storage " + 75 | "connection string as a value."); 76 | 77 | return; 78 | } 79 | 80 | try 81 | { 82 | // Create the CloudBlobClient that represents the Blob storage endpoint for the storage account. 83 | CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient(); 84 | 85 | // Create a container called 'quickstartblob' and append a GUID value to it to make the name unique. 86 | cloudBlobContainer = cloudBlobClient.GetContainerReference($"quickstartblob{Guid.NewGuid().ToString()}"); 87 | await cloudBlobContainer.CreateAsync(); 88 | Console.WriteLine($"Created container '{cloudBlobContainer.Name}'"); 89 | Console.WriteLine(); 90 | 91 | // Set the permissions so the blobs are public. 92 | // This means you'll be able to download it anonymously via HTTPS using the URL displayed in the console. 93 | BlobContainerPermissions permissions = new BlobContainerPermissions 94 | { 95 | PublicAccess = BlobContainerPublicAccessType.Blob 96 | }; 97 | 98 | await cloudBlobContainer.SetPermissionsAsync(permissions); 99 | 100 | // Create a file in your local MyDocuments folder to upload to a blob. 101 | string localPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 102 | string localFileName = $"QuickStart_{Guid.NewGuid().ToString()}.txt"; 103 | sourceFile = Path.Combine(localPath, localFileName); 104 | 105 | // Write text to the file. 106 | File.WriteAllText(sourceFile, "Hello, World!"); 107 | 108 | Console.WriteLine($"Temp file = {sourceFile}"); 109 | Console.WriteLine($"Uploading to Blob storage as blob '{localFileName}'"); 110 | Console.WriteLine(); 111 | 112 | // Get a reference to the blob address, then upload the file to the blob. 113 | // Use the value of localFileName for the blob name. 114 | CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(localFileName); 115 | await cloudBlockBlob.UploadFromFileAsync(sourceFile); 116 | 117 | // List the blobs in the container. 118 | Console.WriteLine("Listing blobs in container."); 119 | BlobContinuationToken blobContinuationToken = null; 120 | 121 | do 122 | { 123 | var resultSegment = await cloudBlobContainer.ListBlobsSegmentedAsync(null, blobContinuationToken); 124 | 125 | // Get the value of the continuation token returned by the listing call. 126 | blobContinuationToken = resultSegment.ContinuationToken; 127 | foreach (IListBlobItem item in resultSegment.Results) 128 | { 129 | Console.WriteLine(item.Uri); 130 | } 131 | } 132 | 133 | while (blobContinuationToken != null); // Loop while the continuation token is not null. 134 | Console.WriteLine(); 135 | 136 | // Download the blob to a local file, using the reference created earlier. 137 | // Append the string "_DOWNLOADED" before the .txt extension so that you can see both files in MyDocuments. 138 | destinationFile = sourceFile.Replace(".txt", "_DOWNLOADED.txt"); 139 | Console.WriteLine($"Downloading blob to {destinationFile}"); 140 | Console.WriteLine(); 141 | 142 | await cloudBlockBlob.DownloadToFileAsync(destinationFile, FileMode.Create); 143 | } 144 | catch (StorageException ex) 145 | { 146 | Console.WriteLine($"Error returned from the service: {ex.Message}"); 147 | } 148 | finally 149 | { 150 | Console.WriteLine("Press enter to delete the sample files and example container."); 151 | Console.ReadLine(); 152 | 153 | // Clean up resources. This includes the container and the two temp files. 154 | Console.WriteLine("Deleting the container and any blobs it contains"); 155 | if (cloudBlobContainer != null) 156 | { 157 | await cloudBlobContainer.DeleteIfExistsAsync(); 158 | } 159 | 160 | Console.WriteLine("Deleting the local source file and local downloaded files"); 161 | Console.WriteLine(); 162 | if (File.Exists(sourceFile)) 163 | { 164 | File.Delete(sourceFile); 165 | } 166 | if (File.Exists(destinationFile)) 167 | { 168 | File.Delete(destinationFile); 169 | } 170 | } 171 | } 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /v11/storage-blobs-dotnet-quickstart.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /v12/Program.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | //MIT License 3 | 4 | //Copyright(c) 2017 Microsoft Corporation. All rights reserved. 5 | 6 | //Permission is hereby granted, free of charge, to any person obtaining a copy 7 | //of this software and associated documentation files (the "Software"), to deal 8 | //in the Software without restriction, including without limitation the rights 9 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | //copies of the Software, and to permit persons to whom the Software is 11 | //furnished to do so, subject to the following conditions: 12 | 13 | //The above copyright notice and this permission notice shall be included in all 14 | //copies or substantial portions of the Software. 15 | 16 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | //SOFTWARE. 23 | //------------------------------------------------------------------------------ 24 | 25 | using System; 26 | using System.IO; 27 | using System.Threading.Tasks; 28 | using Azure; 29 | using Azure.Storage.Blobs; 30 | using Azure.Storage.Blobs.Models; 31 | 32 | namespace Storage.Blob.Dotnet.Quickstart.V12 33 | { 34 | /// 35 | /// Azure Storage QuickStart Sample - Demonstrate how to upload, list, download, and delete blobs. 36 | /// 37 | /// Note: This sample uses the .NET asynchronous programming model to demonstrate how to call Blob storage using the 38 | /// azure storage client library's asynchronous API's. When used in production applications, this approach enables you to improve the 39 | /// responsiveness of your application. 40 | /// 41 | /// 42 | 43 | public static class Program 44 | { 45 | public static async Task Main() 46 | { 47 | Console.WriteLine("Azure Blob Storage - .NET QuickStart sample"); 48 | Console.WriteLine(); 49 | await OperateBlobAsync(); 50 | 51 | Console.WriteLine("Press enter to exit the sample application."); 52 | Console.ReadLine(); 53 | } 54 | 55 | private static async Task OperateBlobAsync() 56 | { 57 | string tempDirectory = null; 58 | string destinationPath = null; 59 | string sourcePath = null; 60 | BlobContainerClient blobContainerClient = null; 61 | 62 | // Retrieve the connection string for use with the application. The storage connection string is stored 63 | // in an environment variable on the machine running the application called AZURE_STORAGE_CONNECTIONSTRING. 64 | // If the environment variable is created after the application is launched in a console or with Visual 65 | // Studio, the shell needs to be closed and reloaded to take the environment variable into account. 66 | string storageConnectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTIONSTRING"); 67 | 68 | if (storageConnectionString == null) 69 | { 70 | Console.WriteLine("A connection string has not been defined in the system environment variables. " + 71 | "Add a environment variable named 'AZURE_STORAGE_CONNECTIONSTRING' with your storage " + 72 | "connection string as a value."); 73 | 74 | return; 75 | } 76 | 77 | try 78 | { 79 | // Create a container called 'quickstartblob' and append a GUID value to it to make the name unique. 80 | string containerName = "quickstartblob" + Guid.NewGuid().ToString(); 81 | blobContainerClient = new BlobContainerClient(storageConnectionString, containerName); 82 | await blobContainerClient.CreateAsync(); 83 | Console.WriteLine($"Created container '{blobContainerClient.Uri}'"); 84 | Console.WriteLine(); 85 | 86 | // Set the permissions so the blobs are public. 87 | await blobContainerClient.SetAccessPolicyAsync(PublicAccessType.Blob); 88 | Console.WriteLine("Setting the Blob access policy to public."); 89 | Console.WriteLine(); 90 | 91 | // Create a file in a temp directory folder to upload to a blob. 92 | tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); 93 | Directory.CreateDirectory(tempDirectory); 94 | string blobFileName = $"QuickStart_{Path.GetRandomFileName()}.txt"; 95 | sourcePath = Path.Combine(tempDirectory, blobFileName); 96 | 97 | // Write text to this file. 98 | File.WriteAllText(sourcePath, "Storage Blob Quickstart."); 99 | Console.WriteLine($"Created Temp file = {sourcePath}"); 100 | Console.WriteLine(); 101 | 102 | // Get a reference to the blob named "sample-blob", then upload the file to the blob. 103 | Console.WriteLine($"Uploading file to Blob storage as blob '{blobFileName}'"); 104 | string blobName = "sample-blob"; 105 | BlobClient blob = blobContainerClient.GetBlobClient(blobName); 106 | 107 | // Open this file and upload it to blob 108 | using (FileStream fileStream = File.OpenRead(sourcePath)) 109 | { 110 | await blob.UploadAsync(fileStream); 111 | } 112 | 113 | Console.WriteLine("Uploaded successfully."); 114 | Console.WriteLine(); 115 | 116 | // List the blobs in the container. 117 | Console.WriteLine("Listing blobs in container."); 118 | await foreach (BlobItem item in blobContainerClient.GetBlobsAsync()) 119 | { 120 | Console.WriteLine($"The blob name is '{item.Name}'"); 121 | } 122 | 123 | Console.WriteLine("Listed successfully."); 124 | Console.WriteLine(); 125 | 126 | // Append the string "_DOWNLOADED" before the .txt extension so that you can see both files in the temp directory. 127 | destinationPath = sourcePath.Replace(".txt", "_DOWNLOADED.txt"); 128 | 129 | // Download the blob to a file in same directory, using the reference created earlier. 130 | Console.WriteLine($"Downloading blob to file in the temp directory {destinationPath}"); 131 | BlobDownloadInfo blobDownload = await blob.DownloadAsync(); 132 | 133 | using (FileStream fileStream = File.OpenWrite(destinationPath)) 134 | { 135 | await blobDownload.Content.CopyToAsync(fileStream); 136 | } 137 | 138 | Console.WriteLine("Downloaded successfully."); 139 | Console.WriteLine(); 140 | } 141 | catch (RequestFailedException ex) 142 | { 143 | Console.WriteLine($"Error returned from the service: {ex.Message}"); 144 | } 145 | finally 146 | { 147 | Console.WriteLine("Press enter to delete the sample files and example container."); 148 | Console.ReadLine(); 149 | 150 | // Clean up resources. This includes the container and the two temp files. 151 | Console.WriteLine("Deleting the container and any blobs it contains."); 152 | if (blobContainerClient != null) 153 | { 154 | await blobContainerClient.DeleteAsync(); 155 | } 156 | 157 | Console.WriteLine("Deleting the local source file and local downloaded files."); 158 | Console.WriteLine(); 159 | if (File.Exists(sourcePath)) 160 | { 161 | File.Delete(sourcePath); 162 | } 163 | if (File.Exists(destinationPath)) 164 | { 165 | File.Delete(destinationPath); 166 | } 167 | if (Directory.Exists(tempDirectory)) 168 | { 169 | Directory.Delete(tempDirectory); 170 | } 171 | } 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /v12/storage-blobs-dotnet-quickstart.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | --------------------------------------------------------------------------------