private Task <CloudFileDirectory> GetDirectoryReferenceAsync(string fullPath, CancellationToken cancellationToken) { string[] parts = StoragePath.Split(fullPath); if (parts.Length == 0) { return(null); } string shareName = parts[0]; CloudFileShare share = _client.GetShareReference(shareName); CloudFileDirectory dir = share.GetRootDirectoryReference(); for (int i = 1; i < parts.Length; i++) { string sub = parts[i]; dir = dir.GetDirectoryReference(sub); } return(Task.FromResult(dir)); }
internal string SetAzureShareStoredAccessPolicy(IStorageFileManagement localChannel, string shareName, string policyName, DateTime?startTime, DateTime?expiryTime, string permission, bool noStartTime, bool noExpiryTime) { //Get existing permissions CloudFileShare share = localChannel.GetShareReference(shareName); FileSharePermissions permissions = localChannel.GetSharePermissions(share); //Set the policy with new value if (!permissions.SharedAccessPolicies.Keys.Contains(policyName)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.PolicyNotFound, policyName)); } SharedAccessFilePolicy policy = permissions.SharedAccessPolicies[policyName]; AccessPolicyHelper.SetupAccessPolicy <SharedAccessFilePolicy>(policy, startTime, expiryTime, permission, noStartTime, noExpiryTime); permissions.SharedAccessPolicies[policyName] = policy; //Set permission back to share localChannel.SetSharePermissions(share, permissions); WriteObject(AccessPolicyHelper.ConstructPolicyOutputPSObject <SharedAccessFilePolicy>(permissions.SharedAccessPolicies, policyName)); return(policyName); }
public async Task CreateFileShare(string siteName, string connectionString, string fileShareName) { try { var storageAccount = CloudStorageAccount.Parse(connectionString); var fileClient = storageAccount.CreateCloudFileClient(); // Get a reference to the file share we created previously. CloudFileShare share = fileClient.GetShareReference(fileShareName); KuduEventGenerator.Log(_environment).LogMessage(EventLevel.Informational, siteName, $"Creating Kudu mount file share {fileShareName}", string.Empty); await share.CreateIfNotExistsAsync(new FileRequestOptions(), new OperationContext()); } catch (Exception e) { KuduEventGenerator.Log(_environment) .LogMessage(EventLevel.Warning, siteName, nameof(CreateFileShare), e.ToString()); throw; } }
public void UploadToFileShare(string fileShareName, string fileContents, string fileName = "") { //Create GUID to for filename if no name specified if (fileName.Length == 0) { fileName = Guid.NewGuid().ToString(); } byte[] filebytes = Encoding.UTF8.GetBytes(fileContents); CloudFileClient fileClient = new CloudFileClient(fileURI, creds); // Create a CloudFileClient object for credentialed access to Azure Files. // Get a reference to the file share we created previously. CloudFileShare share = fileClient.GetShareReference(fileShareName); // Ensure that the share exists. if (share.Exists()) { try { // Get a reference to the root directory for the share. CloudFileDirectory rootDir = share.GetRootDirectoryReference(); CloudFile cloudFile = rootDir.GetFileReference(fileName); Stream stream = new MemoryStream(filebytes); //Upload the file to Azure. cloudFile.UploadFromStreamAsync(stream).Wait(); stream.Dispose(); } catch (Exception e) { throw new StorageAccountException("Error while attempting to upload", e); } } else { DirectoryNotFoundException e = new DirectoryNotFoundException(string.Format("The file share '{0}' does not exist.", fileShareName)); throw new StorageAccountException("Error while attempting to upload", e); } }
public static List <string> ListFiles() { List <string> files = new List <string>(); CloudFileShare share = GetFileShare(); if (share.Exists()) { CloudFileDirectory directory = share.GetRootDirectoryReference(); if (directory.Exists()) { IEnumerable <IListFileItem> list = directory.ListFilesAndDirectories(); foreach (IListFileItem item in list) { string filename = Path.GetFileName(item.Uri.ToString()); files.Add(filename); } } } return(files); }
/// <summary> /// GetCloudFileStream - ORIG /// </summary> /// <param name="imageFileDirectory"></param> /// <param name="imageFileName"></param> /// <returns></returns> protected MemoryStream GetCloudFileStreamOrig(string imageFileDirectory, string imageFileName) { MemoryStream memstream = new MemoryStream(); try { CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(azureFileShareConnectionString); CloudFileClient fileClient = cloudStorageAccount.CreateCloudFileClient(); CloudFileShare share = fileClient.GetShareReference(azureFileShareName); if (!share.Exists()) { throw new ShareNotFoundException(azureFileShareName); } // Get a reference to the root directory for the share CloudFileDirectory rootDir = share.GetRootDirectoryReference(); // Get a reference to the image directory CloudFileDirectory shareDir = rootDir.GetDirectoryReference(imageFileDirectory); if (!shareDir.Exists()) { throw new FolderNotFoundException(imageFileDirectory); } // get a cloud file reference to the image CloudFile file = shareDir.GetFileReference(imageFileName); if (!file.Exists()) { throw new FileNotFoundException(imageFileDirectory, imageFileName); } file.DownloadToStream(memstream); } catch (Exception oExeption) { oExeption.Log($"GetCloudFileStreamOrig - {imageFileDirectory}\\{imageFileName}]"); } return(memstream); }
/// <summary> /// Create a directory (if it doesn't exist already) /// </summary> /// <param name="directoryName"></param> /// <returns></returns> public bool CreateDirectory(string directoryName) { try { directoryName = CleanRelativeCloudDirectoryName(directoryName); CloudStorageAccount cloudStorageAccount = GetCloudStorageAccount(); CloudFileClient fileClient = GetCloudFileClient(cloudStorageAccount); CloudFileShare cloudFileShare = GetCloudFileShareReference(fileClient); // share /// 20180106 - we need a ref to the directory in order to create it - our create returns null /// 20180106 - modified Get/Check to return ref when not found // Get a reference to the root directory for the share /*CloudFileDirectory cloudRootShareDirectory = cloudFileShare.GetRootDirectoryReference(); * * directoryName = CleanRelativeCloudDirectoryName(directoryName); * * // Get a reference to the image directory * CloudFileDirectory cloudShareDirectory = cloudRootShareDirectory.GetDirectoryReference(directoryName); * * if (!cloudShareDirectory.Exists()) * cloudRootShareDirectory.Create(); * //////// */ CloudFileDirectory shareDir = GetCloudFileDirectory(cloudFileShare, directoryName); // share, if ((shareDir != null) && !shareDir.Exists()) // (shareDir == null) || { shareDir.Create(); } //////// return(true); } catch (Exception oExeption) { oExeption.Log($"CreateDirectory - [{directoryName}]"); return(false); } }
public static bool DeleteFileShare() { try { // Create the CloudTable that represents the "people" table. CloudFileShare fileShare = fileClient.GetShareReference(_shareName); // Delete the table it if exists. fileShare.DeleteIfExists(); } catch (Exception ex) { if (_feedback != null) { _feedback.OnException(fileClient, ex); } return(false); } return(true); }
private static CloudFileDirectory GetFileDirectory(string folderPath) { CloudFileDirectory directory = null; try { CloudFileShare fileShare = GetFileShare(); CloudFileDirectory root = fileShare.GetRootDirectoryReference(); directory = root.GetDirectoryReference(folderPath); } catch (Exception ex) { if (_feedback != null) { _feedback.OnException(fileClient, ex); } } return(directory); }
/// <summary> /// Validate the file share access policy /// </summary> /// <param name="policy">SharedAccessFilePolicy object</param> /// <param name="policyIdentifier">The policy identifier which need to be checked.</param> public static bool ValidateShareAccessPolicy(IStorageFileManagement channel, string shareName, string policyIdentifier, bool shouldNoPermission, bool shouldNoStartTime, bool shouldNoExpiryTime) { if (string.IsNullOrEmpty(policyIdentifier)) { return(true); } CloudFileShare fileShare = channel.GetShareReference(shareName); FileSharePermissions permission; try { permission = fileShare.GetPermissionsAsync().Result; } catch (AggregateException e) when(e.InnerException is StorageException) { throw e.InnerException; } SharedAccessFilePolicy sharedAccessPolicy = GetExistingPolicy <SharedAccessFilePolicy>(permission.SharedAccessPolicies, policyIdentifier); if (shouldNoPermission && sharedAccessPolicy.Permissions != SharedAccessFilePermissions.None) { throw new InvalidOperationException(Resources.SignedPermissionsMustBeOmitted); } if (shouldNoStartTime && sharedAccessPolicy.SharedAccessStartTime.HasValue) { throw new InvalidOperationException(Resources.SignedStartTimeMustBeOmitted); } if (shouldNoExpiryTime && sharedAccessPolicy.SharedAccessExpiryTime.HasValue) { throw new InvalidOperationException(Resources.SignedExpiryTimeMustBeOmitted); } return(!sharedAccessPolicy.SharedAccessExpiryTime.HasValue); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); // Parse the connection string and return a reference to the storage account. // CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=personal5772156649;AccountKey=GPV82gR7e7+1woWq0MwIlVU6zrNg1OCE+9/+cY1vCWHE6gfXzzGvscGNxnTerRiiXToiu+Du0yGLcq0MF7kLRg==;EndpointSuffix=core.windows.net"); // Create a CloudFileClient object for credentialed access to Azure Files. CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); // Get a reference to the file share we created previously. CloudFileShare share = fileClient.GetShareReference("genrestxt"); // Ensure that the share exists. if (share.Exists()) { // Get a reference to the root directory for the share. CloudFileDirectory rootDir = share.GetRootDirectoryReference(); // Get a reference to the directory we created previously. CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("CustomLogs"); // Ensure that the directory exists. if (sampleDir.Exists()) { // Get a reference to the file we created previously. CloudFile file = sampleDir.GetFileReference("Log1.txt"); // Ensure that the file exists. if (file.Exists()) { // Write the contents of the file to the console window. Console.WriteLine(file.DownloadTextAsync().Result); } } } }
public static string GetSharedAccessSignature( CloudFileShare share, SharedAccessFilePolicy policy, string groupPolicyIdentifier, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange, string targetStorageVersion) { if (!share.ServiceClient.Credentials.IsSharedKey) { string errorMessage = string.Format(CultureInfo.CurrentCulture, "CannotCreateSASWithoutAccountKey"); throw new InvalidOperationException(errorMessage); } string resourceName = GetCanonicalName(share); string signature = GetHash( policy, null /* headers */, groupPolicyIdentifier, resourceName, targetStorageVersion, protocols, ipAddressOrRange, share.ServiceClient.Credentials.ExportKey()); UriQueryBuilder builder = GetSignature( policy, null /* headers */, groupPolicyIdentifier, "s", signature, null, targetStorageVersion, protocols, ipAddressOrRange); return(builder.ToString()); }
public static void Main(string[] args) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare shareFile = fileClient.GetShareReference("unit name or directory"); if (shareFile.Exists()) { CloudFileDirectory rootDirectory = shareFile.GetRootDirectoryReference(); CloudFileDirectory directory = rootDirectory.GetDirectoryReference("especific directory"); if (directory.Exists()) { CloudFile file = directory.GetFileReference("file_name.extension"); if (file.Exists()) { Console.WriteLine(file.DownloadTextAsync().Result); Console.ReadLine(); } } } }
public void ValidateShareCreatableWithSasToken(string shareName, string accountName, string sastoken) { Test.Info("Verify share create permission"); CloudStorageAccount sasAccount = TestBase.GetStorageAccountWithSasToken(accountName, sastoken); //make sure the share not exist before create CloudFileShare sasShareReference = client.GetShareReference(shareName); if (sasShareReference.Exists()) { sasShareReference.Delete(); Thread.Sleep(2 * 60 * 1000); // Sleep 2 minutes to make sure the share can be created successfully } //Create Share with SAS CloudFileShare sasShare = sasAccount.CreateCloudFileClient().GetShareReference(shareName); sasShare.Create(); //Verify and delete share Test.Assert(sasShareReference.Exists(), "The Share {0} should exist.", shareName); sasShareReference.Delete(); }
public bool DeleteFile(string fileDirectory, string fileName) { try { fileDirectory = CleanRelativeCloudDirectoryName(fileDirectory); CloudStorageAccount cloudStorageAccount = GetCloudStorageAccount(); CloudFileClient fileClient = GetCloudFileClient(cloudStorageAccount); CloudFileShare share = GetCloudFileShareReference(fileClient); CloudFileDirectory shareDir = GetCloudFileDirectory(share, fileDirectory); CloudFile file = GetCloudFile(shareDir, fileName); if (file.Exists()) { file.Delete(); return(true); } } catch (Exception oExeption) { oExeption.Log($"DeleteFile - [{fileDirectory}\\{fileName}]"); } return(false); }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Public helpers members /// public bool FileExists(string fileDirectory, string fileName) { try { fileDirectory = CleanRelativeCloudDirectoryName(fileDirectory); CloudStorageAccount cloudStorageAccount = GetCloudStorageAccount(); CloudFileClient fileClient = GetCloudFileClient(cloudStorageAccount); CloudFileShare share = GetCloudFileShareReference(fileClient); CloudFileDirectory cloudFileDirectory = GetCloudFileDirectory(share, fileDirectory); if ((cloudFileDirectory != null) && cloudFileDirectory.Exists()) { CloudFile cloudFile = cloudFileDirectory.GetFileReference(fileName); //CloudFile file = GetCloudFile(shareDir, fileName); return(cloudFile.Exists()); } } catch (Exception oExeption) { oExeption.Log($"FileExits - [{fileDirectory}\\{fileName}]"); } return(false); }
public CloudFile GetCloudFileReference(string rootPath, FileNode fileNode, StorageCredentials credentials = null) { var share = this.fileHelper.FileClient.GetShareReference(this.shareName, snapshotTime); if (credentials != null) { share = new CloudFileShare(share.SnapshotQualifiedStorageUri, credentials); } string fileName = fileNode.GetURLRelativePath(); if (fileName.StartsWith("/")) { fileName = fileName.Substring(1, fileName.Length - 1); } if (!string.IsNullOrEmpty(rootPath)) { fileName = rootPath + "/" + fileName; } return(share.GetRootDirectoryReference().GetFileReference(fileName)); }
/// <summary> /// Async Method to get Data from Azure Cloud. /// </summary> /// <returns>String of the file.</returns> private async Task <string> GetData_Async() { string DataToShare = string.Empty; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_ConnectionString); // Create a new file share, if it does not already exist. // Create a CloudFileClient object for credentialed access to File storage. CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare share = fileClient.GetShareReference(_DirectoryLocation); if (await share.ExistsAsync()) { CloudFileDirectory rootDir = share.GetRootDirectoryReference(); if (await rootDir.ExistsAsync()) { CloudFile FiletoUse = rootDir.GetFileReference(_FileName); if (await FiletoUse.ExistsAsync()) { DataToShare = await FiletoUse.DownloadTextAsync(); } } } return(DataToShare); }
public async Task <bool> UploadAsync(string filePath, string version) { try { CloudStorageAccount account = GetStorageAccount(); logger.Debug("Uploading {trace} to {azure}/{directory}/", filePath, account.FileStorageUri, storage.Directory); CloudFileShare share = await GetOrCreateShareAsync(account); CloudFileDirectory directory = await GetOrCreateTargetDirectoryAsync(share); await UploadFileAsync(filePath, directory); logger.Info("Successfully uploaded {trace} to {azure}/{directory}", filePath, account.FileStorageUri, storage.Directory); return(true); } catch (Exception e) { logger.Error(e, "Upload of {trace} to Azure File Storage failed: {message}", filePath, e.Message); return(false); } }
public void storeFile(String path, String fileName, String uploadFile) { CloudFileClient fileClient = this.storageAccount.CreateCloudFileClient(); CloudFileShare fileShare = fileClient.GetShareReference(this._appSettings.AzureFIleStoreName); if (fileShare.Exists()) { CloudFileDirectory root = fileShare.GetRootDirectoryReference(); CloudFileDirectory folder = root.GetDirectoryReference(path); if (!folder.Exists()) { folder.Create(); } CloudFile file = folder.GetFileReference(fileName); using (AutoResetEvent waitHandle = new AutoResetEvent(false)) { ICancellableAsyncResult result = file.BeginUploadFromFile(uploadFile, ar => waitHandle.Set(), new object()); waitHandle.WaitOne(); file.EndUploadFromFile(result); } } }
public AzureFilePersistenceSystem(Enums.FileType fileType, Enums.FileSubType fileSubType, string folder) : base(fileType, fileSubType, folder) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create a CloudFileClient object for credentialed access to File storage. CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); // Get a reference to the file share we created previously. CloudFileShare share = null; switch (FileType) { case Enums.FileType.Photo: share = fileClient.GetShareReference("photos"); break; } // Ensure that the share exists. if (share.Exists()) { // Get a reference to the root directory for the share. CloudFileDirectory rootDir = share.GetRootDirectoryReference(); // Get a reference to the directory we created previously. fileDirectory = rootDir.GetDirectoryReference(((int)FileSubType).ToString()); if (!fileDirectory.Exists()) { fileDirectory.Create(); } fileDirectory = fileDirectory.GetDirectoryReference(Folder); if (!fileDirectory.Exists()) { fileDirectory.Create(); } } }
public async Task <FileResult> GetPdf(string fileName) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create a CloudFileClient object for credentialed access to Azure Files. CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); // Get a reference to the file share we created previously. CloudFileShare share = fileClient.GetShareReference("ankerhpdf"); // Ensure that the share exists. if (share.Exists()) { // Get a reference to the root directory for the share. CloudFileDirectory rootDir = share.GetRootDirectoryReference(); // Get a reference to the directory we created previously. CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("Faktura"); // Ensure that the directory exists. if (sampleDir.Exists()) { // Get a reference to the file we created previously. CloudFile file = sampleDir.GetFileReference(fileName); // Ensure that the file exists. if (file.Exists()) { MemoryStream ms = new MemoryStream(); await file.DownloadToStreamAsync(ms); ms.Seek(0, SeekOrigin.Begin); return(File(ms, "application/pdf")); } } } return(null); }
public void Access_the_file_share_programmatically() { // Retrieve storage account from connection string. StorageCredentials Credentials = new StorageCredentials(this.Account, this.Key); CloudStorageAccount storageAccount = new CloudStorageAccount(Credentials, false); // Create a CloudFileClient object for credentialed access to File storage. CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); // Get a reference to the file share we created previously. CloudFileShare share = fileClient.GetShareReference("logs"); // Ensure that the share exists. if (share.Exists()) { // Get a reference to the root directory for the share. CloudFileDirectory rootDir = share.GetRootDirectoryReference(); // Get a reference to the directory we created previously. CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("CustomLogs"); // Ensure that the directory exists. if (sampleDir.Exists()) { // Get a reference to the file we created previously. CloudFile file = sampleDir.GetFileReference("Log1.txt"); // Ensure that the file exists. if (file.Exists()) { // Write the contents of the file to the console window. Console.WriteLine(file.DownloadTextAsync().Result); } } } }
public TasklistCSVRemote() { this.storageAccount = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting("StorageConnectionString")); this.fileClient = storageAccount.CreateCloudFileClient(); this.share = fileClient.GetShareReference("tasklistdatabasestore"); this.root = this.share.GetRootDirectoryReference(); // Get a reference to the file we created previously. dbFile = this.root.GetFileReference("tasklist.csv"); // Ensure that the files exists, and create if necessary if (!dbFile.Exists()) { dbFile.Create(1000000); // Create 1mb file // Write CSV header string hdrText = "id,title,isComplete\r\n"; this.hdrBytes = Encoding.ASCII.GetBytes(hdrText); dbFile.WriteRange(new MemoryStream(this.hdrBytes), 0); // Populate with a few entries this.RebuildList(); } }
static void Main(string[] args) { CloudStorageAccount cuentaAlmacenamiento = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("cadenaConexion")); CloudFileClient clienteArchivos = cuentaAlmacenamiento.CreateCloudFileClient(); CloudFileShare archivoCompartido = clienteArchivos.GetShareReference("platzi"); if (archivoCompartido.Exists()) { CloudFileDirectory carpetaRaiz = archivoCompartido.GetRootDirectoryReference(); CloudFileDirectory directorio = carpetaRaiz.GetDirectoryReference("registros"); if (directorio.Exists()) { CloudFile archivo = directorio.GetFileReference("logActividades.txt"); if (archivo.Exists()) { System.Console.WriteLine(archivo.DownloadTextAsync().Result); System.Console.ReadLine(); } } } }
private async Task <CloudFile> GetFileReference(string shareName, string folder, string fileName) { CloudFile cloudFile = null; try { CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(this.ConnectionString); CloudFileClient cloudFileClient = storageAccount.CreateCloudFileClient(); CloudFileShare cloudFileShare = cloudFileClient.GetShareReference(shareName); await cloudFileShare.CreateIfNotExistsAsync(); CloudFileDirectory rootDirectory = cloudFileShare.GetRootDirectoryReference(); CloudFileDirectory fileDirectory = null; if (!string.IsNullOrEmpty(folder)) { fileDirectory = rootDirectory.GetDirectoryReference(folder); } else { fileDirectory = rootDirectory; } await fileDirectory.CreateIfNotExistsAsync(); cloudFile = fileDirectory.GetFileReference(fileName); } catch (StorageException exStorage) { this.ErrorMessage = exStorage.ToString(); } catch (Exception ex) { this.ErrorMessage = ex.ToString(); } return(cloudFile); }
private async static void DownloadContent() { CloudFileShare trialFileShare = _cloudFileClient.GetShareReference("trial"); if (await trialFileShare.ExistsAsync()) { CloudFileDirectory rootDirectory = trialFileShare.GetRootDirectoryReference(); CloudFileDirectory textFoldersDirectory = rootDirectory.GetDirectoryReference("text-folders"); if (await textFoldersDirectory.ExistsAsync()) { CloudFile myTargetFile = textFoldersDirectory.GetFileReference("my targets.txt"); if (await myTargetFile.ExistsAsync()) { string content = await myTargetFile.DownloadTextAsync(); Console.WriteLine(content); } } } else { Console.WriteLine("File share doesn't exist"); } }
internal bool RemoveAzureShareStoredAccessPolicy(IStorageFileManagement localChannel, string shareName, string policyName) { bool success = false; string result = string.Empty; //Get existing permissions CloudFileShare share = localChannel.GetShareReference(shareName); FileSharePermissions permissions = localChannel.GetSharePermissions(share); //remove the specified policy if (!permissions.SharedAccessPolicies.Keys.Contains(policyName)) { throw new ResourceNotFoundException(String.Format(CultureInfo.CurrentCulture, Resources.PolicyNotFound, policyName)); } if (this.Force || ConfirmRemove(policyName)) { permissions.SharedAccessPolicies.Remove(policyName); localChannel.SetSharePermissions(share, permissions); success = true; } return(success); }
public override async Task <string> SaveAsync(FileSetOptions fileSetOptions) { FileData file = new FileData(); CloudStorageAccount storageAccount = Authorized(fileSetOptions); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare fileshare = fileClient.GetShareReference(fileSetOptions.Folder); await fileshare.CreateIfNotExistsAsync(); CloudFileDirectory cFileDir = fileshare.GetRootDirectoryReference(); await cFileDir.CreateIfNotExistsAsync(); CloudFile cFile = cFileDir.GetFileReference(fileSetOptions.Key); fileSetOptions._stream.Position = 0; await cFile.UploadFromStreamAsync(fileSetOptions._stream); return(fileSetOptions.Key); }
public static void NewFileCreate() { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connection); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare share = fileClient.GetShareReference("doc2020"); // Ensure that the share exists. if (share.Exists()) { string policyName = "FileSharePolicy" + DateTime.UtcNow.Ticks; SharedAccessFilePolicy sharedPolicy = new SharedAccessFilePolicy() { SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24), Permissions = SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write }; FileSharePermissions permissions = share.GetPermissions(); permissions.SharedAccessPolicies.Add(policyName, sharedPolicy); share.SetPermissions(permissions); CloudFileDirectory rootDir = share.GetRootDirectoryReference(); CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("storage"); CloudFile file = sampleDir.GetFileReference("Log2.txt"); string sasToken = file.GetSharedAccessSignature(null, policyName); Uri fileSasUri = new Uri(file.StorageUri.PrimaryUri.ToString() + sasToken); // Create a new CloudFile object from the SAS, and write some text to the file. CloudFile fileSas = new CloudFile(fileSasUri); fileSas.UploadText("This file created by the Console App at Runtime"); Console.WriteLine(fileSas.DownloadText()); } }