public string Get(string shareName, string path, string fileName)
        {
            CloudStorageAccount storageAcc = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

            CloudFileClient cloudFileClient = storageAcc.CreateCloudFileClient();
            CloudFileShare  share           = cloudFileClient.GetShareReference(shareName);

            try
            {
                if (share.Exists())
                {
                    CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                    CloudFileDirectory targetDir = rootDir.GetDirectoryReference(path);
                    if (targetDir.Exists())
                    {
                        CloudFile file = targetDir.GetFileReference(fileName);
                        if (file.Exists())
                        {
                            return(file.DownloadTextAsync().Result);
                        }
                        else
                        {
                            return("Invalid file name.");
                        }
                    }
                    else
                    {
                        return("Invalid directory");
                    }
                }
                else
                {
                    return("Invalid share.");
                }
            }
            catch (Exception ex) {
                return(ex.Message);
            }
        }
        public async Task <ActionResult> SelectDataSource(MainViewModel main)
        {
            try
            {
                string fileName = main.SelectedDataSourceName.Split('/').Last();

                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(GetCurrentUserAsync().Result.Id);

                await cloudFileShare.CreateIfNotExistsAsync();

                CloudFileDirectory cloudFileDirectory = cloudFileShare.GetRootDirectoryReference();

                CloudFile cloudFile = cloudFileDirectory.GetFileReference(fileName);

                MemoryStream stream = new MemoryStream();

                await cloudFile.DownloadToStreamAsync(stream);

                stream.Position = 0;

                StreamReader reader = new StreamReader(stream);

                main.RawData = reader.ReadToEnd();

                //Copied raw data to processed data in case user skips the pre-processing/cleansing step
                main.ProcessedData = main.RawData;

                return(PartialView("_DisplayDataSource", main));
            }
            catch (Exception e)
            {
                return(PartialView("_GeneralError", e));
            }
        }
示例#3
0
        /// <summary>
        /// Save an Upload Image
        /// </summary>
        /// <param name="memStreamFileData"></param>
        /// <param name="fileName"></param>

        /*public bool SaveCloudFileStreamUploadImage(MemoryStream memStreamFileData, string fileName)
         * {
         *      string fileSaveDirectory = "";
         *      return SaveCloudFileStream(memStreamFileData, fileSaveDirectory, fileName);
         * }*/
        /// <summary>
        /// Save a file via MemoryStream to the share
        /// </summary>
        /// <param name="memStreamFileData"></param>
        /// <param name="fileName"></param>
        public bool SaveCloudFileStream(MemoryStream memStreamFileData, string fileSaveDirectory, string saveFileName, bool AllowOverWriteExistingFile = false)
        {
            try
            {
                fileSaveDirectory = this.CleanRelativeCloudDirectoryName(fileSaveDirectory);

                CloudStorageAccount cloudStorageAccount = this.GetCloudStorageAccount();
                CloudFileClient     fileClient          = this.GetCloudFileClient(cloudStorageAccount);
                CloudFileShare      share    = this.GetCloudFileShareReference(fileClient);
                CloudFileDirectory  shareDir = this.GetCloudFileDirectory(share, fileSaveDirectory);
                if (!(shareDir != null) && shareDir.Exists())
                {
                    return(false);
                }

                CloudFile cloudfile = shareDir.GetFileReference(saveFileName);
                if (cloudfile.Exists())
                {
                    /// ??? - overwrite?
                    if (AllowOverWriteExistingFile)
                    {
                        return(false);                                  // for now, we can't let this pass!  true;
                    }

                    throw new DuplicateFileException(saveFileName);

                    //ExplodeStaticError(string.Format("{0} [{1}]", "GetCloudFileStream", saveFileName), "File Already Exists!");
                    //return false;
                }

                memStreamFileData.Position = 0;
                cloudfile.UploadFromStream(memStreamFileData);
                return(true);
            }
            catch (Exception oExeption)
            {
                oExeption.Log($"GetCloudFileStream - [{saveFileName}]");
            }
            return(false);
        }
示例#4
0
        public async Task <FileReference> UploadAsync(IFormFile file)
        {
            var storageAccountKey = _configuration[AZURE_KEY];

            if (storageAccountKey == null)
            {
                throw new ArgumentNullException(nameof(storageAccountKey), $"You must set an environment variable for {AZURE_KEY}");
            }

            //Connect to Azure
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccountKey);
            // Create a reference to the file client.
            CloudFileClient cloudFileClient = storageAccount.CreateCloudFileClient();

            // Create a reference to the Azure path
            CloudFileShare cloudFileShare = cloudFileClient.GetShareReference(CONTAINER_NAME);

            //Create a reference to the filename that you will be uploading
            CloudFile cloudFile = cloudFileShare
                                  .GetRootDirectoryReference()
                                  .GetDirectoryReference("uploads")
                                  .GetFileReference(file.FileName);

            //Open a stream from a local file.
            Stream fileStream = file.OpenReadStream();

            //Upload the file to Azure.
            await cloudFile.UploadFromStreamAsync(fileStream);

            fileStream.Dispose();

            var response = new FileReference
            {
                FileName = file.FileName,
                Uri      = cloudFile.Uri.AbsoluteUri,
                Success  = true
            };

            return(response);
        }
示例#5
0
        /// <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);
        }
示例#6
0
        /// <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 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);
            }
        }
示例#8
0
        /// <summary>
        /// Test some of the file storage operations.
        /// </summary>
        public async Task RunFileStorageAdvancedOpsAsync()
        {
            //***** Setup *****//
            Console.WriteLine("Getting reference to the storage account.");

            // Retrieve storage account information from connection string
            // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            Console.WriteLine("Instantiating file client.");
            Console.WriteLine(string.Empty);

            // Create a file client for interacting with the file service.
            CloudFileClient cloudFileClient = storageAccount.CreateCloudFileClient();

            // List shares
            await ListSharesSample(cloudFileClient);

            // CORS Rules
            await CorsSample(cloudFileClient);

            // Share Properties
            await SharePropertiesSample(cloudFileClient);

            // Share Metadata
            await ShareMetadataSample(cloudFileClient);

            // Directory Properties
            await DirectoryPropertiesSample(cloudFileClient);

            // Directory Metadata
            await DirectoryMetadataSample(cloudFileClient);

            // File Properties
            await FilePropertiesSample(cloudFileClient);

            // File Metadata
            await FileMetadataSample(cloudFileClient);
        }
        public ActionResult <string> GetFileContent()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(@"DefaultEndpointsProtocol=https;AccountName=lab1diag679;AccountKey=TtymI1zwujPy40v9NvlAApX1o04SSA4Jnj2TAH4VvlnoOiPbCym4Rt9qLZwVRgeKgPIHskJBcRtcW0Rt9vxFZw==;EndpointSuffix=core.windows.net");
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      share          = fileClient.GetShareReference("lab1-fs");

            if (share.ExistsAsync().Result)
            {
                // Get a reference to the root directory for the share.
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                // Get a reference to the directory we created previously.
                CloudFile file = rootDir.GetFileReference("Test1.txt");

                if (file.ExistsAsync().Result)
                {
                    // Write the contents of the file to the console window.
                    return(file.DownloadTextAsync().Result);
                }
            }
            return("file not found");
        }
        public static CloudFileShare Setup()
        {
            Console.WriteLine("Setting up File Share Connection...");

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CONNECTION_STRING);
            // 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(SHARE_NAME);

            // Ensure that the share exists.
            if (share.Exists())
            {
                // Get a reference to the root directory for the share.
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();
                Console.WriteLine($"\nConnection to File Share succeeded. Root Dir storage URI: {rootDir.StorageUri.PrimaryUri}");

                return(share);
            }

            return(null);
        }
示例#11
0
        /// <summary>
        /// Save document file to Azure File
        /// </summary>
        /// <param name="shareName">Define share name</param>
        /// <param name="sourceFolder">Define folder name which created under share</param>
        /// <param name="fileName">Define file name which resided under sourcefolder </param>
        /// <param name="stream">File stream</param>
        /// <returns></returns>
        public async Task UploadFileAsync(string shareName, string sourceFolder, string fileName, Stream stream)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(settings.ConnectionString);

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

            CloudFileShare cloudFileShare = null;

            cloudFileShare = cloudFileClient.GetShareReference(shareName);

            await cloudFileShare.CreateIfNotExistsAsync();

            // First, get a reference to the root directory, because that's where you're going to put the new directory.
            CloudFileDirectory rootDirectory = cloudFileShare.GetRootDirectoryReference();

            CloudFileDirectory fileDirectory = null;
            CloudFile          cloudFile     = null;

            // Set a reference to the file directory.
            // If the source folder is null, then use the root folder.
            // If the source folder is specified, then get a reference to it.
            if (string.IsNullOrWhiteSpace(sourceFolder))
            {
                // There is no folder specified, so return a reference to the root directory.
                fileDirectory = rootDirectory;
            }
            else
            {
                // There was a folder specified, so return a reference to that folder.
                fileDirectory = rootDirectory.GetDirectoryReference(sourceFolder);
                await fileDirectory.CreateIfNotExistsAsync();
            }

            // Set a reference to the file.
            cloudFile = fileDirectory.GetFileReference(fileName);

            await cloudFile.UploadFromStreamAsync(stream);
        }
        public async Task <IEnumerable <Well> > GetWells()
        {
            var key = Resources.AzureStorageKey;
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(key);

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

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

            if (await share.ExistsAsync())
            {
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();
                var fileList = await rootDir.ListFilesAndDirectoriesSegmentedAsync(new FileContinuationToken());

                var wellFile   = fileList.Results.Last() as CloudFile;
                var wellString = await wellFile.DownloadTextAsync();

                var wells = JArray.Parse(wellString).ToObject <List <Well> >();
                return(wells);
            }
            return(new List <Well>());
        }
        public void FileOperations(string fileSharename, string Directory, string filePath)
        {
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare  fileShare  = fileClient.GetShareReference(fileSharename);

            fileShare.CreateIfNotExists(null, null);
            CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference();
            CloudFileDirectory fileDirectory = rootDirectory.GetDirectoryReference(Directory);

            fileDirectory.CreateIfNotExists();
            CloudFile file = fileDirectory.GetFileReference("testfile");

            //Deleting If File Exists
            file.DeleteIfExistsAsync();
            if (file.Exists() == false)
            {
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
                file.Create(fs.Length);
                fs.Close();
            }
            file.OpenWrite(null);
            //Upload File Operation
            file.UploadFromFile(filePath, FileMode.Open);
            //Write File Operation
            file.WriteRange(new FileStream(filePath, FileMode.Open), 0);
            Stream azureFile = file.OpenRead();

            //Read File Operation
            azureFile.Position = 0;
            byte[] buffer = new byte[azureFile.Length - 1];
            int    n      = azureFile.Read(buffer, (int)0, 14050);

            for (int i = 0; i < buffer.Length; i++)
            {
                Console.Write(buffer[i].ToString());
            }
            //Download File Operation
            file.DownloadToFile(@"D:\TestFile.pptx", FileMode.Create);
        }
        public async Task <string> GetText()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_configuration.GetConnectionString("StorageAccount"));

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            CloudFileShare share = fileClient.GetShareReference(_configuration.GetSection("FileConfig:Folder").Value);

            if (await share.ExistsAsync())
            {
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                CloudFile file = rootDir.GetFileReference(_configuration.GetSection("FileConfig:Filename").Value);

                if (await file.ExistsAsync())
                {
                    var result = file.DownloadTextAsync().Result;
                }
            }

            return(string.Empty);
        }
示例#15
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);
        }
示例#16
0
        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);
                    }
                }
            }
        }
示例#17
0
        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);
                }
            }
        }
示例#18
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// 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);
        }
示例#19
0
        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();
                    }
                }
            }
        }
示例#20
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);
     }
 }
示例#21
0
        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);
        }
示例#22
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);
        }
示例#23
0
        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);
        }
示例#24
0
        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();
                }
            }
        }
示例#25
0
        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();
                    }
                }
            }
        }
        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());
            }
        }
示例#27
0
        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);
        }
示例#28
0
        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);
        }
示例#29
0
        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();
            }
        }
示例#30
0
        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);
                    }
                }
            }
        }