private CloudFile GetCloudFileReference(string path, bool createIfNotExist = false)
        {
            CloudFileDirectory directory = cloudFileClient.GetShareReference(rootDir).GetRootDirectoryReference();
            CloudFile          file      = null;

            string[] folders = GetArrrayOfFolders(path);

            for (int i = 0; i < folders.Length; i++)
            {
                if (i == folders.Length - 1)
                {
                    file = directory.GetFileReference(folders[i]);
                    if (!file.Exists() && createIfNotExist)
                    {
                        file.Create(0L);
                    }
                }
                else
                {
                    directory = directory.GetDirectoryReference(folders[i]);
                    if (!directory.Exists() && createIfNotExist)
                    {
                        directory.Create();
                    }
                }
            }

            return(file);
        }
예제 #2
0
        private async Task <CloudFile> GetFileReferenceAsync(string fullPath, bool createParents, CancellationToken cancellationToken)
        {
            string[] parts = StoragePath.Split(fullPath);
            if (parts.Length == 0)
            {
                return(null);
            }

            string shareName = parts[0];

            CloudFileShare share = _client.GetShareReference(shareName);

            if (createParents)
            {
                await share.CreateIfNotExistsAsync(cancellationToken).ConfigureAwait(false);
            }

            CloudFileDirectory dir = share.GetRootDirectoryReference();

            for (int i = 1; i < parts.Length - 1; i++)
            {
                string sub = parts[i];
                dir = dir.GetDirectoryReference(sub);

                if (createParents)
                {
                    await dir.CreateIfNotExistsAsync().ConfigureAwait(false);
                }
            }

            return(dir.GetFileReference(parts[parts.Length - 1]));
        }
        public async Task DeleteFile(string fileName)
        {
            var parts = fileName.Split('/');

            var share     = _client.GetShareReference(parts[0]);
            var directory = share.GetRootDirectoryReference();

            var file = directory.GetFileReference(parts[1]);

            await file.DeleteAsync();
        }
예제 #4
0
        public async Task RunFileTest(SharedAccessAccountPolicy policy, int?httpsPort, OperationContext opContext = null)
        {
            CloudFileClient fileClient = GenerateCloudFileClient();
            string          shareName  = "s" + Guid.NewGuid().ToString("N");

            try
            {
                CloudStorageAccount account        = new CloudStorageAccount(fileClient.Credentials, false);
                string             accountSASToken = account.GetSharedAccessSignature(policy);
                StorageCredentials accountSAS      = new StorageCredentials(accountSASToken);

                StorageUri storageUri = fileClient.StorageUri;
                if (httpsPort != null)
                {
                    storageUri = new StorageUri(TransformSchemeAndPort(storageUri.PrimaryUri, "https", httpsPort.Value), TransformSchemeAndPort(storageUri.SecondaryUri, "https", httpsPort.Value));
                }
                else
                {
                    storageUri = new StorageUri(TransformSchemeAndPort(storageUri.PrimaryUri, "http", 80), TransformSchemeAndPort(storageUri.SecondaryUri, "http", 80));
                }

                CloudStorageAccount accountWithSAS    = new CloudStorageAccount(accountSAS, null, null, null, storageUri);
                CloudFileClient     fileClientWithSAS = accountWithSAS.CreateCloudFileClient();
                CloudFileShare      shareWithSAS      = fileClientWithSAS.GetShareReference(shareName);
                CloudFileShare      share             = fileClient.GetShareReference(shareName);
                await share.CreateAsync();

                string    fileName    = "file";
                CloudFile file        = share.GetRootDirectoryReference().GetFileReference(fileName);
                CloudFile fileWithSAS = shareWithSAS.GetRootDirectoryReference().GetFileReference(fileName);
                byte[]    content     = new byte[] { 0x1, 0x2, 0x3, 0x4 };
                await file.CreateAsync(content.Length);

                using (MemoryStream stream = new MemoryStream(content))
                {
                    await file.WriteRangeAsync(stream, 0, null);
                }

                byte[] result = new byte[content.Length];
                await fileWithSAS.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length, null, null, opContext);

                for (int i = 0; i < content.Length; i++)
                {
                    Assert.AreEqual(content[i], result[i]);
                }
            }
            finally
            {
                fileClient.GetShareReference(shareName).DeleteIfExistsAsync().Wait();
            }
        }
        static async Task <bool> FileExists(string strSourceFolderPath, string strSourceFileName)
        {
            log.Info("Checking if the file exists");
            log.Info("Folder " + strSourceFolderPath);
            log.Info("File : " + strSourceFileName);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionStr);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      share          = fileClient.GetShareReference(fileshare);
            CloudFileDirectory  rootDir        = share.GetRootDirectoryReference();
            CloudFile           sourceFile;

            if (strSourceFolderPath != "")
            {
                CloudFileDirectory sourcefolder = rootDir.GetDirectoryReference(strSourceFolderPath);
                sourceFile = sourcefolder.GetFileReference(strSourceFileName);
            }
            else
            {
                sourceFile = rootDir.GetFileReference(strSourceFileName);
            }

            log.Info(sourceFile.Uri.ToString());


            return(await sourceFile.ExistsAsync() ? true : false);
        }
        static void CopyFile(string strSourceFolderPath, string strSourceFileName, string strTargetFolderPath)
        {
            log.Info("Executing Copy File");
            log.Info("Folder " + strSourceFolderPath);
            log.Info("File : " + strSourceFileName);
            log.Info("Target : " + strTargetFolderPath);

            //Copy File method.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionStr);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      share          = fileClient.GetShareReference(fileshare);
            CloudFileDirectory  rootDir        = share.GetRootDirectoryReference();
            CloudFile           sourceFile;

            if (strSourceFolderPath != "")
            {
                CloudFileDirectory sourcefolder = rootDir.GetDirectoryReference(strSourceFolderPath);
                sourceFile = sourcefolder.GetFileReference(strSourceFileName);
            }
            else
            {
                sourceFile = rootDir.GetFileReference(strSourceFileName);
            }


            CloudFileDirectory targetfolder = rootDir.GetDirectoryReference(strTargetFolderPath);
            CloudFile          destFile     = targetfolder.GetFileReference(strSourceFileName);

            log.Info("Source File : " + sourceFile.Name);
            log.Info("Target File : " + targetfolder.Name);
            destFile.StartCopyAsync(sourceFile);
            log.Info(sourceFile.Name + " copied to " + targetfolder.Name);
        }
        static void DeleteFile(string strSourceFolderPath, string strSourceFileName)
        {
            log.Info("Executing Delete File");
            log.Info("Folder " + strSourceFolderPath);
            log.Info("File : " + strSourceFileName);

            //Delete File method
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionStr);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      share          = fileClient.GetShareReference(fileshare);
            CloudFileDirectory  rootDir        = share.GetRootDirectoryReference();
            CloudFile           sourceFile;

            if (strSourceFolderPath != "")
            {
                CloudFileDirectory sourcefolder = rootDir.GetDirectoryReference(strSourceFolderPath);
                sourceFile = sourcefolder.GetFileReference(strSourceFileName);
            }
            else
            {
                sourceFile = rootDir.GetFileReference(strSourceFileName);
            }
            sourceFile.DeleteIfExistsAsync();
            log.Info(sourceFile.Name + " deleted.");
        }
예제 #8
0
        public override async Task <FileData> GetAsync(FileGetOptions fileGetOptions)
        {
            FileData file = new FileData();

            CloudStorageAccount storageAccount = Authorized(fileGetOptions);

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            CloudFileShare fileshare = fileClient.GetShareReference(fileGetOptions.Folder);

            if (fileshare.ExistsAsync().Result)
            {
                CloudFileDirectory cFileDir = fileshare.GetRootDirectoryReference();

                CloudFile cFile = cFileDir.GetFileReference(fileGetOptions.Key);

                if (cFile.ExistsAsync().Result)
                {
                    file.Stream.Position = 0;
                    await cFile.DownloadToStreamAsync(file.Stream);
                }
            }

            file.Type = "Azure File Storage";

            return(file);
        }
        static void Main(string[] args)
        {
            // Parse the connection string for the storage account.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=*************");
            // Create a CloudFileClient object for credentialed access to File storage.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            // Get a reference to the file share you created previously.
            CloudFileShare share = fileClient.GetShareReference("hurytest");
            // Get a reference to the file I have uploaded to the file share("hurytest")
            CloudFile sourceFile = share.GetRootDirectoryReference().GetFileReference("test.csv");
            // Get a reference to the blob to which the file will be copied.(I have created a container with name of "targetcontainer")
            CloudBlobClient    blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference("targetcontainer");
            //container.CreateIfNotExists();
            CloudBlockBlob destBlob = container.GetBlockBlobReference("test.csv");
            // 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);
        }
예제 #10
0
        public void AzureFile_Crud()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

            Assert.NotNull(storageAccount);
            // 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("bma");

            // 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("bma");

                // Ensure that the directory exists.
                if (sampleDir.Exists())
                {
                    // Get a reference to the file we created previously.
                    CloudFile file = sampleDir.GetFileReference("function.json");
                    Assert.AreEqual(true, file.Exists());
                    file.
                }
            }
        }
        public void CloudStorageAccountClientUriVerify()
        {
            StorageCredentials  cred = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey);
            CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(cred, true);

            CloudBlobClient    blobClient = cloudStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference("container1");

            Assert.AreEqual(cloudStorageAccount.BlobEndpoint.ToString() + "container1", container.Uri.ToString());

            CloudQueueClient queueClient = cloudStorageAccount.CreateCloudQueueClient();
            CloudQueue       queue       = queueClient.GetQueueReference("queue1");

            Assert.AreEqual(cloudStorageAccount.QueueEndpoint.ToString() + "queue1", queue.Uri.ToString());

            CloudTableClient tableClient = cloudStorageAccount.CreateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("table1");

            Assert.AreEqual(cloudStorageAccount.TableEndpoint.ToString() + "table1", table.Uri.ToString());

            CloudFileClient fileClient = cloudStorageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference("share1");

            Assert.AreEqual(cloudStorageAccount.FileEndpoint.ToString() + "share1", share.Uri.ToString());
        }
예제 #12
0
        static void Main(string[] args)
        {
            string s1 = "";

            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("your account", "your key"), true);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      share          = fileClient.GetShareReference("t11");
            CloudFileDirectory  rootDir        = share.GetRootDirectoryReference();
            CloudFile           file           = rootDir.GetFileReference("test.txt");

            if (file.Exists())
            {
                using (var ms = new MemoryStream())
                {
                    long?offset = Convert.ToInt64(file.Properties.Length * .8);
                    long?length = Convert.ToInt64(file.Properties.Length * .20);

                    file.DownloadRangeToStream(ms, offset, length);
                    //set the position of memory stream to zero
                    ms.Position = 0;
                    using (var sr = new StreamReader(ms))
                    {
                        s1 = sr.ReadToEnd();
                    }

                    Console.WriteLine(s1);
                }
            }

            Console.WriteLine("---done---");
            Console.ReadLine();
        }
예제 #13
0
        /// <summary>
        /// Delete the share with the specified name if it exists.
        /// </summary>
        /// <param name="shareName">Name of share to delete.</param>
        public static void DeleteShare(string shareName)
        {
            CloudFileClient client = GetCloudFileClient();
            CloudFileShare  share  = client.GetShareReference(shareName);

            share.DeleteIfExists();
        }
        public async Task Test_11_QueryForFilesAndDirectories()
        {
            var share = _client.GetShareReference("demo01");

            var shareExists = await share.ExistsAsync();

            Check.That(shareExists).IsTrue();

            var root = share.GetRootDirectoryReference();

            var rootExists = await root.ExistsAsync();

            Check.That(rootExists).IsTrue();

            var queryResults = new List <IListFileItem>();

            FileContinuationToken fct = null;

            do
            {
                var queryResult = await root.ListFilesAndDirectoriesSegmentedAsync(fct);

                queryResults.AddRange(queryResult.Results);

                fct = queryResult.ContinuationToken;
            }while (fct != null);

            Check.That(queryResults.Count).IsStrictlyGreaterThan(0);
        }
예제 #15
0
        public CloudFileDirectory GetCloudFileDirectoryByEvent(LogEvent logEvent)
        {
            var azureConfig = _azureConfigContainer.Get(logEvent);

            if (azureConfig == null)
            {
                return(null);
            }

            var storageAccount = CloudStorageAccount.Parse(azureConfig.ConnectionString);

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            CloudFileShare share = fileClient.GetShareReference(azureConfig.FileShare);

            if (!share.Exists())
            {
                throw new StorageException($"{azureConfig.FileDirectory} not found.");
            }

            CloudFileDirectory rootDir = share.GetRootDirectoryReference();

            CloudFileDirectory cloudFileDirectory = rootDir.GetDirectoryReference(azureConfig.FileDirectory);

            return(cloudFileDirectory);
        }
예제 #16
0
        private static void TransferFileToAzure(MemoryStream stream, string file, Agent agent)
        {
            string shortFileName = file.Substring(file.LastIndexOf('/') + 1);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_azureFileConnectionString);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      fileShare      = fileClient.GetShareReference(_shareName);

            if (!fileShare.Exists())
            {
                _log.Error("Azure file share does not exist as expected.  Connection string: {0}", _azureFileConnectionString);
            }
            else
            {
                try
                {
                    CloudFileDirectory fileDirectoryRoot  = fileShare.GetRootDirectoryReference();
                    CloudFileDirectory fileAgentDirectory = fileDirectoryRoot.GetDirectoryReference(agent.Queue.ToString());
                    fileAgentDirectory.CreateIfNotExists();
                    CloudFile cloudFile = fileAgentDirectory.GetFileReference(shortFileName);
                    stream.Seek(0, SeekOrigin.Begin);
                    cloudFile.UploadFromStream(stream);
                    stream.Seek(0, SeekOrigin.Begin);
                    int recordCount = TotalLines(stream);

                    LogFile(agent.Id, file, cloudFile.StorageUri.PrimaryUri.ToString(), FileStatusEnum.UPLOADED, recordCount);
                    _log.Info("Successfully transfered file {0} to {1} by agent ID: {2}", shortFileName, cloudFile.StorageUri.PrimaryUri.ToString(), agent.Id.ToString());
                }
                catch (Exception ex)
                {
                    _log.Error(ex, "Unexpected error in TransferFileToAzure for file: {0} on site: ", agent.Url);
                    LogFile(agent.Id, file, "", FileStatusEnum.ERROR_UPLOADED, 0);
                }
            }
        }
예제 #17
0
        public async Task <IActionResult> Post()
        {
            var files = Request.Form.Files;

            CloudStorageAccount storageAccount = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials("processimprovement", "kVatBtO1SKg9Sp4y8v1PzpY7J4F9yJSodKNFq+lg8ZDj63w+RTdlTgYYzLS2ot7LRfrtwhRhNGPkOL+n77tbAg=="), true);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      share          = fileClient.GetShareReference("uploads");

            foreach (var file in files)
            {
                if (file.Length > 0)
                {
                    CloudFileDirectory rootDir = share.GetRootDirectoryReference();
                    //CloudFileDirectory innoDir = rootDir.GetDirectoryReference();
                    CloudFile cloudFile = rootDir.GetFileReference(file.FileName);

                    using (var fileStream = file.OpenReadStream())
                    {
                        await cloudFile.UploadFromStreamAsync(fileStream);
                    }
                }

                _docsRepository.Save(new Doc {
                    Name = file.FileName, InnovationId = int.Parse(file.Name)
                });
            }


            return(Ok());
        }
        public async Task <ActionResult> SelectSampleDataSource(MainViewModel main)
        {
            main.SelectedDataSourceName = main.SelectedSampleDataSourceName;

            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("samples");

            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));
        }
예제 #19
0
        public static CloudFileDirectory BasicAzureFileOperations()
        {
            // Get Storage Account Key from Key Vault
            string saKey = EncryptionHelper.GetSAKey();

            // Retrieve storage account information from connection string
            CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(string.Format(storageConnectionString, saKey));

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

            // Get the storage file share reference based on storage account
            CloudFileShare fileShare = fileClient.GetShareReference(storageFileShareName);

            // Check whether the File Share exist or not. By default, is should be created by TM team. And now, the focalpoint is: Spoelhof, Nathan (ND) <*****@*****.**>
            // who create the storage manually (blob, file, table & queue)
            // Default size of file share is 1GB and configued in web.config
            if (!fileShare.Exists())
            {
                fileShare.Properties.Quota = storageFileShareSize;
                fileShare.CreateIfNotExists();
            }

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

            return(root);
        }
예제 #20
0
        static void Main(string[] args)
        {
            string accountName = "xxx";
            string accountKey  = "xxx";
            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);

            CloudFileClient cloudFileClient = storageAccount.CreateCloudFileClient();

            //make sure the file share named test1 exists.
            CloudFileShare     fileShare     = cloudFileClient.GetShareReference("test1");
            CloudFileDirectory fileDirectory = fileShare.GetRootDirectoryReference();
            CloudFile          myfile        = fileDirectory.GetFileReference("test123.txt");

            if (!myfile.Exists())
            {
                //if the file does not exists, then create the file and set the file max size to 100kb.
                myfile.Create(100 * 1024 * 1024);
            }

            //upload text to the file
            //Besides using UploadText() method to directly upload text, you can also use UploadFromFile() / UploadFromByteArray() / UploadFromStream() methods as per your need.
            myfile.UploadText("hello, it is using azure storage SDK");

            Console.WriteLine("**completed**");
            Console.ReadLine();
        }
예제 #21
0
        public static async Task <bool> UploadFilesToTableStorage(string valFileName)
        {
            bool         vResult       = false;
            const string DemoShare     = "demofileshare";
            const string DemoDirectory = "demofiledirectory";

            try {
                CloudStorageAccount vStorageAccount = CreateStorageAccountFromConnectionString(Constants.vStorageConnectionString);

                CloudFileClient fileClient = vStorageAccount.CreateCloudFileClient();
                Console.WriteLine("1. Creating file share");
                CloudFileShare     share = fileClient.GetShareReference(DemoShare);
                CloudFileDirectory root  = share.GetRootDirectoryReference();

                CloudFileDirectory dir          = root.GetDirectoryReference(DemoDirectory);
                string[]           FileInfoName = valFileName.Split("\\");
                CloudFile          file         = dir.GetFileReference(FileInfoName.LastOrDefault());

                FileRequestOptions fr = new FileRequestOptions();
                OperationContext   oc = new OperationContext();
                AccessCondition    ac = new AccessCondition();
                //using (FileStream FileUpload = new FileStream(valFileName, FileMode.Open)) {
                await file.UploadFromFileAsync(valFileName);

                //await file.UploadFromStreamAsync(FileUpload, FileUpload.Length);
                //}
                vResult = true;
            } catch (Exception vEx) {
                string message = vEx.Message;
            }
            return(vResult);
            // List all files/directories under the root directory
        }
예제 #22
0
        private static void GenerateFileSAS()
        {
            CloudStorageAccount storageAccount = GetStorageAccount();

            //Create the file client object
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            //Get a reference to file share
            Console.WriteLine("Share:");
            string         shareName = Console.ReadLine();
            CloudFileShare share     = fileClient.GetShareReference(shareName);

            //Get reference to file
            Console.WriteLine("File:");
            string             fileName = Console.ReadLine();
            CloudFileDirectory rootDir  = share.GetRootDirectoryReference();
            CloudFile          file     = rootDir.GetFileReference("abc.txt");

            //Create SAS
            SharedAccessFilePolicy sasConstraints = new SharedAccessFilePolicy();

            sasConstraints.SharedAccessStartTime  = DateTime.UtcNow.AddMinutes(-10);
            sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(10);
            sasConstraints.Permissions            = SharedAccessFilePermissions.Read;

            //Generate the shared access signature on the blob, setting the constraints directly on the signature.
            string sasFileToken = file.GetSharedAccessSignature(sasConstraints);

            //Return the URI string for the container, including the SAS token.
            Console.WriteLine(file.Uri + sasFileToken);
        }
예제 #23
0
        public void Set_the_maximum_size_for_a_file_share()
        {
            // 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();

            // Get a reference to the file share we created previously.
            CloudFileShare share = fileClient.GetShareReference("logs");

            // Ensure that the share exists.
            if (share.Exists())
            {
                // Check current usage stats for the share.
                // Note that the ShareStats object is part of the protocol layer for the File service.
                Microsoft.WindowsAzure.Storage.File.Protocol.ShareStats stats = share.GetStats();
                Console.WriteLine("Current share usage: {0} GB", stats.Usage.ToString());

                // Specify the maximum size of the share, in GB.
                // This line sets the quota to be 10 GB greater than the current usage of the share.
                share.Properties.Quota = 10 + stats.Usage;
                share.SetProperties();

                // Now check the quota for the share. Call FetchAttributes() to populate the share's properties.
                share.FetchAttributes();
                Console.WriteLine("Current share quota: {0} GB", share.Properties.Quota);
            }
        }
예제 #24
0
        static void Main(string[] args)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connection);

            CloudFileClient cloudFileClient = storageAccount.CreateCloudFileClient();

            // Get a reference to the file share we created previously.
            CloudFileShare fileShare = cloudFileClient.GetShareReference("doc2020");

            // Ensure that the share exists.
            if (fileShare.Exists())
            {
                // Get a reference to the root directory for the share.
                CloudFileDirectory fileDirectory = fileShare.GetRootDirectoryReference();

                // Get a reference to the directory we created previously.
                CloudFileDirectory customDirectory = fileDirectory.GetDirectoryReference("storage");

                // Ensure that the directory exists.
                if (customDirectory.Exists())
                {
                    // Get a reference to the file we created previously.
                    CloudFile fileInfo = customDirectory.GetFileReference("Log1.txt");

                    // Ensure that the file exists.
                    if (fileInfo.Exists())
                    {
                        // Write the contents of the file to the console window.
                        Console.WriteLine(fileInfo.DownloadTextAsync().Result);
                    }
                }

                NewFileCreate();
            }
        }
예제 #25
0
        /// <summary>
        /// Method to Copy file to Azure File share
        /// </summary>
        /// <param name="finputstream">source file inputstream</param>
        /// <param name="filename">source filename</param>
        private void CopyToFileShare(Stream finputstream, string filename)
        {
            try
            {
                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 .
                CloudFileShare share = fileClient.GetShareReference(CloudConfigurationManager.GetSetting("ShareDirectoryName"));

                // 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 destination file.
                    CloudFile destFile = rootDir.GetFileReference(filename);
                    // Start the copy operation.
                    destFile.UploadFromStream(finputstream);
                    finputstream.Dispose();
                }
            }
            catch (Exception ex)
            {
                Write(string.Format("message: {0} stacktrace: {1}", ex.Message, ex.StackTrace));
            }
        }
예제 #26
0
    /// <summary>
    /// Create the references necessary to log into Azure
    /// </summary>
    private async void CreateCloudIdentityAsync()
    {
        // Retrieve storage account information from connection string
        storageAccount = CloudStorageAccount.Parse(storageConnectionString);
        // Create a file client for interacting with the file service.
        fileClient = storageAccount.CreateCloudFileClient();
        // Create a share for organizing files and directories within the storage account.
        share = fileClient.GetShareReference(fileShare);
        await share.CreateIfNotExistsAsync();

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

        // Create a directory under the root directory
        dir = root.GetDirectoryReference(storageDirectory);
        await dir.CreateIfNotExistsAsync();

        //Check if the there is a stored text file containing the list
        shapeIndexCloudFile = dir.GetFileReference("TextShapeFile");
        if (!await shapeIndexCloudFile.ExistsAsync())
        {
            // File not found, enable gaze for shapes creation
            Gaze.instance.enableGaze = true;

            azureStatusText.text = "No Shape\nFile!";
        }
        else
        {              // The file has been found, disable gaze and get the list from the file
            Gaze.instance.enableGaze = false; azureStatusText.text = "Shape File\nFound!";
            await ReplicateListFromAzureAsync();
        }
    }
예제 #27
0
        public override bool Execute()
        {
            Log.LogMessage(MessageImportance.High, "Creating file share named '{0}' in storage account {1}.", ShareName, AccountName);

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AccountName, AccountKey));
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      fileShare      = fileClient.GetShareReference(ShareName);

            fileShare.CreateIfNotExists();
            StorageUri = fileShare.Uri.ToString();

            // NOTE: by convention the tokens don't contain the leading '?' character.

            if (ReadOnlyTokenDaysValid > 0)
            {
                SharedAccessFilePolicy rFilePolicy = new SharedAccessFilePolicy();
                rFilePolicy.SharedAccessExpiryTime = DateTime.UtcNow.AddDays(ReadOnlyTokenDaysValid);
                rFilePolicy.Permissions            = SharedAccessFilePermissions.Read;
                ReadOnlyToken = fileShare.GetSharedAccessSignature(rFilePolicy).Substring(1);
            }

            if (WriteOnlyTokenDaysValid > 0)
            {
                SharedAccessFilePolicy wFilePolicy = new SharedAccessFilePolicy();
                wFilePolicy.SharedAccessExpiryTime = DateTime.UtcNow.AddDays(WriteOnlyTokenDaysValid);
                wFilePolicy.Permissions            = SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write | SharedAccessFilePermissions.List | SharedAccessFilePermissions.Delete;
                WriteOnlyToken = fileShare.GetSharedAccessSignature(wFilePolicy).Substring(1);
            }

            return(true);
        }
예제 #28
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post")] PostData data, ILogger log)
        {
            log.LogInformation($"C# Blob trigger function Processed blob\n Name:{data.name}\n StorageAccount: {data.storageAccount}\n SourceFileShare: {data.sourceFileShare}\n DestinationFolder: {data.destinationFolder}");

            if (data.name.Split('.').Last().ToLower() == "zip")
            {
                try{
                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(data.storageAccount);
                    CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
                    CloudFileShare      fileShare      = fileClient.GetShareReference(data.sourceFileShare);
                    CloudFile           zipFile        = fileShare.GetRootDirectoryReference().GetFileReference(data.name);

                    MemoryStream blobMemStream = new MemoryStream();

                    await zipFile.DownloadToStreamAsync(blobMemStream);

                    extract(blobMemStream, log, fileShare, data);
                }
                catch (Exception ex) {
                    log.LogInformation($"Error! Something went wrong: {ex.Message}");
                    return(new ExceptionResult(ex, true));
                }
            }

            return(new OkObjectResult("Unzip succesfull"));
        }
예제 #29
0
        public static void UploadtoFileShare(string shareReference, byte[] fileStream, string fileName)
        {
            // Parse the connection string and return a reference to the storage account.
            CloudStorageAccount storageAccount = Helper.storageAccount;



            // Create a reference to the file client.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();



            CloudFileShare share = fileClient.GetShareReference(shareReference);

            share.CreateIfNotExists();

            if (share.Exists())
            {
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();
                //Create a reference to the filename that you will be uploading
                CloudFile cloudFile = rootDir.GetFileReference(fileName);


                FileStream fStream = File.OpenRead("C:\\myprojs\\images\\krishna.jpg");



                cloudFile.UploadFromByteArray(fileStream, 0, fileStream.Length);
                Console.WriteLine($"File uploaded successfully   {fileName}");
            }
        }
        private async Task UploadFileAsync()
        {
            if (string.IsNullOrEmpty(this.FileToUploadName))
            {
                return;
            }
            var remoteFileName = Path.GetFileName(this.FileToUploadName);

            //
            // This is the interesting code for the sample
            //

            string             storageConnectionString = this.ConnectionString;
            var                storageAccount          = CloudStorageAccount.Parse(storageConnectionString);
            CloudFileClient    fileClient = storageAccount.CreateCloudFileClient();
            CloudFileDirectory cfDir      = fileClient.GetShareReference(this.RemoteShareName).GetRootDirectoryReference();
            CloudFile          cloudFile  = cfDir.GetFileReference(remoteFileName);

            try
            {
                var fileStream = await this.fileToUpload.OpenStreamForReadAsync();

                await cloudFile.UploadFromStreamAsync(fileStream);
            }
            catch (StorageException)
            {
                // TODO - user actionable error - could be auth, missing file, server down, etc.
            }
        }