public async Task DeleteFile(string shareName, string folder, string fileName) { try { CloudFile cloudFile = await this.GetFileReference(shareName, folder, fileName); await cloudFile.DeleteAsync(); } catch (Exception ex) { this.ErrorMessage = ex.ToString(); } }
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); }
/// <summary> /// DeleteFileAsync /// </summary> /// <param name="shareName"></param> /// <param name="sourceFolder"></param> /// <param name="fileName"></param> /// <returns></returns> public async Task DeleteFileAsync(string shareName, string sourceFolder, string fileName) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(settings.ConnectionString); CloudFileClient cloudFileClient = storageAccount.CreateCloudFileClient(); CloudFileShare cloudFileShare = null; cloudFileShare = cloudFileClient.GetShareReference(shareName); CloudFileDirectory rootDirectory = cloudFileShare.GetRootDirectoryReference(); CloudFileDirectory fileDirectory = null; CloudFile cloudFile = null; fileDirectory = rootDirectory.GetDirectoryReference(sourceFolder); cloudFile = fileDirectory.GetFileReference(fileName); await cloudFile.DeleteAsync(); }
private async void MoveFileToProcessedFolder(CloudFile cloudFile) { CloudFileDirectory rootDirectory = _cloudFileShare.GetRootDirectoryReference(); if (rootDirectory.Exists()) { CloudFileDirectory customDirectory = rootDirectory.GetDirectoryReference(_azureFileProcessedFolderName); customDirectory.CreateIfNotExists(); var fileName = $"{Path.GetFileNameWithoutExtension(cloudFile.Name)}-{DateTime.Now.ToString(_appendDateFormatInFileName)}{Path.GetExtension(cloudFile.Name)}"; CloudFile file = customDirectory.GetFileReference(fileName); Uri fileUrl = new Uri(cloudFile.StorageUri.PrimaryUri.ToString()); await file.StartCopyAsync(fileUrl); await cloudFile.DeleteAsync(); } }
protected override async Task DeleteSingleAsync(string fullPath, CancellationToken cancellationToken) { CloudFile file = await GetFileReferenceAsync(fullPath, false, cancellationToken).ConfigureAwait(false); try { await file.DeleteAsync(cancellationToken).ConfigureAwait(false); } catch (AzStorageException ex) when(ex.RequestInformation.ErrorCode == "ResourceNotFound") { //this may be a folder CloudFileDirectory dir = await GetDirectoryReferenceAsync(fullPath, cancellationToken).ConfigureAwait(false); if (await dir.ExistsAsync().ConfigureAwait(false)) { await DeleteDirectoryAsync(dir, cancellationToken).ConfigureAwait(false); } } }
/// <summary> /// Deletes the file. /// </summary> /// <returns>The file</returns> /// <param name="type">Type of file being deleted</param> public async Task <bool> DeleteFile(FileType type, string guid) { try { CloudFileDirectory root = cloud.CreateCloudFileClient() .GetShareReference(type.ToString().ToLower()) .GetRootDirectoryReference(); CloudFile cloudFile = root.GetFileReference(Path.GetFileName(guid)); if (cloudFile != null) { await cloudFile.DeleteAsync(); return(true); } } catch (Exception e) { System.Diagnostics.Trace.TraceWarning("Exception during deleting file: " + e.ToString()); } return(false); }
public Task DeleteFileAsync(CloudFile file, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { return(file.DeleteAsync(accessCondition, options, operationContext, cancellationToken)); }
/// <summary> /// Basic operations to work with Azure Files /// </summary> /// <returns>Task</returns> private static async Task BasicAzureFileOperationsAsync() { const string DemoShare = "demofileshare"; const string DemoDirectory = "demofiledirectory"; const string ImageToUpload = "HelloWorld.png"; // Retrieve storage account information from connection string // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create a file client for interacting with the file service. CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); // Create a share for organizing files and directories within the storage account. Console.WriteLine("1. Creating file share"); CloudFileShare share = fileClient.GetShareReference(DemoShare); try { await share.CreateIfNotExistsAsync(); } catch (StorageException) { Console.WriteLine("Please make sure your storage account has storage file endpoint enabled and specified correctly in the app.config - then restart the sample."); Console.WriteLine("Press any key to exit"); Console.ReadLine(); throw; } // Get a reference to the root directory of the share. CloudFileDirectory root = share.GetRootDirectoryReference(); // Create a directory under the root directory Console.WriteLine("2. Creating a directory under the root directory"); CloudFileDirectory dir = root.GetDirectoryReference(DemoDirectory); await dir.CreateIfNotExistsAsync(); // Uploading a local file to the directory created above Console.WriteLine("3. Uploading a file to directory"); CloudFile file = dir.GetFileReference(ImageToUpload); await file.UploadFromFileAsync(ImageToUpload); // List all files/directories under the root directory Console.WriteLine("4. List Files/Directories in root directory"); List <IListFileItem> results = new List <IListFileItem>(); FileContinuationToken token = null; do { FileResultSegment resultSegment = await share.GetRootDirectoryReference().ListFilesAndDirectoriesSegmentedAsync(token); results.AddRange(resultSegment.Results); token = resultSegment.ContinuationToken; }while (token != null); // Print all files/directories listed above foreach (IListFileItem listItem in results) { // listItem type will be CloudFile or CloudFileDirectory Console.WriteLine("- {0} (type: {1})", listItem.Uri, listItem.GetType()); } // Download the uploaded file to your file system Console.WriteLine("5. Download file from {0}", file.Uri.AbsoluteUri); await file.DownloadToFileAsync(string.Format("./CopyOf{0}", ImageToUpload), FileMode.Create); // Clean up after the demo Console.WriteLine("6. Delete file"); await file.DeleteAsync(); // When you delete a share it could take several seconds before you can recreate a share with the same // name - hence to enable you to run the demo in quick succession the share is not deleted. If you want // to delete the share uncomment the line of code below. // Console.WriteLine("7. Delete Share"); // await share.DeleteAsync(); }
public static void Delete(this CloudFile file, AccessCondition accessCondition = null, FileRequestOptions options = null, OperationContext operationContext = null) { file.DeleteAsync(accessCondition, options, operationContext).GetAwaiter().GetResult(); }
public async void FileStorageTest() { ClearOutput(); WriteLine("-- Testing File Storage --"); WriteLine("0. Creating file client"); // Create a file client for interacting with the file service. CloudFileClient fileClient = StorageAccount.CreateCloudFileClient(); // Create a share for organizing files and directories within the storage account. WriteLine("1. Creating file share"); CloudFileShare share = fileClient.GetShareReference(DemoShare); try { await share.CreateIfNotExistsAsync(); } catch (StorageException) { WriteLine("Please make sure your storage account has storage file endpoint enabled and specified correctly in the app.config - then restart the sample."); throw; } // Get a reference to the root directory of the share. CloudFileDirectory root = share.GetRootDirectoryReference(); // Create a directory under the root directory WriteLine("2. Creating a directory under the root directory"); CloudFileDirectory dir = root.GetDirectoryReference(DemoDirectory); await dir.CreateIfNotExistsAsync(); // Uploading a local file to the directory created above WriteLine("3. Uploading a file to directory"); CloudFile file = dir.GetFileReference(ImageToUpload); #if WINDOWS_UWP && ENABLE_DOTNET StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(Application.streamingAssetsPath.Replace('/', '\\')); StorageFile sf = await storageFolder.GetFileAsync(ImageToUpload); await file.UploadFromFileAsync(sf); #else await file.UploadFromFileAsync(Path.Combine(Application.streamingAssetsPath, ImageToUpload)); #endif // List all files/directories under the root directory WriteLine("4. List Files/Directories in root directory"); List <IListFileItem> results = new List <IListFileItem>(); FileContinuationToken token = null; do { FileResultSegment resultSegment = await share.GetRootDirectoryReference().ListFilesAndDirectoriesSegmentedAsync(token); results.AddRange(resultSegment.Results); token = resultSegment.ContinuationToken; }while (token != null); // Print all files/directories listed above foreach (IListFileItem listItem in results) { // listItem type will be CloudFile or CloudFileDirectory WriteLine(string.Format("- {0} (type: {1})", listItem.Uri, listItem.GetType())); } // Download the uploaded file to your file system string path; WriteLine(string.Format("5. Download file from {0}", file.Uri.AbsoluteUri)); string fileName = string.Format("CopyOf{0}", ImageToUpload); #if WINDOWS_UWP && ENABLE_DOTNET storageFolder = ApplicationData.Current.TemporaryFolder; sf = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); path = sf.Path; await file.DownloadToFileAsync(sf); #else path = Path.Combine(Application.temporaryCachePath, fileName); await file.DownloadToFileAsync(path, FileMode.Create); #endif WriteLine("File written to " + path); // Clean up after the demo WriteLine("6. Delete file"); await file.DeleteAsync(); // When you delete a share it could take several seconds before you can recreate a share with the same // name - hence to enable you to run the demo in quick succession the share is not deleted. If you want // to delete the share uncomment the line of code below. WriteLine("7. Delete Share -- Note that it will take a few seconds before you can recreate a share with the same name"); await share.DeleteAsync(); WriteLine("-- Test Complete --"); }
private async Task BasicAzureFileOperationsAsync() { const string DemoShare = "demofileshare"; const string DemoDirectory = "demofiledirectory"; const string ImageToUpload = "HelloWorld.png"; CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(AppConfig.ConnectionString); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare share = fileClient.GetShareReference(DemoShare); try { await share.CreateIfNotExistsAsync(); } catch (StorageException) { Debug.WriteLine("Please make sure your storage account has storage file endpoint enabled and specified correctly in the app.config - then restart the sample."); } CloudFileDirectory root = share.GetRootDirectoryReference(); Debug.WriteLine("2. Creating a directory under the root directory"); CloudFileDirectory dir = root.GetDirectoryReference(DemoDirectory); await dir.CreateIfNotExistsAsync(); StorageFolder storageFolder = ApplicationData.Current.LocalFolder; var realFile = await storageFolder.CreateFileAsync(ImageToUpload, Windows.Storage.CreationCollisionOption.ReplaceExisting); Debug.WriteLine("3. Uploading a file to directory"); CloudFile file = dir.GetFileReference(ImageToUpload); await file.UploadFromFileAsync(realFile); // List all files/directories under the root directory Debug.WriteLine("4. List Files/Directories in root directory"); List <IListFileItem> results = new List <IListFileItem>(); FileContinuationToken token = null; do { FileResultSegment resultSegment = await share.GetRootDirectoryReference().ListFilesAndDirectoriesSegmentedAsync(token); results.AddRange(resultSegment.Results); token = resultSegment.ContinuationToken; }while (token != null); // Print all files/directories listed above foreach (IListFileItem listItem in results) { // listItem type will be CloudFile or CloudFileDirectory Debug.WriteLine("- {0} (type: {1})", listItem.Uri, listItem.GetType()); } // Download the uploaded file to your file system Debug.WriteLine("5. Download file from {0}", file.Uri.AbsoluteUri); var newFile = await storageFolder.CreateFileAsync(string.Format("./CopyOf{0}", ImageToUpload), Windows.Storage.CreationCollisionOption.ReplaceExisting); await file.DownloadToFileAsync(newFile); // Clean up after the demo Debug.WriteLine("6. Delete file"); await file.DeleteAsync(); // When you delete a share it could take several seconds before you can recreate a share with the same // name - hence to enable you to run the demo in quick succession the share is not deleted. If you want // to delete the share uncomment the line of code below. // Console.WriteLine("7. Delete Share"); // await share.DeleteAsync(); }
public override async Task DeleteAsync() { await _file.DeleteAsync(); }
public async Task RunPermissionsTestFiles(SharedAccessAccountPolicy policy) { CloudFileClient fileClient = GenerateCloudFileClient(); string shareName = "s" + Guid.NewGuid().ToString("N"); try { CloudStorageAccount account = new CloudStorageAccount(fileClient.Credentials, false); string accountSASToken = account.GetSharedAccessSignature(policy); StorageCredentials accountSAS = new StorageCredentials(accountSASToken); CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, null, null, null, fileClient.StorageUri); CloudFileClient fileClientWithSAS = accountWithSAS.CreateCloudFileClient(); CloudFileShare shareWithSAS = fileClientWithSAS.GetShareReference(shareName); CloudFileShare share = fileClient.GetShareReference(shareName); // General pattern - If current perms support doing a thing with SAS, do the thing with SAS and validate with shared // Otherwise, make sure SAS fails and then do the thing with shared key. // Things to do: // Create the share (Create / Write perms, Container RT) // List shares with prefix (List perms, Service RT) // Create a new file (Create / Write, Object RT) // Add a range to the file (Write, Object RT) // Read the data from the file (Read, Object RT) // Overwrite a file (Write, Object RT) // Delete the file (Delete perms, Object RT) if ((((policy.Permissions & SharedAccessAccountPermissions.Create) == SharedAccessAccountPermissions.Create) || ((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write)) && ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Container) == SharedAccessAccountResourceTypes.Container)) { await shareWithSAS.CreateAsync(); } else { await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await shareWithSAS.CreateAsync(), "Creating a share with SAS should fail without Create or Write and Container-level perms."); await share.CreateAsync(); } Assert.IsTrue(await share.ExistsAsync()); if (((policy.Permissions & SharedAccessAccountPermissions.List) == SharedAccessAccountPermissions.List) && ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Service) == SharedAccessAccountResourceTypes.Service)) { Assert.AreEqual(shareName, (await fileClientWithSAS.ListSharesSegmentedAsync(shareName, null)).Results.First().Name); } else { await TestHelper.ExpectedExceptionAsync <StorageException>(async() => (await fileClientWithSAS.ListSharesSegmentedAsync(shareName, null)).Results.First(), "Listing shared with SAS should fail without List and Service-level perms."); } string filename = "fileName"; CloudFile fileWithSAS = shareWithSAS.GetRootDirectoryReference().GetFileReference(filename); CloudFile file = share.GetRootDirectoryReference().GetFileReference(filename); //Try creating credentials using SAS Uri directly CloudFile fileWithSASUri = new CloudFile(new Uri(share.Uri + accountSASToken)); byte[] content = new byte[] { 0x1, 0x2, 0x3, 0x4 }; if ((((policy.Permissions & SharedAccessAccountPermissions.Create) == SharedAccessAccountPermissions.Create) || ((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write)) && ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object)) { await fileWithSAS.CreateAsync(content.Length); } else { await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await fileWithSAS.CreateAsync(content.Length), "Creating a file with SAS should fail without Create or Write and Object-level perms."); await file.CreateAsync(content.Length); } Assert.IsTrue(await file.ExistsAsync()); using (MemoryStream stream = new MemoryStream(content)) { if (((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write) && ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object)) { await fileWithSAS.WriteRangeAsync(stream, 0, null); } else { await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await fileWithSAS.WriteRangeAsync(stream, 0, null), "Writing a range to a file with SAS should fail without Write and Object-level perms."); stream.Seek(0, SeekOrigin.Begin); await file.WriteRangeAsync(stream, 0, null); } } byte[] result = new byte[content.Length]; await file.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length); for (int i = 0; i < content.Length; i++) { Assert.AreEqual(content[i], result[i]); } if (((policy.Permissions & SharedAccessAccountPermissions.Read) == SharedAccessAccountPermissions.Read) && ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object)) { result = new byte[content.Length]; await fileWithSAS.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length); for (int i = 0; i < content.Length; i++) { Assert.AreEqual(content[i], result[i]); } } else { await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await fileWithSAS.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length), "Reading a file with SAS should fail without Read and Object-level perms."); } if (((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write) && ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object)) { await fileWithSAS.CreateAsync(2); } else { await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await fileWithSAS.CreateAsync(2), "Overwriting a file with SAS should fail without Write and Object-level perms."); await file.CreateAsync(2); } result = new byte[content.Length]; await file.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length); for (int i = 0; i < content.Length; i++) { Assert.AreEqual(0, result[i]); } if (((policy.Permissions & SharedAccessAccountPermissions.Delete) == SharedAccessAccountPermissions.Delete) && ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object)) { await fileWithSAS.DeleteAsync(); } else { await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await fileWithSAS.DeleteAsync(), "Deleting a file with SAS should fail without Delete and Object-level perms."); await file.DeleteAsync(); } Assert.IsFalse(await file.ExistsAsync()); } finally { fileClient.GetShareReference(shareName).DeleteIfExistsAsync().Wait(); } }