public async Task <string> GetLogContent() { try { CloudFileDirectory root = Share.GetRootDirectoryReference(); File = root.GetFileReference($"log_{DateTime.Now.ToString("dd_MM_yyyy")}.log"); string content; if (!await File.ExistsAsync()) { content = ""; } else { using (var memoryStream = new MemoryStream()) { await File.DownloadToStreamAsync(memoryStream); content = Encoding.UTF8.GetString(memoryStream.ToArray()); } } return(content); } catch (Exception ex) { throw ex; } }
/// <inheritdoc /> public void CopyFile(string sourceFileName, string[] sourceParentDirectories, string targetFileName, string[] targetParentDirectories, bool overwriteIfExists = false) { #region validation if (string.IsNullOrEmpty(sourceFileName)) { throw new ArgumentNullException(nameof(sourceFileName)); } if (string.IsNullOrEmpty(targetFileName)) { throw new ArgumentNullException(nameof(targetFileName)); } #endregion CloudFileDirectory sourceDirectory = CloudFileShare.GetDirectoryReference(path: sourceParentDirectories); CloudFileDirectory targetDirectory = CloudFileShare.GetDirectoryReference(path: targetParentDirectories); CloudFile sourceFile = sourceDirectory.GetFileReference(sourceFileName); CloudFile targetFile = targetDirectory.GetFileReference(targetFileName); if (overwriteIfExists) { TaskUtilities.ExecuteSync(targetFile.DeleteIfExistsAsync()); } if (!TaskUtilities.ExecuteSync(targetFile.ExistsAsync())) { TaskUtilities.ExecuteSync(targetFile.StartCopyAsync(sourceFile)); } }
public async Task Test_30_SAS() { var share = _client.GetShareReference("photos"); var rootDirectory = share.GetRootDirectoryReference(); var file = rootDirectory.GetFileReference("Joins.png"); // Get a Shared Access Signature for that file that is for read access for that file var sasToken = file.GetSharedAccessSignature( new SharedAccessFilePolicy { Permissions = SharedAccessFilePermissions.Read, SharedAccessExpiryTime = new DateTimeOffset(DateTime.UtcNow.AddMinutes(5)) } ); var sasCreds = new StorageCredentials(sasToken); var sasCloudFile = new CloudFile( new Uri("https://omazurestoragecli.file.core.windows.net/photos/Joins.png"), sasCreds ); bool fileExists = await sasCloudFile.ExistsAsync(); Check.That(fileExists).IsTrue(); using (var ms = new MemoryStream()) { await sasCloudFile.DownloadToStreamAsync(ms); Check.That(ms.Length).IsStrictlyGreaterThan(0); } }
/// <summary> /// DownloadFileAsync which using shareNname, sourcefoldername, file namd and filedownload path /// </summary> /// <param name="shareName"></param> /// <param name="sourceFolder"></param> /// <param name="fileName"></param> /// <param name="fileDownloadPath"></param> /// <returns></returns> public async Task DownloadFileAsync(string shareName, string sourceFolder, string fileName, string fileDownloadPath) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(settings.ConnectionString); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare fileShare = fileClient.GetShareReference(shareName); if (await fileShare.ExistsAsync()) { CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference(); if (await rootDirectory.ExistsAsync()) { CloudFileDirectory customDirectory = rootDirectory.GetDirectoryReference(sourceFolder); if (await customDirectory.ExistsAsync()) { CloudFile cloudfile = customDirectory.GetFileReference(fileName); if (await cloudfile.ExistsAsync()) { await cloudfile.DownloadToFileAsync(fileDownloadPath, System.IO.FileMode.OpenOrCreate); } } } } }
/// <summary> /// DownloadFileAsyncStream /// </summary> /// <param name="shareName"></param> /// <param name="sourceFolder"></param> /// <param name="fileName"></param> /// <returns></returns> public async Task <MemoryStream> DownloadFileAsyncStream(string shareName, string sourceFolder, string fileName) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(settings.ConnectionString); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare fileShare = fileClient.GetShareReference(shareName); if (await fileShare.ExistsAsync()) { CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference(); if (await rootDirectory.ExistsAsync()) { CloudFileDirectory customDirectory = rootDirectory.GetDirectoryReference(sourceFolder); if (await customDirectory.ExistsAsync()) { CloudFile cloudfile = customDirectory.GetFileReference(fileName); if (await cloudfile.ExistsAsync()) { using (var stream = new MemoryStream()) { await cloudfile.DownloadToStreamAsync(stream); return(stream); } } } } } return(null); }
/// <summary> /// Create the references necessary to log into Azure /// </summary> private async void CreateCloudIdentityAsync() { // Retrieve storage account information from connection string storageAccount = CloudStorageAccount.Parse(storageConnectionString); // Create a file client for interacting with the file service. fileClient = storageAccount.CreateCloudFileClient(); // Create a share for organizing files and directories within the storage account. share = fileClient.GetShareReference(fileShare); await share.CreateIfNotExistsAsync(); // Get a reference to the root directory of the share. CloudFileDirectory root = share.GetRootDirectoryReference(); // Create a directory under the root directory dir = root.GetDirectoryReference(storageDirectory); await dir.CreateIfNotExistsAsync(); //Check if the there is a stored text file containing the list shapeIndexCloudFile = dir.GetFileReference("TextShapeFile"); if (!await shapeIndexCloudFile.ExistsAsync()) { // File not found, enable gaze for shapes creation Gaze.instance.enableGaze = true; azureStatusText.text = "No Shape\nFile!"; } else { // The file has been found, disable gaze and get the list from the file Gaze.instance.enableGaze = false; azureStatusText.text = "Shape File\nFound!"; await ReplicateListFromAzureAsync(); } }
public override async Task <FileData> GetAsync(FileGetOptions fileGetOptions) { FileData file = new FileData(); CloudStorageAccount storageAccount = Authorized(fileGetOptions); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare fileshare = fileClient.GetShareReference(fileGetOptions.Folder); if (fileshare.ExistsAsync().Result) { CloudFileDirectory cFileDir = fileshare.GetRootDirectoryReference(); CloudFile cFile = cFileDir.GetFileReference(fileGetOptions.Key); if (cFile.ExistsAsync().Result) { file.Stream.Position = 0; await cFile.DownloadToStreamAsync(file.Stream); } } file.Type = "Azure File Storage"; return(file); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log) { dynamic data = JsonConvert.DeserializeObject(await new StreamReader(req.Body).ReadToEndAsync()); string inputFileName = data.fileName; log.LogInformation("Request received to extract file {inputFileName}.", inputFileName); CloudFileClient fileClient = LoadFileClient(); CloudFileShare sourceFileShare = fileClient.GetShareReference(Environment.GetEnvironmentVariable("SourceFileShareName")); CloudFileDirectory rootDirectory = sourceFileShare.GetRootDirectoryReference(); CloudFile sourceFile = rootDirectory.GetFileReference(inputFileName); if (!await sourceFile.ExistsAsync()) { return(new NotFoundObjectResult("Source file does not exist.")); } CloudFileDirectory destinationDirectory = await LoadDestinationDirectory(sourceFile, rootDirectory); dynamic returnObject = await ExtractionManager.ExtractAndUploadFiles(log, sourceFile, destinationDirectory); return(new OkObjectResult(returnObject)); }
public async Task DownloadStream(Stream stream, string name) { CloudFile originalFile = baseDir.GetFileReference(name); if (!await originalFile.ExistsAsync()) { return; } await originalFile.DownloadToStreamAsync(stream); }
public async Task <Stream> FindAsync(Entry entry, Image image, ImageType type) { CloudFile imageFile = await GetFileAsync(entry, image, type); if (await imageFile.ExistsAsync()) { return(await imageFile.OpenReadAsync()); } return(null); }
protected override async Task <bool> ExistsAsync(string fullPath, CancellationToken cancellationToken) { CloudFile file = await GetFileReferenceAsync(fullPath, false, cancellationToken).ConfigureAwait(false); if (file == null) { return(false); } return(await file.ExistsAsync().ConfigureAwait(false)); }
public async Task <bool> UpdateFile(string fileName, string name) { CloudFile originalFile = baseDir.GetFileReference(name); if (!await originalFile.ExistsAsync()) { return(false); } await originalFile.UploadFromFileAsync(fileName); return(true); }
private IEnumerable <TransferEntry> EnumerateLocationNonRecursive(string fileName, CancellationToken cancellationToken) { Utils.CheckCancellation(cancellationToken); if (fileName == null || fileName.Length == 0 || fileName.Length > MaxDirectoryAndFileNameLength) { // Empty string or exceed-limit-length file name surely match no files. yield break; } if (this.listContinuationToken != null) { int compareResult = string.Compare(fileName, this.listContinuationToken.FilePath, StringComparison.Ordinal); if (compareResult <= 0) { yield break; } } CloudFile cloudFile = this.location.FileDirectory.GetFileReference(fileName); FileRequestOptions requestOptions = Transfer_RequestOptions.DefaultFileRequestOptions; ErrorEntry errorEntry = null; bool exist = false; try { exist = cloudFile.ExistsAsync(requestOptions, null, cancellationToken).Result; } catch (Exception ex) { string errorMessage = string.Format( CultureInfo.CurrentCulture, Resources.FailedToEnumerateDirectory, this.location.FileDirectory.SnapshotQualifiedUri.AbsoluteUri, fileName); // Use TransferException to be more specific about the cloud file URI. TransferException exception = new TransferException(TransferErrorCode.FailToEnumerateDirectory, errorMessage, ex); errorEntry = new ErrorEntry(exception); } if (null != errorEntry) { yield return(errorEntry); } else if (exist) { yield return(new AzureFileEntry(fileName, cloudFile, new AzureFileListContinuationToken(fileName))); } }
public async Task <Stream> GetDownloadStreamAsync(string nomeArquivo) { await CheckFileShare(); CloudFile file = (await GetBaseDir()).GetFileReference(nomeArquivo); if (!(await file.ExistsAsync())) { throw new ArgumentException($"Arquivo {nomeArquivo} não encontrado"); } return(await file.OpenReadAsync()); }
public async Task <string> GetFhirBundleAndDelete(string fileName) { string ret = ""; CloudFile source = PatientDirectory.GetFileReference(fileName); if (await source.ExistsAsync()) { ret = await source.DownloadTextAsync(); await source.DeleteAsync(); } return(ret); }
public void CopyFileTest(string sourceFileName, string[] sourceParentFolders, string targetFileName, string[] targetParentFolders, bool overwriteIfExists = false) { // Arrange CloudFileDirectory targetDirectory = _cloudFileShare.GetDirectoryReference(path: targetParentFolders); // Act _fileContainer.CopyFile(sourceFileName, sourceParentFolders, targetFileName, targetParentFolders, overwriteIfExists); CloudFile fileReference = targetDirectory.GetFileReference(targetFileName); bool result = TaskUtilities.ExecuteSync(fileReference.ExistsAsync()); // Assert Assert.IsTrue(result); }
public void CreateFileWithByteArrayTest(string fileName, byte[] fileContent, string[] path) { // Arrange CloudFileDirectory targetDirectory = _cloudFileShare.GetDirectoryReference(path: path); // Act _fileContainer.CreateFile(fileName, fileContent, path); CloudFile fileReference = targetDirectory.GetFileReference(fileName); bool result = TaskUtilities.ExecuteSync(fileReference.ExistsAsync()); // Assert Assert.IsTrue(result); }
public void DeleteFileTest(string fileName, string[] path) { // Arrange CloudFileDirectory targetDirectory = _cloudFileShare.GetDirectoryReference(path: path); // Act _fileContainer.DeleteFile(fileName, path); CloudFile fileReference = targetDirectory.GetFileReference(fileName); bool result = TaskUtilities.ExecuteSync(fileReference.ExistsAsync()); // Assert Assert.IsFalse(result); }
public async Task <MemoryStream> GetFile(string clientId, string filename) { this.Init(); CloudFileShare share = this._cloudFileClient.GetShareReference(this._fileStorageOptions.ShareName); bool shareExist = await share.ExistsAsync(); if (shareExist != true) { throw new ServiceOperationException("No such share."); } //Get root directory CloudFileDirectory rootDirectory = share.GetRootDirectoryReference(); bool rootDirExist = await rootDirectory.ExistsAsync(); if (rootDirExist != true) { throw new ServiceOperationException("No such root dir."); } //Get clients directory CloudFileDirectory clientsFolder = rootDirectory.GetDirectoryReference(clientId); bool clientsDirExist = await clientsFolder.ExistsAsync(); if (clientsDirExist != true) { throw new ServiceOperationException("No such client dir."); } //Get reference to file //If file already exists it will be overwritten CloudFile file = clientsFolder.GetFileReference(filename); bool fileExists = await file.ExistsAsync(); if (fileExists != true) { throw new ServiceOperationException("No such file"); } MemoryStream ms = new MemoryStream(); await file.DownloadToStreamAsync(ms); ms.Position = 0; return(ms); }
public void InsertEntity(FileLogMessagecs logMessage) { try { // Get a reference to the root directory for the share. CloudFileDirectory rootDir = this.share.GetRootDirectoryReference(); // Get a reference to the directory we created previously. CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("Logs"); sampleDir.CreateIfNotExistsAsync(); var fileName = DateTime.Today.ToString("ddMMyyyy"); CloudFile file = sampleDir.GetFileReference(fileName + ".txt"); if (!file.ExistsAsync().Result) { file.UploadTextAsync( string.Format("{0} - {1}{2}", logMessage.Timestamp.ToString(), logMessage.Text, Environment.NewLine)); } else { using (MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(string.Format("{0} - {1}{2}", logMessage.Timestamp.ToString(), logMessage.Text, Environment.NewLine)))) { var startOffset = file.Properties.Length; file.WriteRangeAsync(ms, startOffset, null).Wait(); } } //if (!file.ExistsAsync().Result) //{ // file.CreateAsync(7).Wait(); //} //using (MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(string.Format("{0} - {1}{2}", logMessage.Timestamp.ToString(), logMessage.Text, Environment.NewLine)))) //{ // var startOffset = file.Properties.Length; // file.WriteRangeAsync(ms, startOffset, null); //} } catch (Exception ExceptionObj) { throw ExceptionObj; } }
public async Task <IDriveItem> GetItemByFileIdAysnc(string path) { var file = new CloudFile(new Uri(path), fileShare.ServiceClient.Credentials); if (await file.ExistsAsync()) { await file.FetchAttributesAsync(); return(new DriveFile(file.Uri.ToString(), file.Name, Root, DriveType, file.Properties.Length)); } var dir = new CloudFileDirectory(new Uri(path), fileShare.ServiceClient.Credentials); if (await dir.ExistsAsync()) { return(new DriveFolder(dir.Uri.ToString(), dir.Name, Root, DriveType)); } return(null); //var split = new Queue<string>(path.Split(new[] { Delimiter }, StringSplitOptions.RemoveEmptyEntries)); //var folder = this._fileShare.GetRootDirectoryReference(); //while (split.Count > 1) //{ // var current = split.Dequeue(); // folder = folder.GetDirectoryReference(current); //} //var name = split.Dequeue(); //var file = folder.GetFileReference(name); //if (file.Exists()) //{ // await file.FetchAttributesAsync(); // return new DriveFile(file.Uri.ToString(), file.Name, Root, DriveType, file.Properties.Length); //} //var dir = folder.GetDirectoryReference(name); //if (dir.Exists()) //{ // return new DriveFolder(dir.Uri.ToString(), dir.Name, Root, DriveType); //} //return null; }
public async Task <bool> RenameFile(string originalName, string newName, bool overrideIfExists = false) { CloudFile originalFile = baseDir.GetFileReference(originalName); if (!await originalFile.ExistsAsync()) { return(false); } var newFile = baseDir.GetFileReference(newName); if (await newFile.ExistsAsync() && !overrideIfExists) { return(false); } await newFile.StartCopyAsync(originalFile); await originalFile.DeleteIfExistsAsync(); return(true); }
public async Task <bool> AddFile(string fileName, string name, bool overrideIfExists = false) { CloudFile originalFile = baseDir.GetFileReference(name); if (await originalFile.ExistsAsync() && !overrideIfExists) { return(false); } try { using (var str = File.OpenRead(fileName)) { await originalFile.UploadFromStreamAsync(str); } return(true); } catch (Exception) { return(false); } }
public async Task <bool> AddFile(Stream stream, string name, bool overrideIfExists = false) { CloudFile file = baseDir.GetFileReference(name); if (await file.ExistsAsync() && !overrideIfExists) { return(false); } await CreateFoldersFromPath(name); try { await file.UploadFromStreamAsync(stream); } catch { return(false); } return(true); }
private async Task OnBinaryMessageReceived(WebSocketHandler handler, string conversationId, string watermark, int musicId) { string fileName = musicId.ToString() + ".wav"; Uri uri = new Uri(baseURL + '/' + fileName); CloudFile file = new CloudFile(uri, storageCredentials); bool ifExist = await file.ExistsAsync(); if (!ifExist) { if (musicId == 1) { Trace.TraceError("No music!!"); return; } else { musicId = 1; Count.count = 1; fileName = musicId.ToString() + ".wav"; uri = new Uri(baseURL + fileName); file = new CloudFile(uri, storageCredentials); } } file.FetchAttributes(); byte[] totalBytes = new byte[file.Properties.Length]; try { using (AutoResetEvent waitHandle = new AutoResetEvent(false)) { ICancellableAsyncResult result = file.BeginDownloadRangeToByteArray(totalBytes, 0, null, null, ar => waitHandle.Set(), null); waitHandle.WaitOne(); } } catch (Exception ex) { Trace.TraceError(ex.ToString()); } Trace.TraceInformation(String.Format("File length {0}", totalBytes.Length)); // totalBytes = totalBytes.Skip(startIdx).ToArray(); await handler.SendBinary(totalBytes, cts.Token); }
public ActionResult <string> GetFileContent() { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(@"DefaultEndpointsProtocol=https;AccountName=lab1diag679;AccountKey=TtymI1zwujPy40v9NvlAApX1o04SSA4Jnj2TAH4VvlnoOiPbCym4Rt9qLZwVRgeKgPIHskJBcRtcW0Rt9vxFZw==;EndpointSuffix=core.windows.net"); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare share = fileClient.GetShareReference("lab1-fs"); if (share.ExistsAsync().Result) { // Get a reference to the root directory for the share. CloudFileDirectory rootDir = share.GetRootDirectoryReference(); // Get a reference to the directory we created previously. CloudFile file = rootDir.GetFileReference("Test1.txt"); if (file.ExistsAsync().Result) { // Write the contents of the file to the console window. return(file.DownloadTextAsync().Result); } } return("file not found"); }
/// <summary> /// Reads the BLOB storing with the given key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> /// <exception cref="NotImplementedException"></exception> public byte[] ReadBlob(string key) { CloudFile cloudFile = GetCloudFileFromKey(key); try { if (!cloudFile.ExistsAsync().Result) { return(null); } cloudFile.FetchAttributesAsync().Wait(); byte[] content = new byte[cloudFile.Properties.Length]; cloudFile.DownloadToByteArrayAsync(content, 0).Wait(); return(content); } catch (Exception ex) { throw new LendsumException(S.Invariant($"The filename {key} cannot be read in {config.AzureSharedReference} "), ex); } }
public async Task <bool> AddFile(byte[] bytes, string name, bool overrideIfExists = false) { CloudFile originalFile = baseDir.GetFileReference(name); if (await originalFile.ExistsAsync() && !overrideIfExists) { return(false); } await CreateFoldersFromPath(name); try { await originalFile.UploadFromByteArrayAsync(bytes, 0, bytes.Length); } catch { return(false); } return(true); }
/// <inheritdoc /> public bool ExistsFile(string fileName, string[] path) { #region validation if (string.IsNullOrEmpty(fileName)) { throw new ArgumentNullException(nameof(fileName)); } #endregion CloudFileDirectory currentDir = CloudFileShare.GetDirectoryReference(path: path); if (!TaskUtilities.ExecuteSync(currentDir.ExistsAsync())) { return(false); } CloudFile file = currentDir.GetFileReference(fileName); return(file != null && TaskUtilities.ExecuteSync(file.ExistsAsync())); }
public async Task <string> GetText() { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_configuration.GetConnectionString("StorageAccount")); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare share = fileClient.GetShareReference(_configuration.GetSection("FileConfig:Folder").Value); if (await share.ExistsAsync()) { CloudFileDirectory rootDir = share.GetRootDirectoryReference(); CloudFile file = rootDir.GetFileReference(_configuration.GetSection("FileConfig:Filename").Value); if (await file.ExistsAsync()) { var result = file.DownloadTextAsync().Result; } } return(string.Empty); }