private void WriteLogLine(WriteWay writeWay, string writeLogLine, params string[] logFilePath) { if (logFilePath.Length < 2) { Console.WriteLine(invalidExistLogFilePath); return; } CloudStorageAccount storageAccount = CloudStorageAccount.Parse( string.Format(@"DefaultEndpointsProtocol=https;AccountName={0}; AccountKey={1};EndpointSuffix=core.windows.net", Constant.LOGGER_ACCOUNT_NAME, Constant.Instance.StorageAccountKey)); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare share = fileClient.GetShareReference(logFilePath[0]); if (!share.Exists()) { share.Create(); } CloudFileDirectory sampleDir = share.GetRootDirectoryReference(); for (int i = 1; i < logFilePath.Length - 1; i++) { CloudFileDirectory nextLevelDir = sampleDir.GetDirectoryReference("TestLogs"); if (!sampleDir.Exists()) { sampleDir.Create(); } sampleDir = nextLevelDir; } CloudFile file = sampleDir.GetFileReference(logFilePath[logFilePath.Length - 1]); string writenLineContent = ""; if (file.Exists()) { if (writeWay == WriteWay.Cover) { } else if (writeWay == WriteWay.Append) { writenLineContent = file.DownloadTextAsync().Result; } } file.UploadText(writenLineContent + writeLogLine + "\n"); }
public void GetCopyStateWithSAS() { string destShareName = Utility.GenNameString("destshare"); CloudFileShare destShare = fileUtil.EnsureFileShareExists(destShareName); try { string fileName = Utility.GenNameString("DestFile"); StorageFile.CloudFile destFile = fileUtil.GetFileReference(destShare.GetRootDirectoryReference(), fileName); object destContext; if (lang == Language.PowerShell) { destContext = PowerShellAgent.GetStorageContext(StorageAccount.ToString(true)); } else { destContext = NodeJSAgent.GetStorageContext(StorageAccount.ToString(true)); } string bigBlobUri = Test.Data.Get("BigBlobUri"); Test.Assert(CommandAgent.StartFileCopy(bigBlobUri, destShareName, fileName, destContext), "Copy to file should succeed."); string sasToken = destShare.GetSharedAccessSignature(new SharedAccessFilePolicy() { Permissions = SharedAccessFilePermissions.Read, SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddHours(1) }); CommandAgent.SetStorageContextWithSASToken(StorageAccount.Credentials.AccountName, sasToken); Test.Assert(CommandAgent.GetFileCopyState(destShareName, fileName, destContext), "Get copy state with sas token should succeed."); string copyId = null; if (lang == Language.NodeJS) { copyId = ((JObject)CommandAgent.Output[0]["copy"])["id"].ToString(); } NodeJSAgent.AgentConfig.ConnectionString = StorageAccount.ToString(true); Test.Assert(CommandAgent.StopFileCopy(destFile, copyId), "Stop file copy should succeed."); } finally { fileUtil.DeleteFileShareIfExists(destShareName); } }
public static CloudFileDirectory getAssetDir(CloudStorageAccount _storageAccount, String UserName, String assetType) { CloudFileClient fileClient = _storageAccount.CreateCloudFileClient(); CloudFileShare share = fileClient.GetShareReference("techmervisionuserimages"); if (!share.Exists()) { throw new Exception("User Image Share Unavailable."); } CloudFileDirectory rootDir = share.GetRootDirectoryReference(); CloudFileDirectory userDir = getDirByName(rootDir, UserName); CloudFileDirectory assetDir = getDirByName(userDir, assetType); return(assetDir); }
public static async Task <List <IListFileItem> > ListFilesAndDirsAsync(string account, string key, string share) { CloudFileShare shareRef = Get(account, key, share); FileContinuationToken continuationToken = null; List <IListFileItem> results = new List <IListFileItem>(); do { var response = await shareRef.GetRootDirectoryReference().ListFilesAndDirectoriesSegmentedAsync(continuationToken); continuationToken = response.ContinuationToken; results.AddRange(response.Results); }while (continuationToken != null); return(results); }
private CloudFileDirectory GetRootDirectory() { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(options.ConnectionString); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare share = fileClient.GetShareReference("entries"); if (!share.Exists()) { throw Ensure.Exception.InvalidOperation("Missing file share."); } CloudFileDirectory rootDir = share.GetRootDirectoryReference(); return(rootDir); }
public void StopFileCopyWithInvalidCredential() { string shareName = Utility.GenNameString("share"); CloudFileShare share = fileUtil.EnsureFileShareExists(shareName); try { StorageFile.CloudFile file = fileUtil.CreateFile(share.GetRootDirectoryReference(), Utility.GenNameString("")); Test.Assert(!CommandAgent.StopFileCopy(shareName, file.Name, Guid.NewGuid().ToString()), "Stop file copy with invalid credential should fail."); CheckErrorMessage(); } finally { fileUtil.DeleteFileShareIfExists(shareName); } }
public static void Uploadfile() { string StorageString = ConfigurationSettings.AppSettings.Get("AzureStorageAccount"); CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(StorageString); CloudFileClient cloudfileClient = cloudStorageAccount.CreateCloudFileClient(); CloudFileShare share = cloudfileClient.GetShareReference("test"); share.CreateIfNotExists(); CloudFile sourceFile = share.GetRootDirectoryReference().GetFileReference("test.txt"); using (var filestream = System.IO.File.OpenRead(@"D:\test.txt")) { sourceFile.UploadFromStream(filestream); } }
public static void DownloadFile(string path) { var value = path; if (value != null && value != "") { string[] fname = value.Split('/'); string foldername = ""; int count = 0; for (int i = fname.Length - 2; i <= (fname.Length - 2); i--) { if (i != 0) { count++; foldername += fname[count] + '/'; } else { break; } } //get share name string ShareName = fname[0].ToLower(); CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); CloudFileClient cloudFileClient = cloudStorageAccount.CreateCloudFileClient(); CloudFileShare cloudFileShare = cloudFileClient.GetShareReference(ShareName); CloudFileDirectory root = cloudFileShare.GetRootDirectoryReference(); CloudFileDirectory directoryToUse = root.GetDirectoryReference(foldername); CloudFile cloudFile = directoryToUse.GetFileReference(fname.Last()); //checking for file exist on directory or not if (directoryToUse.Exists()) { //if yes store it to local path of your project with given file name var memStream = new MemoryStream(); using (var fileStream = System.IO.File.OpenWrite(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Download.pdf"))) { cloudFile.DownloadToStream(memStream); } Console.WriteLine("File saved in {0}", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Download.pdf")); Console.ReadLine(); } else { Console.WriteLine("File not exist on Azure."); } } }
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 async Task <bool> UploadImageToAzureStorage(HttpPostedFileBase image /*, HttpRequest request*/) { try { //Console.WriteLine("request.Files.Count: " + request.Files.Count); Console.WriteLine("image==null: " + image == null); Console.WriteLine(image == null ? "" : "image.ContentLength: " + image.ContentLength + ", image.ContentType: " + image.ContentType); if (/*request.Files != null && */ image != null && image.ContentLength != 0) { string connectionString = ConfigurationManager.ConnectionStrings["AzureStorageConnectionString"].ConnectionString; //Connect to Azure CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); // Create a reference to the file client. CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); // Get a reference to the file share we created previously. CloudFileShare share = fileClient.GetShareReference("organizationfiles"); await share.CreateIfNotExistsAsync(); if (share.Exists()) { // Generate a SAS for a file in the share CloudFileDirectory rootDir = share.GetRootDirectoryReference(); CloudFileDirectory cloudFileDirectory = rootDir.GetDirectoryReference("organizationlogos"); await cloudFileDirectory.CreateIfNotExistsAsync(); CloudFile cloudFile = cloudFileDirectory.GetFileReference(image.FileName); Stream fileStream = image.InputStream; cloudFile.UploadFromStream(fileStream); fileStream.Dispose(); } } return(true); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); //throw ex; return(false); } }
static void Main(string[] args) { string accountname = "xxx"; string accountkey = "xxxxxxx"; CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(accountname, accountkey), true); // Create a CloudFileClient object for credentialed access to Azure Files. CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); // Get a reference to the file share. CloudFileShare share = fileClient.GetShareReference("s66"); //if fileshare does not exist, create it. share.CreateIfNotExists(); if (share.Exists()) { // Get a reference to the root directory for the share. CloudFileDirectory rootDir = share.GetRootDirectoryReference(); // Get a reference to the directory. CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("CustomLogs"); //if the directory does not exist, create it. sampleDir.CreateIfNotExists(); if (sampleDir.Exists()) { // Get a reference to the file. CloudFile file = sampleDir.GetFileReference("Log1.txt"); // if the file exists, read the content of the file. if (file.Exists()) { // Write the contents of the file to the console window. Console.WriteLine(file.DownloadTextAsync().Result); } //if the file does not exist, create it with size == 500bytes else { file.Create(500); } } } Console.WriteLine("--file share test--"); Console.ReadLine(); }
private async Task <T> AccessToFileAsync <T>(string filePath, Func <CloudFile, Task <T> > delFunction) { var azureFile = AzureFilePath.FromFilePath(filePath); // Get a reference to the file share we created previously. CloudFileShare share = fileClient.GetShareReference(azureFile.ShareReference); // Ensure that the share exists. if (true || await share.ExistsAsync().ConfigureAwait(false)) //Obviamos esta comprobación porque puede que no se tenga privilegios suficientes { // Get a reference to the root directory for the share. CloudFileDirectory rootDir = share.GetRootDirectoryReference(); // Get a reference to the directory we created previously. if (azureFile.Folders.Any()) { CloudFileDirectory sampleDir = rootDir.GetDirectoryReference(azureFile.Folders[0]); if (!sampleDir.Exists()) { throw new Exception("Incorrect route path."); } for (int i = 1; i < azureFile.Folders.Count; i++) { sampleDir = sampleDir.GetDirectoryReference(azureFile.Folders[i]); if (!sampleDir.Exists()) { throw new Exception("Incorrect route path."); } } CloudFile file = sampleDir.GetFileReference(azureFile.FileName); // Ensure that the file exists. return(await delFunction(file).ConfigureAwait(false)); } else { CloudFile file = rootDir.GetFileReference(azureFile.FileName); // Ensure that the file exists. return(await delFunction(file).ConfigureAwait(false)); } } else { throw new Exception("Share not found."); } }
public override void ExecuteCmdlet() { if (String.IsNullOrEmpty(ShareName)) { return; } CloudFileShare fileShare = null; CloudFile file = null; if (null != this.File) { file = this.File; fileShare = this.File.Share; } else { string[] path = NamingUtil.ValidatePath(this.Path, true); fileShare = Channel.GetShareReference(this.ShareName); file = fileShare.GetRootDirectoryReference().GetFileReferenceByPath(path); } SharedAccessFilePolicy accessPolicy = new SharedAccessFilePolicy(); bool shouldSetExpiryTime = SasTokenHelper.ValidateShareAccessPolicy( Channel, fileShare.Name, accessPolicyIdentifier, !string.IsNullOrEmpty(this.Permission), this.StartTime.HasValue, this.ExpiryTime.HasValue); SetupAccessPolicy(accessPolicy, shouldSetExpiryTime); string sasToken = file.GetSharedAccessSignature(accessPolicy, null, accessPolicyIdentifier, Protocol, Util.SetupIPAddressOrRangeForSAS(IPAddressOrRange)); if (FullUri) { string fullUri = SasTokenHelper.GetFullUriWithSASToken(file.SnapshotQualifiedUri.AbsoluteUri.ToString(), sasToken); WriteObject(fullUri); } else { WriteObject(sasToken); } }
public void WriteFilesIntoFileService() { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_configuration.ReadKeyFromFilePath(Constants.ConnectionStringPathKey)); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare fileShare = fileClient.GetShareReference("h2h"); if (Task.Run(async() => await fileShare.ExistsAsync()).Result) { string policyName = "DemoPolicy" + new Random().Next(50); FileSharePermissions fileSharePermissions = Task.Run(async() => await fileShare.GetPermissionsAsync()).Result; // define policy SharedAccessFilePolicy sharedAccessFilePolicy = new SharedAccessFilePolicy() { SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1), //Permissions = SharedAccessFilePermissions.Read Permissions = SharedAccessFilePermissions.Write }; fileSharePermissions.SharedAccessPolicies.Add(policyName, sharedAccessFilePolicy); // set permissions of file share Task.Run(async() => await fileShare.SetPermissionsAsync(fileSharePermissions)); // generate SAS token based on policy and use to create a new file CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference(); if (Task.Run(async() => await rootDirectory.ExistsAsync()).Result) { CloudFileDirectory customDirectory = rootDirectory.GetDirectoryReference("Output"); if (Task.Run(async() => await customDirectory.ExistsAsync()).Result) { CloudFile file = customDirectory.GetFileReference(_globalNotesPdf.Name); string sasToken = file.GetSharedAccessSignature(null, policyName); //generate URL of file with SAS token Uri fileSASUrl = new Uri(file.StorageUri.PrimaryUri.ToString() + sasToken); CloudFile newFile = new CloudFile(fileSASUrl); Task.Run(async() => await newFile.UploadFromFileAsync(_globalNotesPdf.FullName)); } } } }
public void Copy_a_file_to_a_blob() { // Parse the connection string for the storage account. 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(); // Create a new file share, if it does not already exist. CloudFileShare share = fileClient.GetShareReference("sample-share"); share.CreateIfNotExists(); // Create a new file in the root directory. CloudFile sourceFile = share.GetRootDirectoryReference().GetFileReference("sample-file.txt"); sourceFile.UploadText("A sample file in the root directory."); // Get a reference to the blob to which the file will be copied. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("sample-container"); container.CreateIfNotExists(); CloudBlockBlob destBlob = container.GetBlockBlobReference("sample-blob.txt"); // Create a SAS for the file that's valid for 24 hours. // Note that when you are copying a file to a blob, or a blob to a file, you must use a SAS // to authenticate access to the source object, even if you are copying within the same // storage account. string fileSas = sourceFile.GetSharedAccessSignature(new SharedAccessFilePolicy() { // Only read permissions are required for the source file. Permissions = SharedAccessFilePermissions.Read, SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24) }); // Construct the URI to the source file, including the SAS token. Uri fileSasUri = new Uri(sourceFile.StorageUri.PrimaryUri.ToString() + fileSas); // Copy the file to the blob. destBlob.StartCopy(fileSasUri); // Write the contents of the file to the console window. Console.WriteLine("Source file contents: {0}", sourceFile.DownloadText()); Console.WriteLine("Destination blob contents: {0}", destBlob.DownloadText()); }
public static void CreatePBFile(CloudStorageAccount storageAccount, string filename, byte[] feed) { // 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("gtfsrt"); share.CreateIfNotExists(); var rootDir = share.GetRootDirectoryReference(); using (var stream = new MemoryStream(feed, writable: false)) { rootDir.GetFileReference(filename).UploadFromStream(stream);//.UploadFromByteArray(feed,); } }
public async Task Test_Azure_File_Storage_Upload() { CloudFileShare shareReference = this._cloudFileClient.GetShareReference("test232323"); bool created = await shareReference.CreateIfNotExistsAsync(); Check.That(created).IsFalse(); var root = shareReference.GetRootDirectoryReference(); var file = root.GetFileReference("microsoft-logo.png"); string filePath = System.IO.Path.Combine(@"C:\Users\jindev\Desktop", file.Name); await file.UploadFromFileAsync(filePath); }
public AzureSession(string connectionString, string shareName, string systemDir, int waitForLockMilliseconds = 5000, bool optimisticLocking = true, bool enableCache = true, CacheEnum objectCachingDefaultPolicy = CacheEnum.Yes) : base(systemDir, waitForLockMilliseconds, optimisticLocking, enableCache, objectCachingDefaultPolicy) { m_cloudStorageAccount = CloudStorageAccount.Parse(connectionString); if (Path.IsPathRooted(systemDir) == false) SystemDirectory = systemDir; m_shareName = shareName; m_cloudFileClient = m_cloudStorageAccount.CreateCloudFileClient(); m_cloudShare = m_cloudFileClient.GetShareReference(shareName); if (m_cloudShare.Exists()) { m_rootDir = m_cloudShare.GetRootDirectoryReference(); m_databaseDir = m_rootDir.GetDirectoryReference(systemDir); m_databaseDir.CreateIfNotExists(); } }
protected override void GenerateDataImp(DMLibDataInfo dataInfo) { fileHelper.CreateShare(this.shareName); using (TemporaryTestFolder localTemp = new TemporaryTestFolder(this.tempFolder)) { CloudFileDirectory rootCloudFileDir = this.fileHelper.GetDirReference(this.shareName, dataInfo.RootPath); this.GenerateDir(dataInfo.RootNode, rootCloudFileDir, this.tempFolder); if (dataInfo.IsFileShareSnapshot) { CloudFileShare baseShare = this.fileHelper.FileClient.GetShareReference(this.shareName); this.snapshotTime = baseShare.SnapshotAsync().Result.SnapshotTime; CloudFileHelper.CleanupFileDirectory(baseShare.GetRootDirectoryReference()); } } }
internal static async Task <string> ReadFileContents(CloudFileShare fileShare, string path) { var rootDirectory = fileShare.GetRootDirectoryReference(); var file = rootDirectory.GetFileReference(path); string content; using (var stream = new MemoryStream()) { await file.DownloadToStreamAsync(stream); content = Encoding.UTF8.GetString(stream.ToArray()); } return(content); }
public HttpResponseMessage Post(string shareName, string path, string fileName) { var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting("StorageConnectionString")); CloudFileClient cloudFileClient = cloudStorageAccount.CreateCloudFileClient(); CloudFileShare share = cloudFileClient.GetShareReference(shareName); try { if (share.Exists()) { CloudFileDirectory rootDir = share.GetRootDirectoryReference(); CloudFileDirectory targetDir = rootDir.GetDirectoryReference(path); CloudFile cloudFile = targetDir.GetFileReference(fileName); Stream fileStream = postedFile.InputStream; cloudFile.UploadFromStream(fileStream); fileStream.Dispose(); return(Request.CreateResponse(HttpStatusCode.Created)); } else { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } } catch (Exception ex) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message)); } } } else { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } return(Request.CreateResponse(HttpStatusCode.InternalServerError)); }
public CloudFile getFIle(String path, String fileName) { CloudFileClient fileClient = this.storageAccount.CreateCloudFileClient(); CloudFileShare fileShare = fileClient.GetShareReference(this._appSettings.AzureFIleStoreName); if (fileShare.Exists()) { CloudFileDirectory root = fileShare.GetRootDirectoryReference(); CloudFileDirectory folder = root.GetDirectoryReference(path); CloudFile file = folder.GetFileReference(fileName); return(file); } else { throw new Exception("File Share does not exists"); } }
protected bool ShareIsEmpty(CloudFileShare share) { try { FileContinuationToken fileToken = new FileContinuationToken(); using (IEnumerator <IListFileItem> listedFiles = share.GetRootDirectoryReference() .ListFilesAndDirectoriesSegmentedAsync(1, fileToken, RequestOptions, OperationContext).Result .Results.GetEnumerator()) { return(!(listedFiles.MoveNext() && listedFiles.Current != null)); } } catch (Exception) { return(false); } }
/* * GetAppendBlobReference is removed from Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer * So we cannot release the log function based on the append function from Microsoft.WindowsAzure.Storage. * stackoverflow: https://stackoverflow.com/questions/48411359/getappendblobreference-is-removed-from-microsoft-windowsazure-storage-blob-cloud */ public static void MainMethod() { string accountName = ""; string accountKey = ""; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(string.Format(@"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", accountName, accountKey)); // 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("logs"); // If the share does not exist, create it. if (!share.Exists()) { share.Create(); } // 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("TestLogs"); if (!sampleDir.Exists()) { sampleDir.Create(); } // 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); file.UploadText("12345"); Console.WriteLine(file.DownloadTextAsync().Result); } else { file.UploadText("1234"); } Console.ReadKey(); }
// Assumes the images are in subfolders at the root of the fileshare public static Uri GetFileURL(string path, CloudFileShare share) { CloudFileDirectory rootDir = null; CloudFileDirectory dir = null; CloudFile file = null; string[] splitPath = path.Split('/'); try { rootDir = share.GetRootDirectoryReference(); dir = rootDir.GetDirectoryReference(splitPath[0]); } catch (Exception e) { Console.WriteLine($"\n{e.GetType().Name}: Error accessing directory."); throw; } if (dir != null) { try { file = dir.GetFileReference(splitPath[1]); if (file.Exists()) { Console.WriteLine($"File '{file.Name}' successfully retrieved."); } } catch (Exception e) { Console.WriteLine($"\n{e.GetType().Name}: File '{file.Name}' could not be retrieved."); throw; } } Uri URI; Uri.TryCreate(file.Uri.ToString() + SAS_TOKEN, UriKind.Absolute, out URI); return(URI); }
public static void OutputLogContent(params string[] logFilePath) { if (logFilePath.Length < 2) { Console.WriteLine(invalidExistLogFilePath); return; } CloudStorageAccount storageAccount = CloudStorageAccount.Parse( string.Format(@"DefaultEndpointsProtocol=https;AccountName={0}; AccountKey={1};EndpointSuffix=core.windows.net", Constant.LOGGER_ACCOUNT_NAME, Constant.Instance.StorageAccountKey)); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare share = fileClient.GetShareReference(logFilePath[0]); if (!share.Exists()) { Console.WriteLine(invalidExistLogFilePath); return; } CloudFileDirectory sampleDir = share.GetRootDirectoryReference(); for (int i = 1; i < logFilePath.Length - 1; i++) { CloudFileDirectory nextLevelDir = sampleDir.GetDirectoryReference(logFilePath[i]); if (!sampleDir.Exists()) { Console.WriteLine(invalidExistLogFilePath); return; } sampleDir = nextLevelDir; } CloudFile file = sampleDir.GetFileReference(logFilePath[logFilePath.Length - 1]); if (file.Exists()) { Console.WriteLine(file.DownloadTextAsync().Result); } else { Console.WriteLine(); } }
public async Task <IActionResult> Create([Bind("Id,Name,Description,Uri,TypeId,CreatedDate,DataFile")] SampleDataSource sampleDataSource) { if (ModelState.IsValid) { if (sampleDataSource == null || sampleDataSource.DataFile == null || sampleDataSource.DataFile.Length == 0) { return(Content("file not selected")); } CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_configuration.GetConnectionString("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 cloudFileShare = fileClient.GetShareReference("samples"); await cloudFileShare.CreateIfNotExistsAsync(); CloudFileDirectory cloudFileDirectory = cloudFileShare.GetRootDirectoryReference(); CloudFile cloudFile = cloudFileDirectory.GetFileReference(sampleDataSource.DataFile.FileName); await cloudFile.DeleteIfExistsAsync(); using (var stream = new MemoryStream()) { await sampleDataSource.DataFile.CopyToAsync(stream); stream.Seek(0, SeekOrigin.Begin); await cloudFile.UploadFromStreamAsync(stream); } sampleDataSource.Uri = cloudFile.Uri.ToString(); sampleDataSource.CreatedBy = GetCurrentUserAsync().Result; sampleDataSource.CreatedDate = System.DateTime.Now; _context.Add(sampleDataSource); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewBag.AvailableDataConnectors = _context.DataSourceConnectors.ToList(); return(View(sampleDataSource)); }
public static void SaveDocumentToAzure(XDocument doc, Configuration config, string folderDateTime) { if (IsNullOrEmpty(config.StorageAccountName) || IsNullOrEmpty(config.StorageAccountKey) || IsNullOrEmpty(config.StorageAccountShareReference) || IsNullOrEmpty(config.StorageAccountCatalogDirectoryReference)) { return; } StorageCredentials cred = new StorageCredentials(config.StorageAccountName, config.StorageAccountKey); CloudStorageAccount storageAccount = new CloudStorageAccount(cred, true); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare share = fileClient.GetShareReference(config.StorageAccountShareReference); share.CreateIfNotExists(); string dirPath = Path.Combine(config.ResourcesRootPath, folderDateTime); CloudFileDirectory root = share.GetRootDirectoryReference(); CloudFileDirectory dir = root.GetDirectoryReference(dirPath); dir.CreateIfNotExists(); CloudFile cloudFile = dir.GetFileReference("Resources.xml"); using (MemoryStream stream = new MemoryStream()) { XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = false, Indent = true }; using (XmlWriter xw = XmlWriter.Create(stream, xws)) { doc.WriteTo(xw); } stream.Position = 0; cloudFile.UploadFromStream(stream); } }
public void DownloadFileFromShareSnapshot_dir() { string shareName = CloudFileUtil.GenerateUniqueFileShareName(); string dirName = CloudFileUtil.GenerateUniqueDirectoryName(); string fileName = CloudFileUtil.GenerateUniqueFileName(); try { CloudFileShare share = fileUtil.EnsureFileShareExists(shareName); CloudFileShare shareSnapshot1 = share.Snapshot(); CloudFileDirectory dir = fileUtil.EnsureDirectoryExists(share, dirName); CloudFile file = fileUtil.CreateFile(dir, fileName); CloudFileShare shareSnapshot2 = share.Snapshot(); file.Delete(); dir.Delete(); //Get File content string StorageConnectionString = Test.Data.Get("StorageConnectionString"); Test.Assert((CommandAgent as PowerShellAgent).InvokePSScript(string.Format(",(New-AzureStorageContext -ConnectionString \"{5}\" | Get-AzureStorageShare -Name {0} -SnapshotTime \"{1}\").GetRootDirectoryReference().GetDirectoryReference(\"{4}\") | Get-AzureStorageFileContent -Path {2} -Destination {3} -Force", shareName, shareSnapshot2.SnapshotTime.Value, fileName, fileName, dirName, StorageConnectionString)), string.Format("Download File {0} from share snapshot {1}, {2} should success.", dirName + "\\" + fileName, shareName, shareSnapshot2.SnapshotTime.Value)); //validate MD5 CloudFile file2 = shareSnapshot2.GetRootDirectoryReference().GetDirectoryReference(dirName).GetFileReference(fileName); file2.FetchAttributes(); Test.Assert(file2.Properties.ContentMD5 == FileUtil.GetFileContentMD5(fileName), "Expected MD5: {0}, real MD5: {1}", file2.Properties.ContentMD5, FileUtil.GetFileContentMD5(fileName)); } finally { try { fileUtil.DeleteFileShareIfExists(shareName); } catch (Exception e) { Test.Warn("Unexpected exception when cleanup file share {0}: {1}", shareName, e); } } }
public CloudFileDirectory GetFileShare(string dirname, bool createIfDoesntExist = false) { var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["storagekey"]); var fileClient = storageAccount.CreateCloudFileClient(); var folderPath = dirname.Split('\\'); //ex: fileupload\uploads CloudFileShare share = fileClient.GetShareReference(folderPath[0]); CloudFileDirectory directory = null; if (!share.Exists()) { throw new InvalidOperationException(string.Format("{0}share doesnt exists.", folderPath[0])); } directory = share.GetRootDirectoryReference(); if (!createIfDoesntExist) { //Avoid loop if directory neednt be created if (folderPath.Length > 1) { directory = directory.GetDirectoryReference(string.Join("/", folderPath.Skip(1))); } } else { //Loop if directories need to be checked for existance for (int i = 1; i < folderPath.Length && directory.Exists(); i++) { directory = directory.GetDirectoryReference(folderPath[i]); //Create if directory doesnt exists if (!directory.Exists()) { directory.Create(); } } } if (directory.Exists()) { return(directory); } throw new InvalidOperationException(string.Format("{0} directory doesnt exists.", directory.Name)); }