async void Download_Clicked(object sender, EventArgs e) { BlobDownloadInfo downloadInfo = await blobClient.DownloadAsync(); using MemoryStream memoryStream = new MemoryStream(); await downloadInfo.Content.CopyToAsync(memoryStream); memoryStream.Position = 0; using StreamReader streamReader = new StreamReader(memoryStream); resultsLabel.Text += "Blob Contents: \n"; resultsLabel.Text += await streamReader.ReadToEndAsync(); resultsLabel.Text += "\n"; downloadButton.IsEnabled = false; deleteButton.IsEnabled = true; }
public async Task <byte[]> DownloadBlobAsync(string blobUrl) { var blobUriBuilder = new BlobUriBuilder( new Uri(blobUrl)); var blobContainerClient = _blobServiceClient .GetBlobContainerClient(blobUriBuilder.BlobContainerName); var blobClient = blobContainerClient.GetBlobClient(blobUriBuilder.BlobName); BlobDownloadInfo blobDownloadInfo = await blobClient.DownloadAsync(); using (MemoryStream ms = new MemoryStream()) { await blobDownloadInfo.Content.CopyToAsync(ms) .ConfigureAwait(false); return(ms.ToArray()); } }
private static List <Cotacao> ReadFromBlob(BlobContainerClient containerClient, string fileName) { // Get a reference to a blob BlobClient blobClient = containerClient.GetBlobClient(fileName); if (blobClient.Exists()) { BlobDownloadInfo download = blobClient.DownloadAsync().Result; using (MemoryStream downloadStream = new MemoryStream()) { download.Content.CopyToAsync(downloadStream).Wait(); downloadStream.Position = 0; return(new CsvReader(new StreamReader(downloadStream), new CsvConfiguration(CultureInfo.InvariantCulture) { TrimOptions = TrimOptions.Trim }).GetRecords <Cotacao>().ToList()); } } return(new List <Cotacao>()); }
public async Task <List <SyncedTask> > GetSavedSyncStateAsync() { List <SyncedTask> syncedTasks = new List <SyncedTask>(); BlobContainerClient blobContainerClient = new BlobContainerClient(storageConnectionString, containerName); await blobContainerClient.CreateIfNotExistsAsync(); BlobClient lastSyncStateBlobClient = blobContainerClient.GetBlobClient(blobName); if (lastSyncStateBlobClient.Exists()) { BlobDownloadInfo lastSyncBlobDownloadInfo = await lastSyncStateBlobClient.DownloadAsync(); StreamReader streamReader = new StreamReader(lastSyncBlobDownloadInfo.Content); string lastSyncTasks = streamReader.ReadToEnd(); syncedTasks = JsonSerializer.Deserialize <List <SyncedTask> >(lastSyncTasks); } return(syncedTasks); }
public async Task <List <ImpactStats> > GetAsync() { // Get a reference to a blob if (blobContainerClient == null) { // Create a BlobServiceClient object which will be used to create a container client BlobServiceClient blobServiceClient = new BlobServiceClient(AzureStorageConfig.AccountKey); blobContainerClient = blobServiceClient.GetBlobContainerClient(AzureStorageConfig.ContainerName); } var blobClient = blobContainerClient.GetBlobClient(statsFileName); BlobDownloadInfo blobDownloadInfo = await blobClient.DownloadAsync(); using (StreamReader reader = new StreamReader(blobDownloadInfo.Content)) { string text = reader.ReadToEnd(); List <ImpactStats> stats = JsonSerializer.Deserialize <List <ImpactStats> >(text); return(stats); } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "transform/{mappingFile}")] HttpRequest req, string mappingFile, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); //read input from JSON file var content = await new StreamReader(req.Body).ReadToEndAsync(); //read the transformer from a JSON file BlobServiceClient blobServiceClient = new BlobServiceClient(System.Environment.GetEnvironmentVariable("AzureWebJobsStorage")); //Create a unique name for the container string containerName = "mapping-files"; // Create the container and return a container client object BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName); // Get a reference to a blob BlobClient blobClient = containerClient.GetBlobClient($"{mappingFile}.json"); // Download the blob's contents and save it to a file BlobDownloadInfo download = await blobClient.DownloadAsync(); string mappingjson; using (MemoryStream downloadmemoryStream = new MemoryStream()) { await download.Content.CopyToAsync(downloadmemoryStream); downloadmemoryStream.Position = 0; mappingjson = await new StreamReader(downloadmemoryStream).ReadToEndAsync(); } // do the actual transformation [equal to new JsonTransformer<JsonPathSelectable>(...) for backward compatibility] string transformedString = new JsonTransformer().Transform(mappingjson, content); return(new OkObjectResult(transformedString)); }
/// <summary> /// Download Blob document /// </summary> /// <param name="sourceFile"></param> /// <returns></returns> private async Task <string> DownloadBlobAsync(string localFilePath, BlobClient blobClient) { // Download the blob to a local file // Append the string "DOWNLOAD" before the .txt extension // so you can compare the files in the data directory string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOAD.txt"); Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath); // Download the blob's contents and save it to a file BlobDownloadInfo download = await blobClient.DownloadAsync(); using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath)) { await download.Content.CopyToAsync(downloadFileStream); downloadFileStream.Close(); } return(downloadFilePath); }
public async Task <Stream> GetFile(string fileName) { Stream stream = null; if (await blobContainer.ExistsAsync()) { var blobClient = blobContainer.GetBlobClient(fileName); if (await blobClient.ExistsAsync()) { stream = new MemoryStream(); BlobDownloadInfo download = await blobClient.DownloadAsync(); await download.Content.CopyToAsync(stream); stream.Seek(0, SeekOrigin.Begin); } } return(stream); // returns a FileStreamResult }
public async Task <T> Get(string id) { id = id.Replace(".json", ""); _blobClient = _containerClient.GetBlobClient($"{id}.json"); if (await _blobClient.ExistsAsync()) { BlobDownloadInfo download = await _blobClient.DownloadAsync(); using (FileStream file = File.OpenWrite($"./{id}.json")) { await download.Content.CopyToAsync(file); } JObject obj = JObject.Parse(File.ReadAllText($"./{id}.json")); File.Delete($"./{id}.json"); return(obj.ToObject <T>()); } return(default);
/// <summary> /// Retrieves binary data of an item stored in a container /// </summary> /// <param name="id">The id of the item to retrieve</param> /// <param name="containerName">The name of the blob container where the item is located</param> /// <returns>A byte array containing the binary data of the requested item</returns> public async Task <byte[]> GetItemBinaryData(Guid id, string containerName) { var container = _service.GetBlobContainerClient(containerName); var blobClient = container.GetBlobClient(id.ToString()); if (!(await blobClient.ExistsAsync())) { return(null); } BlobDownloadInfo download = await blobClient.DownloadAsync(); byte[] bytes; using (var memoryStream = new MemoryStream()) { await download.Content.CopyToAsync(memoryStream); bytes = memoryStream.ToArray(); } return(bytes); }
public async void downloadFile(string container, string fileName) { DateTime now = DateTime.Now; string nowAsString = now.ToString("yyyy-MM-dd hh-mm-ss"); string localFilePath = Path.Combine(LOCAL_FILE_DIRECTORY, fileName); string downloadFilePath = "Download-" + nowAsString + "-" + localFilePath; BlobServiceClient blobServiceClient = new BlobServiceClient(AZURE_STORAGE_CONNECTION_STRING); BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(container); BlobClient blobClient = containerClient.GetBlobClient(fileName); BlobDownloadInfo download = await blobClient.DownloadAsync(); using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath)) { await download.Content.CopyToAsync(downloadFileStream); downloadFileStream.Close(); } }
public async Task <Result <DownloadAttachmentDto> > DownloadAttachmentAsync(long attachmentId) { var attachment = await _unitOfWork.AttachmentRepository.GetByIdAsync(attachmentId); BlobClient blobClient = new BlobClient ( _blobAccount.connectionString, attachment.ContainerName, attachment.FileName ); BlobDownloadInfo download = await blobClient.DownloadAsync(); DownloadAttachmentDto downloadedAttachment = new DownloadAttachmentDto() { DownloadInfo = download, FileName = attachment.FileName }; return(Result <DownloadAttachmentDto> .GetSuccess(downloadedAttachment)); }
public static async Task DownloadFileAsync(string @downloadPath) { try { if (!Directory.Exists(Path.GetDirectoryName(downloadPath))) { Directory.CreateDirectory(Path.GetDirectoryName(downloadPath)); } BlobDownloadInfo download = await _blobClient.DownloadAsync(); using FileStream fileStream = File.OpenWrite(downloadPath); await download.Content.CopyToAsync(fileStream); fileStream.Close(); } catch { Console.WriteLine("DownloadFail"); } }
public async Task <IActionResult> Blob() { // string connectionString = Environment.GetEnvironmentVariable("DefaultEndpointsProtocol=https;AccountName=pffile;AccountKey=U9RuCZ5BV3xORbOb//LLh8KW09jVpE41oVzoEY9ZHGZeor4oXKTIIHXd/9bDQvNzON7Eo6ka4HgVe+5HC099lg==;EndpointSuffix=core.windows.net"); // Create a BlobServiceClient object which will be used to create a container client BlobServiceClient blobServiceClient = new BlobServiceClient("DefaultEndpointsProtocol=https;AccountName=pffile;AccountKey=U9RuCZ5BV3xORbOb//LLh8KW09jVpE41oVzoEY9ZHGZeor4oXKTIIHXd/9bDQvNzON7Eo6ka4HgVe+5HC099lg==;EndpointSuffix=core.windows.net"); //Create a unique name for the container string containerName = "monthlystatement"; // Create the container and return a container client object //BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName); BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName); List <BlobInfoClass> lst = new List <BlobInfoClass>(); await foreach (BlobItem blobItem in containerClient.GetBlobsAsync()) { lst.Add(new BlobInfoClass { fileName = blobItem.Name }); } var qry = lst.FirstOrDefault(); BlobClient blobClient = containerClient.GetBlobClient(qry.fileName); // Download the blob's contents and save it to a file BlobDownloadInfo download = await blobClient.DownloadAsync(); //using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath)) //{ // await download.Content.CopyToAsync(downloadFileStream); // downloadFileStream.Close(); //} return(Ok(download.Content)); }
public static async Task Main() { //Get the connection string string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING"); //Create blob service client using conneciton string BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString); string containerName = "mrrkcontainer" + Guid.NewGuid(); //Create container using blob service client and get blob container client in return BlobContainerClient blobContainerClient = await blobServiceClient.CreateBlobContainerAsync(containerName); System.Console.WriteLine(blobContainerClient.ToString()); System.Console.WriteLine("Press to continue"); // Console.ReadLine(); string localPath = "./data"; string fileName = "mrrkfile" + Guid.NewGuid() + ".txt"; string localFilePath = Path.Combine(localPath + fileName); await File.WriteAllTextAsync(localFilePath, "Hello World"); var blobClient = blobContainerClient.GetBlobClient(fileName); System.Console.WriteLine("Uploading {0} to blob storage as {1} ", fileName, blobClient.Uri); using (var fileStreamForupload = File.OpenRead(localFilePath)) { await blobClient.UploadAsync(fileStreamForupload, true); } var downloadFilePath = localFilePath.Replace(".txt", ".download.txt"); BlobDownloadInfo download = await blobClient.DownloadAsync(); using (FileStream fileStreamForWriting = File.OpenWrite(downloadFilePath)) { await download.Content.CopyToAsync(fileStreamForWriting); } System.Console.WriteLine("Press any key to delete the container "); Console.ReadLine(); await blobContainerClient.DeleteAsync(); File.Delete(localFilePath); File.Delete(downloadFilePath); System.Console.WriteLine("Done"); }
public async Task DownloadAsync() { // Create a temporary Lorem Ipsum file on disk that we can upload string originalPath = CreateTempFile(SampleFileContent); // Get a temporary path on disk where we can download the file string downloadPath = CreateTempPath(); // Get a connection string to our Azure Storage account. string connectionString = ConnectionString; // Get a reference to a container named "sample-container" and then create it BlobContainerClient container = new BlobContainerClient(connectionString, Randomize("sample-container")); await container.CreateAsync(); try { // Get a reference to a blob named "sample-file" BlobClient blob = container.GetBlobClient(Randomize("sample-file")); // First upload something the blob so we have something to download await blob.UploadAsync(File.OpenRead(originalPath)); // Download the blob's contents and save it to a file BlobDownloadInfo download = await blob.DownloadAsync(); using (FileStream file = File.OpenWrite(downloadPath)) { await download.Content.CopyToAsync(file); } // Verify the contents Assert.AreEqual(SampleFileContent, File.ReadAllText(downloadPath)); } finally { // Clean up after the test when we're finished await container.DeleteAsync(); } }
private async Task <object> InnerReadBlobAsync(BlobClient blobReference, CancellationToken cancellationToken) { var i = 0; while (true) { try { using (BlobDownloadInfo download = await blobReference.DownloadAsync(cancellationToken).ConfigureAwait(false)) { using (var jsonReader = new JsonTextReader(new StreamReader(download.Content))) { var obj = _jsonSerializer.Deserialize(jsonReader); if (obj is IStoreItem storeItem) { storeItem.ETag = (await blobReference.GetPropertiesAsync(cancellationToken: cancellationToken).ConfigureAwait(false))?.Value?.ETag.ToString(); } return(obj); } } } catch (RequestFailedException ex) when((HttpStatusCode)ex.Status == HttpStatusCode.PreconditionFailed) { // additional retry logic, even though this is a read operation blob storage can return 412 if there is contention if (i++ < 8) { await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken).ConfigureAwait(false); continue; } else { throw; } } } }
public static async Task GetIoTData(string pathname) { string connectionString = AzureConnection.storageConnectionString; BlobContainerClient container = new BlobContainerClient(connectionString, "iotoutput"); container.CreateIfNotExistsAsync().Wait(); if (existsFile(container)) { var fileName = container.GetBlobs().OrderByDescending(m => m.Properties.LastModified).ToList().First().Name; BlobClient blobClient = container.GetBlobClient(fileName); BlobDownloadInfo download = await blobClient.DownloadAsync(); string downloadFilePath = string.Format(Application.temporaryCachePath + "/{0}", pathname + ".csv"); File.Delete(downloadFilePath); using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath)) { await download.Content.CopyToAsync(downloadFileStream); downloadFileStream.Close(); } } else { try { GameObject stateMessage = GameObject.Find("State text"); stateMessage.GetComponent <TextMeshProUGUI>().text = "No files found"; } catch (NullReferenceException) { } } }
public override byte ReadByte() { if (_blobLength == 0) { return(0); } if (_currPage == null || _prevPageOffset != GetCurrentPageOffset()) { // download and cache the current page. _currPage ??= new byte[512]; var range = new HttpRange(_currPageOffset, 512); BlobDownloadInfo download = _pageBlobClient.Download(range); download.Content.Read(_currPage, 0, 512); } var pos = _currPagePosition - _currPageOffset; var b = _currPage[pos]; _currPagePosition += 1; return(b); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", Route = "translation/{lang}/{resourceGroup}_{resource}")] HttpRequest req, string lang, string resourceGroup, string resource, ILogger log) { log.LogInformation($"C# HTTP trigger function processed a request. Requested language: {lang}, resource group: {resourceGroup}, resource: {resource}"); try { // Load configurations string storageConnString = Environment.GetEnvironmentVariable("AzureWebJobsStorage"); string langFilesContainerName = Environment.GetEnvironmentVariable("LanaguageFilesContainer"); // Get the blob reader and get the required translation file. TranslatorFactory translatorFactory = new TranslatorFactory(); IBlobReader blobReader = translatorFactory.GetBlobReader(); BlobDownloadInfo languageFile = await blobReader.ReadBlobAsync(storageConnString, langFilesContainerName, $"{lang}.xml"); if (languageFile != null) { // Read the requested resource from the translation file ITranslationReader translationReader = translatorFactory.GetTranslationReader(); string result = translationReader.ReadResource(lang, resourceGroup, resource, log, languageFile.Content); if (!string.IsNullOrEmpty(result)) { return(new OkObjectResult(result)); } return(new BadRequestObjectResult("Requested resource does not exist")); } log.LogInformation("Translations don't exist for the language"); return(new BadRequestObjectResult("Translations don't exist for the language")); } catch (Exception e) { log.LogError(e, "Unexpected error"); return(new BadRequestResult()); } }
public async Task <IActionResult> DownloadFile([FromRoute] int fileID) { try { // Find Project var blobFile = await _dbContext.BlobFiles.FindAsync(fileID); if (blobFile == null) { return(NotFound()); } BlobDownloadInfo data = await _blobService.GetBlobAsync(blobFile); return(File(data.Content, data.ContentType, blobFile.Name + blobFile.Extension)); } catch (Exception e) { // Return Bad Request If There Is Any Error return(BadRequest(e)); } }
private static async Task <(byte[], string)> DownloadFileAsync(BlobContainerClient containerClient, string blobName) { BlobClient blobClient = containerClient.GetBlobClient(blobName); BlobDownloadInfo download = await blobClient.DownloadAsync(); if (download.Content == Stream.Null) { throw new ApplicationException("No file found on server"); } byte[] result; using (MemoryStream downloadFileStream = new MemoryStream()) { await download.Content.CopyToAsync(downloadFileStream); result = downloadFileStream.ToArray(); downloadFileStream.Close(); } return(result, download.ContentType); }
public async Task <string?> Get(IWorkContext context, string path) { context.Verify(nameof(context)).IsNotNull(); path.Verify(nameof(path)).IsNotEmpty(); BlobClient blobClient = _containerClient.GetBlobClient(path); BlobDownloadInfo download = await blobClient.DownloadAsync(); using (MemoryStream memory = new MemoryStream()) using (var writer = new StreamWriter(memory)) { await download.Content.CopyToAsync(memory); writer.Flush(); memory.Position = 0; using (StreamReader reader = new StreamReader(memory)) { return(reader.ReadToEnd()); } } }
public async Task <FileInfo> DownloadConvertedAsset(Guid jobId) { Guid accountId = new Guid(TestEnvironment.AccountId); string accountDomain = TestEnvironment.AccountDomain; AzureKeyCredential credential = new AzureKeyCredential(TestEnvironment.AccountKey); ObjectAnchorsConversionClient client = new ObjectAnchorsConversionClient(accountId, accountDomain, credential); AssetConversionOperation operation = new AssetConversionOperation(jobId, client); string localFileDownloadPath = modelDownloadLocalFilePath; BlobClient downloadBlobClient = new BlobClient(operation.Value.OutputModelUri, new BlobClientOptions()); BlobDownloadInfo downloadInfo = await downloadBlobClient.DownloadAsync(); using (FileStream file = File.OpenWrite(localFileDownloadPath)) { await downloadInfo.Content.CopyToAsync(file); return(new FileInfo(localFileDownloadPath)); } }
public async Task <BlobDownloadInfo> GetBlobAsync(string containerName, string blobName) { containerName.ShouldNotBeNullOrWhitespace(nameof(containerName)); blobName.ShouldNotBeNullOrWhitespace(nameof(blobName)); BlobDownloadInfo blob = null; var blobServiceClient = new BlobServiceClient(_options.Value.AzureStorageConnectionString); var containerClient = blobServiceClient.GetBlobContainerClient(containerName); if (await containerClient.ExistsAsync().ConfigureAwait(false)) { var blobClient = containerClient.GetBlobClient(blobName); if (await blobClient.ExistsAsync().ConfigureAwait(false)) { blob = await blobClient.DownloadAsync().ConfigureAwait(false); } } return(blob); }
public async Task DownloadBlobDirectStream() { string data = "hello world"; // setup blob string containerName = Randomize("sample-container"); string blobName = Randomize("sample-file"); var containerClient = new BlobContainerClient(ConnectionString, containerName); try { containerClient.Create(); containerClient.GetBlobClient(blobName).Upload(new MemoryStream(Encoding.UTF8.GetBytes(data))); // tools to consume stream while looking good in the sample snippet string downloadedData = null; async Task MyConsumeStreamFunc(Stream stream) { downloadedData = await new StreamReader(stream).ReadToEndAsync(); } #region Snippet:SampleSnippetsBlobMigration_DownloadBlobDirectStream BlobClient blobClient = containerClient.GetBlobClient(blobName); BlobDownloadInfo downloadResponse = await blobClient.DownloadAsync(); using (Stream downloadStream = downloadResponse.Content) { await MyConsumeStreamFunc(downloadStream); } #endregion Assert.AreEqual(data, downloadedData); } finally { await containerClient.DeleteIfExistsAsync(); } }
public async Task DownloadAllBlobsInContainer() { var containerClients = _client.GetBlobContainers(); foreach (BlobContainerItem container in containerClients) { var containerClient = _client.GetBlobContainerClient(container.Name); Console.WriteLine(container.Name); await foreach (var blobItem in containerClient.GetBlobsAsync()) { Console.WriteLine(blobItem.Name); Console.WriteLine($"Downloading blob to: {_downloadPath}"); BlobClient blobClient = containerClient.GetBlobClient(blobItem.Name); BlobDownloadInfo blobDownloadInfo = blobClient.Download(); // Access blob properties BlobProperties props = blobClient.GetProperties(); Console.WriteLine("Properties"); Console.WriteLine($"Access tier: {props.AccessTier}"); Console.WriteLine($"Blob expires on: {props.ExpiresOn.UtcDateTime.ToLongDateString()}"); // Access blob metadata Console.WriteLine("Metadata keyvalue pair"); foreach (var metadata in props.Metadata) { Console.WriteLine($"{metadata.Key}: {metadata.Value}"); } using (FileStream fs = File.OpenWrite($"{_downloadPath}\\{blobItem.Name}")) { blobDownloadInfo.Content.CopyTo(fs); fs.Close(); } } } }
public async Task <ActionResult> DownloadFile(string fileName, string Path) { try { string downloadfile = HelperMethod.GetFileNamePath(fileName, Path); var _blobClient = _blobContainerClient.GetBlobClient(fileName); // Download the blob's contents and save it to a file BlobDownloadInfo download = await _blobClient.DownloadAsync(); using FileStream downloadFileStream = System.IO.File.OpenWrite(downloadfile); await download.Content.CopyToAsync(downloadFileStream); downloadFileStream.Close(); return(StatusCode(200, $"{fileName} downloaded successfully at {Path}")); } catch (Exception ex) { return(StatusCode(500, ex.Message)); } }
public override void ReadBytes(byte[] b, int offset, int len) { // say offset = 200; int excess = 0; while (len > 0) { if (len > BufferSize) // e.g. for len 800 { excess = len % BufferSize; // 288 len -= excess; // 512 } BlobDownloadInfo download = _pageBlobClient.Download(new HttpRange(_currPagePosition, len)); int read = download.Content.Read(b, offset, len); // 512 bytes downloaded _currPagePosition += len; // advance page blob position. SetCurrentPageOffset(); len = excess; // new len = 288 offset += read; // new offset = 200 + 512 } }
internal static async Task <string> WriteFileToLocalStorage(BlobServiceClient storageSvcClient, string sourceContainerName, string filename) { try { var localPath = Path.Combine(Directory.GetCurrentDirectory(), filename); var container = storageSvcClient.GetBlobContainerClient(sourceContainerName); var blob = container.GetBlobClient(filename); log.LogInformation($"Downloading {blob.Uri} to local working file {localPath}"); BlobDownloadInfo blobDownload = await blob.DownloadAsync(); using (FileStream fileStream = File.OpenWrite(localPath)) { await blobDownload.Content.CopyToAsync(fileStream); } return(localPath); } catch (Exception ex) { log.LogError($"Unable to save file {filename} to local storage: {ex.Message}"); return(string.Empty); } }