public async Task DownloadFile()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AzureStorageAccount);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();

            FileContinuationToken token = null;
            ShareResultSegment    shareResultSegment = await fileClient.ListSharesSegmentedAsync("Pat", token);

            foreach (CloudFileShare share in shareResultSegment.Results)
            {
                CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                CloudFileDirectory sampleDir = rootDir.GetDirectoryReference(DateTime.Now.ToString("yyyyMMdd"));
                if (await sampleDir.ExistsAsync())
                {
                    do
                    {
                        FileResultSegment resultSegment = await sampleDir.ListFilesAndDirectoriesSegmentedAsync(token);

                        token = resultSegment.ContinuationToken;

                        List <IListFileItem> listedFileItems = new List <IListFileItem>();

                        foreach (IListFileItem listResultItem in resultSegment.Results)
                        {
                            var cloudFile = sampleDir.GetFileReference(listResultItem.Uri.ToString());
                            Console.WriteLine(cloudFile.Uri.ToString());
                            //await cloudFile.DownloadToFileAsync(cloudFile.Uri.ToString(), FileMode.Create);
                        }
                    }while (token != null);
                }
            }
        }
Esempio n. 2
0
        private static async void GetListOfFilesSegmented()
        {
            var            client         = cloudStorageAccount.CreateCloudFileClient();
            CloudFileShare cloudFileShare = client.GetShareReference("trial");

            if (cloudFileShare != null && await cloudFileShare.ExistsAsync())
            {
                CloudFileDirectory cloudFileDirectory = cloudFileShare.GetRootDirectoryReference();
                if (cloudFileDirectory != null && await cloudFileDirectory.ExistsAsync())
                {
                    FileContinuationToken fileContinuationToken = new FileContinuationToken();

                    do
                    {
                        FileResultSegment fileResultSegment = await cloudFileDirectory.ListFilesAndDirectoriesSegmentedAsync(fileContinuationToken);

                        foreach (CloudFile result in fileResultSegment.Results)
                        {
                            Console.WriteLine($"{result.Name} - {result.Properties.Length} bytes");
                        }
                        fileContinuationToken = fileResultSegment.ContinuationToken;
                    } while (fileContinuationToken != null);
                }
                else
                {
                    Console.WriteLine("Cloud file directory is null");
                }
            }
            else
            {
                Console.WriteLine("Cloud file share is null");
            }
        }
Esempio n. 3
0
        public void CopyDirectoryTest(string directoryName, string[] sourcePath, string[] targetPath)
        {
            // Arrange
            CloudFileDirectory sourceCloudFileDirectory = _cloudFileShare.GetDirectoryReference(directoryName, sourcePath);

            int expectedChildCount = TaskUtilities
                                     .ExecuteSync(sourceCloudFileDirectory.ListFilesAndDirectoriesSegmentedAsync(new FileContinuationToken()))
                                     .Results
                                     .Count();

            // Act
            _fileContainer.CopyDirectory(directoryName, sourcePath, targetPath);

            CloudFileDirectory targetCloudFileDirectory = _cloudFileShare.GetDirectoryReference(directoryName, targetPath);

            bool result = TaskUtilities.ExecuteSync(targetCloudFileDirectory.ExistsAsync());

            int actualChildCount = TaskUtilities
                                   .ExecuteSync(targetCloudFileDirectory.ListFilesAndDirectoriesSegmentedAsync(new FileContinuationToken()))
                                   .Results
                                   .Count();

            // Assert
            Assert.IsTrue(result);

            Assert.AreEqual(expectedChildCount, actualChildCount);
        }
        public async Task Test_Azure_File_Storage_Root_Directory_FilesAndDirectories()
        {
            Check.That(this._storageAccountName).IsNotEmpty();

            Check.That(this._storageKey).IsNotEmpty();

            CloudFileShare client = this._cloudFileClient.GetShareReference("demofileshare01");

            CloudFileDirectory rootDirectory = client.GetRootDirectoryReference();

            bool isRootDirectoryExists = await rootDirectory.ExistsAsync();

            FileContinuationToken fct = null;

            List <FileResultSegment> fileResultSegment = new List <FileResultSegment>();

            do
            {
                var result = await rootDirectory.ListFilesAndDirectoriesSegmentedAsync(fct);

                fct = result.ContinuationToken;

                fileResultSegment.Add(result);
            } while (fct != null);
        }
Esempio n. 5
0
        private static async Task refineLogs()
        {
            StorageConnection conn             = new StorageConnection();
            string            connectionString = "DefaultEndpointsProtocol=https;AccountName=storageaccountgepte86f5;AccountKey=tWMNBa2qlEgVEt6cOnmDbYdsJ0igQmnmJzcJx2d5lxuf0y1iYyMEbkM9n8KlUfPvlSF9Mtc3KE5CrhAWy/fpAg==;EndpointSuffix=core.windows.net";

            conn.config = new MyConfig()
            {
                StorageConnection = connectionString, Container = "techathoninput"
            };
            conn.Connect();
            CloudStorageAccount sAccount   = conn.storageAccount;
            CloudFileClient     fileClient = sAccount.CreateCloudFileClient();

            CloudFileShare share = fileClient.GetShareReference("scheduledfileconverter91d0");

            if (await share.ExistsAsync())
            {
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();
                CloudFileDirectory dir     = rootDir.GetDirectoryReference(@"LogFiles/Application/Functions/Function/Function");
                CloudFile          logs    = rootDir.GetFileReference("Logs.txt");
                if (await dir.ExistsAsync())
                {
                    List <IListFileItem>  results = new List <IListFileItem>();
                    FileContinuationToken token   = null;
                    do
                    {
                        FileResultSegment resultSegment = await dir.ListFilesAndDirectoriesSegmentedAsync(token);

                        results.AddRange(resultSegment.Results);
                        token = resultSegment.ContinuationToken;
                    }while (token != null);
                    List <CloudFile> files = new List <CloudFile>();
                    foreach (IListFileItem item in results)
                    {
                        if (item.GetType() == typeof(Microsoft.WindowsAzure.Storage.File.CloudFile))
                        {
                            files.Add((CloudFile)item);
                        }
                    }
                    string name = "";
                    foreach (CloudFile file in files)
                    {
                        name = (string.Compare(name, Path.GetFileNameWithoutExtension(file.Name)) > 0) ? name : Path.GetFileNameWithoutExtension(file.Name);
                    }
                    name += ".log";
                    CloudFile recentFile = dir.GetFileReference(name);
                    string    data       = await recentFile.DownloadTextAsync();

                    string[] lines = data.Split("\n");
                    if (lines.Length < 50)
                    {
                        await logs.UploadTextAsync(data);
                    }
                    else
                    {
                        await logs.UploadTextAsync(string.Join("\n", lines.Skip(lines.Length - 50).ToArray()));
                    }
                }
            }
        }
Esempio n. 6
0
        private CloudFileDirectory CreateDirectory(string fullPath)
        {
            return(Retrier.Retry <CloudFileDirectory>(5, () =>
            {
                var root = this.share.GetRootDirectoryReference();
                var segments = fullPath.Split('\\');
                CloudFileDirectory lastDir = null;
                foreach (var segment in segments)
                {
                    if (lastDir == null)
                    {
                        lastDir = root.GetDirectoryReference(segment);
                    }
                    else
                    {
                        lastDir = lastDir.GetDirectoryReference(segment);
                    }

                    if (!lastDir.ExistsAsync().Result)
                    {
                        lastDir.CreateAsync().Wait();
                    }
                }

                return lastDir;
            }));
        }
Esempio n. 7
0
        /// <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);
        }
Esempio n. 8
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);
                        }
                    }
                }
            }
        }
        public async static Task <bool> RemoveFileFromCloudFile(string connectionString, string fileFolder, string filename)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                connectionString);

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            // Get a reference to the file share we created previously.
            CloudFileShare     share   = fileClient.GetShareReference(fileFolder);
            CloudFileDirectory userDir = null;

            // Ensure that the share exists.
            if (await share.ExistsAsync())
            {
                // Get a reference to the root directory for the share.
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();
                // Get a reference to the directory we created previously.
                userDir = rootDir.GetDirectoryReference("audio");
                // Ensure that the directory exists.
                if (await userDir.ExistsAsync())
                {
                    CloudFile removefile = userDir.GetFileReference(filename);
                    await removefile.DeleteIfExistsAsync();

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
        private async Task CreateRecursiveIfNotExistsAsync(CloudFileDirectory directory)
        {
            if (!await directory.ExistsAsync())
            {
                await CreateRecursiveIfNotExistsAsync(directory.Parent);

                await directory.CreateAsync();
            }
        }
Esempio n. 11
0
        private async Task CreateRecursiveIfNotExists(CloudFileDirectory directory)
        {
            bool directoryExists = await directory.ExistsAsync();

            if (!directoryExists)
            {
                await CreateRecursiveIfNotExists(directory.Parent);

                await directory.CreateAsync();
            }
        }
Esempio n. 12
0
        public async Task <IFolder> GetFolderWithIdAysnc(string id)
        {
            var folder = new CloudFileDirectory(new Uri(id), fileShare.ServiceClient.Credentials);

            if (await folder.ExistsAsync())
            {
                return(new DriveFolder(id, folder.Name, Root, DriveType));
            }

            return(null);
        }
Esempio n. 13
0
        public void CreateDirectoryTest(string directoryName, string[] path)
        {
            // Act
            _fileContainer.CreateDirectory(directoryName, path);

            CloudFileDirectory cloudFileDirectory = _cloudFileShare.GetDirectoryReference(directoryName, path);

            bool result = TaskUtilities.ExecuteSync(cloudFileDirectory.ExistsAsync());

            // Assert
            Assert.IsTrue(result);
        }
Esempio n. 14
0
        public void UploadFileStream(Stream stream, string connectionString, FileInfo outputFile)
        {
            connectionString.ThrowExceptionIfNullOrEmpty();

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            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("HyperArchive");
                    if (Task.Run(async() => await customDirectory.ExistsAsync()).Result)
                    {
                        CloudFile file     = customDirectory.GetFileReference(outputFile.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);

                        var taskResult = Task.Run(async() => await newFile.UploadFromStreamAsync(stream));
                    }
                }
            }
        }
Esempio n. 15
0
        private void CreateParentDirectoryIfNotExists(CloudFile file)
        {
            FileRequestOptions fileRequestOptions = Transfer_RequestOptions.DefaultFileRequestOptions;
            CloudFileDirectory parent             = file.Parent;

            if (!this.IsLastDirEqualsOrSubDirOf(parent))
            {
                if (!parent.ExistsAsync(fileRequestOptions, null).Result)
                {
                    CreateCloudFileDirectoryRecursively(parent);
                }

                this.lastAzureFileDirectory = parent;
            }
        }
Esempio n. 16
0
        /// <inheritdoc />
        public bool ExistsDirectory(string directoryName, string[] path)
        {
            #region validation

            if (string.IsNullOrEmpty(directoryName))
            {
                throw new ArgumentNullException(nameof(directoryName));
            }

            #endregion

            CloudFileDirectory cloudFileDirectory = CloudFileShare.GetDirectoryReference(directoryName, path);

            return(TaskUtilities.ExecuteSync(cloudFileDirectory.ExistsAsync()));
        }
        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);
        }
Esempio n. 18
0
        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));
                    }
                }
            }
        }
Esempio n. 19
0
        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;
        }
Esempio n. 20
0
        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);
                }
            }
        }
Esempio n. 21
0
        /// <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()));
        }
Esempio n. 22
0
        public async Task <IEnumerable <CloudFile> > GetFiles()
        {
            do
            {
                List <CloudFile> cloudFiles = new List <CloudFile>();

                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AzureStorageAccount);
                CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();

                FileContinuationToken token = null;
                ShareResultSegment    shareResultSegment = await fileClient.ListSharesSegmentedAsync("Pat", token);

                foreach (CloudFileShare share in shareResultSegment.Results)
                {
                    CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                    CloudFileDirectory sampleDir = rootDir.GetDirectoryReference(DateTime.Now.ToString("yyyyMMdd"));
                    if (await sampleDir.ExistsAsync())                            //Console.WriteLine(cloudFile.Uri.ToString()+'\n');
                    {
                        do
                        {
                            FileResultSegment resultSegment = await sampleDir.ListFilesAndDirectoriesSegmentedAsync(token);

                            token = resultSegment.ContinuationToken;

                            List <IListFileItem> listedFileItems = new List <IListFileItem>();

                            foreach (IListFileItem listResultItem in resultSegment.Results)
                            {
                                CloudFile cloudFile = sampleDir.GetFileReference(listResultItem.Uri.ToString());
                                cloudFiles.Add(cloudFile);
                            }
                        }while (token != null);
                    }
                }

                return(cloudFiles);
            } while (true);
        }
Esempio n. 23
0
        /// <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);
        }
Esempio n. 24
0
 private static async void ConnectToAzureFileStorage()
 {
     try
     {
         CloudFileClient cloudFileClient = cloudStorageAccount.CreateCloudFileClient();
         foreach (CloudFileShare fileShare in cloudFileClient.ListShares())
         {
             Console.WriteLine($"{fileShare.Name} - {fileShare.StorageUri}");
             CloudFileDirectory cloudFileDirectory = fileShare.GetRootDirectoryReference();
             if (cloudFileDirectory != null && await cloudFileDirectory.ExistsAsync())
             {
                 foreach (CloudFile fileItem in cloudFileDirectory.ListFilesAndDirectories())
                 {
                     Console.WriteLine($"\t[{fileItem.Name}] - {fileItem?.Properties.Length} bytes");
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
Esempio n. 25
0
        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");
            }
        }
 public static bool Exists(this CloudFileDirectory dir, FileRequestOptions requestOptions = null, OperationContext operationContext = null)
 {
     return(dir.ExistsAsync(requestOptions, operationContext).GetAwaiter().GetResult());
 }
Esempio n. 27
0
 public Task <bool> DirectoryExistsAsync(CloudFileDirectory directory, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
 {
     return(directory.ExistsAsync(options, operationContext, cancellationToken));
 }
Esempio n. 28
0
        static async System.Threading.Tasks.Task Read_FileAsync()
        {
            try
            {
#if DEBUG || DEV
                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile($"appsettings.Development.json", true, true);
#else
                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile($"appsettings.json", true, true);
#endif
                //var builder = new ConfigurationBuilder()
                //                    .SetBasePath(Directory.GetCurrentDirectory())
                //                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

                IConfigurationRoot configuration = builder.Build();

                CloudStorageAccount cuentaAlmacenamiento = CloudStorageAccount.Parse(configuration.GetConnectionString("FileConnectionString"));
                CloudFileClient     clienteArchivos      = cuentaAlmacenamiento.CreateCloudFileClient();
                CloudFileShare      archivoCompartido    = clienteArchivos.GetShareReference("platzifile");

                bool existeFileShare = archivoCompartido.ExistsAsync().GetAwaiter().GetResult();
                //bool existeFileShare = await archivoCompartido.ExistsAsync();
                //.Net Framework no funciona el await con el .ExistsAsync()
                //agregar .GetAwaiter().GetResult()

                if (existeFileShare)
                {
                    CloudFileDirectory carpetaRaiz = archivoCompartido.GetRootDirectoryReference();
                    CloudFileDirectory directorio  = carpetaRaiz.GetDirectoryReference("registros");

                    bool existeDirectorio = directorio.ExistsAsync().GetAwaiter().GetResult();

                    if (existeDirectorio)
                    {
                        CloudFile archivo = directorio.GetFileReference(ARCHIVO_NOMBRE);

                        bool existeArchivo = archivo.ExistsAsync().GetAwaiter().GetResult();

                        if (existeArchivo)
                        {
                            Console.WriteLine($"Escribiendo archivo: {ARCHIVO_NOMBRE}");
                            string x = archivo.DownloadTextAsync().GetAwaiter().GetResult();
                            //string x = await archivo.DownloadTextAsync();
                            Console.WriteLine(x);

                            //Console.WriteLine(archivo.DownloadTextAsync().Result);
                        }
                        else
                        {
                            Console.WriteLine("no se encontro el archivo: logActividades.txt");
                        }
                    }
                    else
                    {
                        Console.WriteLine("no se encontro la carpeta: registros");
                    }
                }
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                Console.ReadLine();
            }
        }
Esempio n. 29
0
 public override Task <bool> ExistsAsync()
 {
     return(_dir.ExistsAsync());
 }
Esempio n. 30
0
        public static async Task <string> UnZip(
            [ActivityTrigger] string name,
            //[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            // Get app settings.
            var destinationStorage            = Environment.GetEnvironmentVariable("DestinationStorageAccount");
            var destinationFileShare          = Environment.GetEnvironmentVariable("DestinationFileShare");
            var sourceStorageConnectionString = Environment.GetEnvironmentVariable("SourceStorageAccount");

            //string name = "test.zip";
            var localZipFile = SetLocalPath(name);

            log.LogInformation($"Blob trigger function Processed blob:{name}");

            // Check whether the connection string can be parsed.
            CloudStorageAccount storageAccount;

            if (CloudStorageAccount.TryParse(sourceStorageConnectionString, out storageAccount))
            {
                // If the connection string is valid, proceed with operations against Blob
                // storage here.
                CloudBlobClient    cloudBlobClient    = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("archived");
                CloudBlockBlob     cloudBlockBlob     = cloudBlobContainer.GetBlockBlobReference(name);
                await cloudBlockBlob.DownloadToFileAsync(localZipFile, FileMode.Create);
            }
            else
            {
                // Otherwise, let the user know that they need to define the environment variable.
                log.LogInformation(
                    "A connection string has not been defined in the system environment variables. " +
                    "Add an environment variable named 'SourceStorageAccount' with your storage " +
                    "connection string as a value.");
            }

            // Parse the connection string for the storage account.
            CloudStorageAccount cloudFileStorageAccount = CloudStorageAccount.Parse(destinationStorage);

            // Create a CloudFileClient object for credentialed access to Azure Files.
            CloudFileClient fileClient = cloudFileStorageAccount.CreateCloudFileClient();

            // Get a reference to the file share.
            CloudFileShare share = fileClient.GetShareReference(destinationFileShare);

            // Get a reference to the root directory for the share.
            CloudFileDirectory destinationDirectory = share.GetRootDirectoryReference();

            // Create file share if it doesn't exist.
            if (!await share.ExistsAsync())
            {
                await share.CreateAsync();
            }

            // Set slash character that is used to differentiate the zip entry from file.
            char slash = '/';

            //var localZipFile = SetLocalPath(name);

            try
            {
                // Filter out only zips.
                if (name.Split('.').Last().ToLower() == "zip")
                {
                    // write the zip to the disk
                    //await myBlob.DownloadToFileAsync(localZipFile, FileMode.Create);

                    // Opening zip file and specifying encoding for entries in the zip.
                    using (ZipArchive archive = ZipFile.Open(localZipFile, 0, Encoding.GetEncoding("ISO-8859-1")))
                    {
                        foreach (ZipArchiveEntry entry in archive.Entries)
                        {
                            /// How to tell if a “ZipArchiveEntry” is directory? - https://stackoverflow.com/questions/40223451/how-to-tell-if-a-ziparchiveentry-is-directory
                            // Check if th zip archive entry is a folder. FullName property for folders end with a "/" and Name property is empty.
                            if (slash == entry.FullName[entry.FullName.Length - 1] && 0 == entry.Name.Length)
                            {
                                // Create a folder if the zip archive entry is a folder.
                                log.LogInformation($"Now processing folder '{entry.FullName}'");
                                CloudFileDirectory EntryDestinationDirectory = destinationDirectory.GetDirectoryReference(entry.FullName);

                                if (!await EntryDestinationDirectory.ExistsAsync())
                                {
                                    await EntryDestinationDirectory.CreateAsync();
                                }
                            }

                            // Check if the zip archive entry is a file.
                            if (slash != entry.FullName.Length - 1 && 0 != entry.Name.Length)
                            {
                                log.LogInformation($"Now processing file '{entry.FullName}'");

                                //// Create buffer that is used to measure the deflated file size
                                byte[] buf  = new byte[1024];
                                int    size = 0;

                                // Open the entry to measure the size
                                using (var fileStream = entry.Open())
                                {
                                    int len;
                                    while ((len = fileStream.Read(buf, 0, buf.Length)) > 0)
                                    {
                                        size += len;
                                    }
                                }

                                //var threadCount = 1;

                                //if (size > 83886080)
                                //{
                                //    threadCount = 4;
                                //}
                                //else
                                //{
                                //    threadCount = 1;

                                //}

                                var requestOptions = new FileRequestOptions()
                                {
                                    ParallelOperationThreadCount = 8
                                };

                                // Open the zip entry for further processing
                                using (var fileStream = entry.Open())
                                {
                                    // Open memory stream by specifying the size
                                    using (var fileMemoryStream = new MemoryStream(size + 1024))
                                    //using (var fileMemoryStream = new MemoryStream())
                                    {
                                        fileStream.CopyTo(fileMemoryStream);
                                        fileMemoryStream.Position = 0;
                                        var destinationFile = destinationDirectory.GetFileReference(entry.FullName);
                                        await destinationFile.UploadFromStreamAsync(fileMemoryStream, null, requestOptions, null);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.LogInformation($"Error! Something went wrong: {ex.Message}, {ex.StackTrace}");
            }

            //log.LogInformation($"cleaning up temp files {localZipFile}");
            //CleanUp(localZipFile);
            log.LogInformation($"Unzip of '{name}' completed!");
            return("OK!");
        }