コード例 #1
0
        private async Task DumpJson <T>(T obj, string fileName)
        {
            // Dump to local temp file (need to do this because need to know file size before copying to Azure File Share).
            var tmpFile = Path.GetTempFileName();

            using (StreamWriter sw = new StreamWriter(tmpFile))
                using (JsonWriter jtw = new JsonTextWriter(sw))
                {
                    var serializer = new JsonSerializer();
                    serializer.Serialize(jtw, obj);
                }

            try
            {
                // Copy the temp file to Azure File Share
                ShareClient          share     = new ShareClient(DataDumpStorageConnectionString, DataDumpStorageShareName);
                ShareDirectoryClient directory = share.GetDirectoryClient("/");
                ShareFileClient      file      = directory.GetFileClient(fileName);

                using (FileStream stream = File.OpenRead(tmpFile))
                {
                    await file.CreateAsync(stream.Length);

                    await file.UploadRangeAsync(new HttpRange(0, stream.Length), stream);
                }
            }
            finally
            {
                // Clean up the temp file
                File.Delete(tmpFile);
            }
        }
コード例 #2
0
        private ShareFileClient StorageSetup(IFormFile loadedFile, string fileType)
        {
            string dirName  = fileType;
            string fileName = loadedFile.FileName;

            ShareClient share = new ShareClient(_storagekey, _storageshare);

            try
            {
                // Try to create the share again
                share.Create();
            }
            catch (RequestFailedException ex)
                when(ex.ErrorCode == ShareErrorCode.ShareAlreadyExists)
                {
                    // Ignore any errors if the share already exists
                }
            ShareDirectoryClient directory = share.GetDirectoryClient(dirName);

            try
            {
                // Try to create the share again
                directory.Create();
            }
            catch (RequestFailedException ex)
            {
                // Ignore any errors if the share already exists
            }
            ShareFileClient shareFile = directory.GetFileClient(fileName);

            return(shareFile);
        }
コード例 #3
0
        public async Task DeleteFileAsync(String filename)
        {
            ShareDirectoryClient raiz = this.cliente.GetRootDirectoryClient();
            ShareFileClient      file = raiz.GetFileClient(filename);

            await file.DeleteAsync();
        }
コード例 #4
0
        public async Task PathClient_CanGetParentDirectoryClient()
        {
            // Arrange
            var parentDirName = SharesClientBuilder.GetNewDirectoryName();

            await using DisposingShare test = await SharesClientBuilder.GetTestShareAsync();

            ShareDirectoryClient parentDirClient = InstrumentClient(test.Container
                                                                    .GetRootDirectoryClient()
                                                                    .GetSubdirectoryClient(parentDirName));
            await parentDirClient.CreateAsync();

            ShareFileClient fileClient = InstrumentClient(parentDirClient
                                                          .GetFileClient(SharesClientBuilder.GetNewFileName()));
            await fileClient.CreateAsync(Constants.KB);

            // Act
            parentDirClient = fileClient.GetParentShareDirectoryClient();
            // make sure that client is functional
            var dirProperties = await parentDirClient.GetPropertiesAsync();

            // Assert
            Assert.AreEqual(fileClient.Path.GetParentPath(), parentDirClient.Path);
            Assert.AreEqual(fileClient.AccountName, parentDirClient.AccountName);
            Assert.IsNotNull(dirProperties);
        }
コード例 #5
0
        /// <summary>
        /// Download a file.
        /// </summary>
        /// <param name="connectionString">
        /// A connection string to your Azure Storage account.
        /// </param>
        /// <param name="shareName">
        /// The name of the share to download from.
        /// </param>
        /// <param name="localFilePath">
        /// Path to download the local file.
        /// </param>
        public static async Task DownloadAsync(string connectionString, string shareName, string localFilePath)
        {
            #region Snippet:Azure_Storage_Files_Shares_Samples_Sample01b_HelloWorldAsync_DownloadAsync
            //@@ string connectionString = "<connection_string>";

            // Name of the share, directory, and file we'll download from
            //@@ string shareName = "sample-share";
            string dirName  = "sample-dir";
            string fileName = "sample-file";

            // Path to the save the downloaded file
            //@@ string localFilePath = @"<path_to_local_file>";

            // Get a reference to the file
            ShareClient          share     = new ShareClient(connectionString, shareName);
            ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
            ShareFileClient      file      = directory.GetFileClient(fileName);

            // Download the file
            ShareFileDownloadInfo download = await file.DownloadAsync();

            using (FileStream stream = File.OpenWrite(localFilePath))
            {
                await download.Content.CopyToAsync(stream);
            }
            #endregion Snippet:Azure_Storage_Files_Shares_Samples_Sample01b_HelloWorldAsync_DownloadAsync
        }
コード例 #6
0
        public static bool WriteStringToAzureFileShare(string storageConnString, string shareName, string fileName, string content)
        {
            if (!azureAuthenticated)
            {
                return(false);
            }
            try
            {
                ShareClient          share     = new ShareClient(storageConnString, shareName);
                ShareDirectoryClient directory = share.GetRootDirectoryClient();
                directory.DeleteFile(fileName);
                ShareFileClient file = directory.GetFileClient(fileName);

                byte[] byteArray = Encoding.UTF8.GetBytes(content);
                using (MemoryStream stream = new MemoryStream(byteArray))
                {
                    file.Create(stream.Length);
                    file.UploadRange(
                        new HttpRange(0, stream.Length),
                        stream);
                }
                return(true);
            }
            catch (Exception _)
            {
                // Log Ex.Message here
                return(false);
            }
        }
コード例 #7
0
        public async Task UploadAsync(ConnectorConfig config, string fullFileName, MemoryStream stream)
        {
            var dirName  = Path.GetDirectoryName(fullFileName).ToString();
            var fileName = Path.GetFileName(fullFileName).ToString();

            ShareClient share = new ShareClient(config.connectionString, config.shareName);

            if (!share.Exists())
            {
                await share.CreateAsync();
            }

            ShareDirectoryClient directory = share.GetDirectoryClient(dirName);

            if (!directory.Exists())
            {
                await directory.CreateAsync();
            }

            ShareFileClient file = directory.GetFileClient(fileName);
            await file.CreateAsync(stream.Length);

            await file.UploadAsync(stream);

            /*
             * await file.UploadRange(
             *      ShareFileRangeWriteType.Update,
             *      new HttpRange(0, stream.Length),
             *      stream);*/
        }
コード例 #8
0
        // <snippet_RestoreFileFromSnapshot>
        //-------------------------------------------------
        // Restore file from snapshot
        //-------------------------------------------------
        public async Task RestoreFileFromSnapshot(string shareName, string directoryName, string fileName, string snapshotTime)
        {
            // Get the connection string from app settings
            string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

            // Instatiate a ShareServiceClient
            ShareServiceClient shareService = new ShareServiceClient(connectionString);

            // Get a ShareClient
            ShareClient share = shareService.GetShareClient(shareName);

            // Get a ShareDirectoryClient, then a ShareFileClient to the live file
            ShareDirectoryClient liveDir  = share.GetDirectoryClient(directoryName);
            ShareFileClient      liveFile = liveDir.GetFileClient(fileName);

            // Get as ShareClient that points to a snapshot
            ShareClient snapshot = share.WithSnapshot(snapshotTime);

            // Get a ShareDirectoryClient, then a ShareFileClient to the snapshot file
            ShareDirectoryClient snapshotDir  = snapshot.GetDirectoryClient(directoryName);
            ShareFileClient      snapshotFile = snapshotDir.GetFileClient(fileName);

            // Restore the file from the snapshot
            ShareFileCopyInfo copyInfo = await liveFile.StartCopyAsync(snapshotFile.Uri);

            // Display the status of the operation
            Console.WriteLine($"Restore status: {copyInfo.CopyStatus}");
        }
コード例 #9
0
        public IActionResult DownloadFile(string userId, string fileName)
        {
            // Get a reference to a share and then create it
            ShareClient share = new ShareClient(Secret.AzureConnectionString, Secret.AzureFileShareName);

            if (!share.Exists())
            {
                share.Create();
            }

            // Get a reference to a directory and create it
            ShareDirectoryClient directory = share.GetDirectoryClient(Auth0Utils.GetUserFolder());

            if (!directory.Exists())
            {
                directory.Create();
            }

            // Get a reference to a file and upload it
            ShareFileClient fileClient = directory.GetFileClient(fileName);

            if (fileClient.Exists())
            {
                //ShareFileDownloadInfo download = file.Download();
                return(File(fileClient.OpenRead(), "application/octet-stream"));
            }
            else
            {
                return(NotFound());
            }
        }
コード例 #10
0
        public List <Metadata> GetMetadatas()
        {
            List <Metadata> metadatas = new List <Metadata>();

            MetadataParser parser =
                new MetadataParser(
                    new MetadataConverter());

            try
            {
                var remaining = new Queue <ShareDirectoryClient>();

                remaining.Enqueue(shareClient.GetDirectoryClient(this.path));
                while (remaining.Count > 0)
                {
                    ShareDirectoryClient dir = remaining.Dequeue();
                    foreach (ShareFileItem item in dir.GetFilesAndDirectories())
                    {
                        if (item.IsDirectory)
                        {
                            remaining.Enqueue(dir.GetSubdirectoryClient(item.Name));
                        }
                        else if (item.Name.Contains(FILE_EXTENSION))
                        {
                            Console.WriteLine($"  In {dir.Uri.AbsolutePath} found {item.Name}");

                            ShareFileClient file = dir.GetFileClient(item.Name);

                            ShareFileDownloadInfo fileContents = file.Download();
                            string json;
                            using (MemoryStream ms = new MemoryStream())
                            {
                                fileContents.Content.CopyTo(ms);
                                json = Encoding.UTF8.GetString(ms.ToArray());
                            }

                            // Parse json string
                            Metadata metadata = parser.Parse(json);

                            // Sets the dataset path relative to the Uri and Path specified in constructor
                            var filePath =
                                Path.GetRelativePath(this.path, file.Path)
                                .Replace(FILE_EXTENSION, "");

                            metadata.Dataset.DatasetPath = filePath;

                            metadatas.Add(metadata);
                        }
                    }
                }

                Console.WriteLine($"Found a total of {metadatas.Count} files");
            }
            catch (Exception e)
            {
                Console.WriteLine($"An error ocurred: {e}");
            }

            return(metadatas);
        }
コード例 #11
0
        public async Task <string> SaveFileUri(string fileShare, string fileName, string fileContent)
        {
            ShareClient share = new ShareClient(connectionString, fileShare);

            if (!share.Exists())
            {
                share.Create();
            }
            ShareDirectoryClient rootDir = share.GetRootDirectoryClient();
            ShareFileClient      file    = rootDir.GetFileClient(fileName);

            if (!file.Exists())
            {
                file.Create(fileContent.Length);
            }

            byte[] outBuff = Encoding.ASCII.GetBytes(fileContent);
            ShareFileOpenWriteOptions options = new ShareFileOpenWriteOptions {
                MaxSize = outBuff.Length
            };
            var stream = await file.OpenWriteAsync(true, 0, options);

            stream.Write(outBuff, 0, outBuff.Length);
            stream.Flush();
            return(file.Uri.ToString());
        }
コード例 #12
0
ファイル: MyWebUtils.cs プロジェクト: adrianypc/CodeClay
        public static ShareFileClient GetAzureFile(string folderName, string fileName)
        {
            string shareName = MyWebUtils.Application.ToLower();

            string connectionString = Properties.Settings.Default.StorageConnectionString;

            ShareClient share = new ShareClient(connectionString, shareName);

            // Create the share if it doesn't already exist
            share.CreateIfNotExists();

            if (share.Exists())
            {
                ShareDirectoryClient subFolder = share.GetRootDirectoryClient();

                foreach (string subFolderName in folderName.Split('\\'))
                {
                    subFolder = subFolder.GetSubdirectoryClient(subFolderName);
                    subFolder.CreateIfNotExists();
                }

                return(subFolder.GetFileClient(fileName));
            }

            return(null);
        }
コード例 #13
0
        public string Download(string connectionString, string shareName, string directory, string fileName)
        {
            // Get a reference to the file
            ShareClient          share           = new ShareClient(connectionString, shareName);
            ShareDirectoryClient directoryClient = share.GetDirectoryClient(directory);
            ShareFileClient      file            = directoryClient.GetFileClient(fileName);

            string localFilePath = @"C:\audio\sales\trusted\Sales\" + file.Name;

            try
            {
                // Download the file
                ShareFileDownloadInfo download = file.Download();

                using (FileStream stream = File.OpenWrite(localFilePath))
                {
                    download.Content.CopyTo(stream);
                }
            }
            catch (Exception e)
            {
                _errors.Add(fileName + ": " + e.Message);
            }

            return(localFilePath);
        }
コード例 #14
0
        public async Task <IActionResult> GetLogo(string fileName)
        {
            var connectionString = _configuration.GetSection("StorageAccount:ConnectionString").Value;
            var shareName        = _configuration.GetSection("StorageAccount:ShareName").Value;

            if (string.IsNullOrEmpty(fileName))
            {
                return(NotFound());
            }

            var extension = GetExtensionFileName(fileName);

            var contentType = GetContentTypeForResponse(extension);

            ShareClient share = new ShareClient(connectionString, shareName);

            ShareDirectoryClient directory = share.GetDirectoryClient("logos");

            var file = directory.GetFileClient(fileName);

            if (!file.Exists())
            {
                return(NotFound());
            }

            Stream stream = await file.OpenReadAsync();

            return(File(stream, contentType));
        }
コード例 #15
0
        private static async Task MoveFileAsync(ShareClient share, ShareDirectoryClient directory, ShareFileClient file, string outputFolder)
        {
            try
            {
                ShareDirectoryClient outputDirectory = share.GetDirectoryClient(outputFolder);

                await outputDirectory.CreateIfNotExistsAsync();

                if (outputDirectory.Exists())
                {
                    ShareFileClient outputFile = outputDirectory.GetFileClient(file.Name);
                    await outputFile.StartCopyAsync(file.Uri);

                    if (await outputFile.ExistsAsync())
                    {
                        Log($"{file.Uri} copied to {outputFile.Uri}");
                        await DeleteFileAsync(file);
                    }
                }
            }
            catch (Exception ex)
            {
                Log(ex);
            }
        }
コード例 #16
0
        public async Task <string> ReadFile(string fileShare, string fileName)
        {
            string      json  = "";
            ShareClient share = new ShareClient(connectionString, fileShare);

            if (!share.Exists())
            {
                Exception error = new Exception($"Fileshare {fileName} does not exist ");
                throw error;
            }
            ShareDirectoryClient directory = share.GetRootDirectoryClient();
            ShareFileClient      file      = directory.GetFileClient(fileName);

            if (file.Exists())
            {
                using (Stream fileStream = await file.OpenReadAsync())
                {
                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        json = reader.ReadToEnd();
                    }
                }
            }
            else
            {
                Exception error = new Exception($"File {fileName} does not exist in Azure storage ");
                throw error;
            }
            return(json);
        }
コード例 #17
0
        public IActionResult DeleteFile(string userId, string fileName)
        {
            // Get a reference to a share and then create it
            ShareClient share = new ShareClient(Secret.AzureConnectionString, Secret.AzureFileShareName);

            if (!share.Exists())
            {
                share.Create();
            }

            // Get a reference to a directory and create it
            ShareDirectoryClient directory = share.GetDirectoryClient(Auth0Utils.GetUserFolder());

            if (!directory.Exists())
            {
                directory.Create();
            }

            // Get a reference to a file and upload it
            ShareFileClient fileClient = directory.GetFileClient(fileName);

            fileClient.DeleteIfExists();

            return(Ok());
        }
コード例 #18
0
        public static FoundFile ScanForANewFile()
        {
            ShareClient share = new ShareClient(CONNECTIONSTRING, SHARENAME);

            foreach (ShareFileItem item in share.GetRootDirectoryClient().GetFilesAndDirectories())    // loop through all plants
            {
                if (item.Name == "System")
                {
                    continue;
                }
                if (item.IsDirectory)
                {
                    var subDirectory         = share.GetRootDirectoryClient().GetSubdirectoryClient(item.Name);
                    ShareDirectoryClient dir = subDirectory.GetSubdirectoryClient("immediateScan");
                    if (!dir.Exists())
                    {
                        continue;
                    }
                    foreach (var file in dir.GetFilesAndDirectories())
                    {
                        if (!file.IsDirectory)
                        {
                            string tempFileName = Path.GetTempFileName();
                            DownloadFile(dir.GetFileClient(file.Name), tempFileName);
                            return(new FoundFile(/*item.Name, */ file.Name, dir.Path + "/" + file.Name, tempFileName));
                        }
                    }
                }
            }
            return(null);
        }
コード例 #19
0
#pragma warning disable CA1806 // Do not ignore method results
        public override void Run(CancellationToken cancellationToken)
        {
            var serviceClient = new ShareServiceClient(s_connectionString);

            new ShareServiceClient(s_serviceUri);
            new ShareServiceClient(s_serviceUri, s_azureSasCredential);
            new ShareServiceClient(s_serviceUri, s_storageSharedKey);

            var shareClient = new ShareClient(s_connectionString, "foo");

            new ShareClient(s_shareUri);
            new ShareClient(s_shareUri, s_azureSasCredential);
            new ShareClient(s_shareUri, s_storageSharedKey);

            var directoryClient = new ShareDirectoryClient(s_connectionString, "foo", "bar");

            new ShareDirectoryClient(s_directoryUri);
            new ShareDirectoryClient(s_directoryUri, s_azureSasCredential);
            new ShareDirectoryClient(s_directoryUri, s_storageSharedKey);

            new ShareFileClient(s_connectionString, "foo", "bar/baz");
            new ShareFileClient(s_fileUri);
            new ShareFileClient(s_fileUri, s_azureSasCredential);
            new ShareFileClient(s_fileUri, s_storageSharedKey);

            serviceClient.GetShareClient("foo");
            shareClient.GetDirectoryClient("bar");
            directoryClient.GetFileClient("baz");
        }
コード例 #20
0
        private static (ShareClient, ShareDirectoryClient, ShareFileClient) GetFileShareClients(string connectionString, string shareName, string dirName, string fileName)
        {
            ShareClient          share     = new ShareClient(connectionString, shareName);
            ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
            ShareFileClient      file      = directory.GetFileClient(fileName);

            return(share, directory, file);
        }
        /// <summary>Creates a wrapper around the file so that you can perform actions on it (doesn't do anything to the server).</summary>
        /// <param name="directoryName">The directory of interest or empty/null if you want the root directory</param>
        /// <param name="fileName">The file name without a path</param>
        public ShareFileClient CreateClient(string directoryName, string fileName)
        {
            ShareDirectoryClient directory = string.IsNullOrWhiteSpace(directoryName) ?
                                             _share.GetRootDirectoryClient() :
                                             _share.GetDirectoryClient(directoryName);

            return(directory.GetFileClient(fileName));
        }
コード例 #22
0
        public async Task UploadFileAsync(String filename, Stream stream)
        {
            ShareDirectoryClient raiz = this.cliente.GetRootDirectoryClient();
            ShareFileClient      file = raiz.GetFileClient(filename);
            await file.CreateAsync(stream.Length);

            await file.UploadAsync(stream);
        }
コード例 #23
0
        // <snippet_CreateShare>
        //-------------------------------------------------
        // Create a file share
        //-------------------------------------------------
        public async Task CreateShareAsync(string shareName)
        {
            // <snippet_CreateShareClient>
            // Get the connection string from app settings
            string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

            // Instantiate a ShareClient which will be used to create and manipulate the file share
            ShareClient share = new ShareClient(connectionString, shareName);
            // </snippet_CreateShareClient>

            // Create the share if it doesn't already exist
            await share.CreateIfNotExistsAsync();

            // Ensure that the share exists
            if (await share.ExistsAsync())
            {
                Console.WriteLine($"Share created: {share.Name}");

                // Get a reference to the sample directory
                ShareDirectoryClient directory = share.GetDirectoryClient("CustomLogs");

                // Create the directory if it doesn't already exist
                await directory.CreateIfNotExistsAsync();

                // Ensure that the directory exists
                if (await directory.ExistsAsync())
                {
                    // Get a reference to a file object
                    ShareFileClient file = directory.GetFileClient("Log1.txt");

                    // Ensure that the file exists
                    if (await file.ExistsAsync())
                    {
                        Console.WriteLine($"File exists: {file.Name}");

                        // Download the file
                        ShareFileDownloadInfo download = await file.DownloadAsync();

                        // Save the data to a local file, overwrite if the file already exists
                        using (FileStream stream = File.OpenWrite(@"downloadedLog1.txt"))
                        {
                            await download.Content.CopyToAsync(stream);

                            await stream.FlushAsync();

                            stream.Close();

                            // Display where the file was saved
                            Console.WriteLine($"File downloaded: {stream.Name}");
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine($"CreateShareAsync failed");
            }
        }
コード例 #24
0
ファイル: Program.cs プロジェクト: nimccoll/AzureBatchSamples
        static void Main(string[] args)
        {
            string downloadDirectory = args[0];

            // Create a BlobServiceClient object which will be used to create a container client
            BlobServiceClient blobServiceClient = new BlobServiceClient(AZURE_STORAGE_CONNECTION_STRING);

            // Create a unique name for the container
            string containerName = "startupfiles";

            // Create the container and return a container client object
            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);

            List <BlobItem> blobs = containerClient.GetBlobs().ToList();

            // Download the blob files in parallel - maximum of 10 at a time }
            Parallel.ForEach(blobs, new ParallelOptions()
            {
                MaxDegreeOfParallelism = 10
            }, blob =>
            {
                string downloadFilePath   = Path.Combine(downloadDirectory, blob.Name);
                BlobClient blobClient     = containerClient.GetBlobClient(blob.Name);
                BlobDownloadInfo download = blobClient.Download();

                using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
                {
                    download.Content.CopyTo(downloadFileStream);
                    downloadFileStream.Close();
                }
            });

            string shareName = "startupfiles";

            ShareClient shareClient = new ShareClient(AZURE_FILES_CONNECTION_STRING, shareName);

            if (shareClient.Exists())
            {
                ShareDirectoryClient shareDirectoryClient = shareClient.GetRootDirectoryClient();

                List <ShareFileItem> items = shareDirectoryClient.GetFilesAndDirectories().ToList();
                foreach (ShareFileItem item in items)
                {
                    if (!item.IsDirectory)
                    {
                        string                downloadFilePath = Path.Combine(downloadDirectory, item.Name);
                        ShareFileClient       shareFileClient  = shareDirectoryClient.GetFileClient(item.Name);
                        ShareFileDownloadInfo download         = shareFileClient.Download();
                        using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
                        {
                            download.Content.CopyTo(downloadFileStream);
                            downloadFileStream.Close();
                        }
                    }
                }
            }
        }
コード例 #25
0
    /// <summary>
    /// Uploads the asynchronous.
    /// </summary>
    /// <param name="storageFile">The storage file.</param>
    /// <param name="overwrite">if set to <c>true</c> [overwrite].</param>
    /// <exception cref="System.ArgumentNullException">storageFile</exception>
    /// <exception cref="System.ArgumentException">storageFile</exception>
    /// <exception cref="CloudFileSystem.Core.V1.FileManagement.Storage.StorageException">
    /// rootDirectoryExists - UploadAsync or fileExists - UploadAsync or Path - UploadAsync
    /// </exception>
    public async Task UploadAsync(StorageFile storageFile, bool overwrite = false)
    {
        if (storageFile is null)
        {
            throw new ArgumentNullException(nameof(storageFile));
        }
        if (string.IsNullOrWhiteSpace(storageFile.SafeName) && string.IsNullOrWhiteSpace(storageFile.FileName))
        {
            throw new ArgumentException(nameof(storageFile));
        }

        ShareDirectoryClient rootDirectory = this._shareClient.GetRootDirectoryClient();
        bool rootDirectoryExists           = await rootDirectory.ExistsAsync();

        if (!rootDirectoryExists)
        {
            throw new StorageException(nameof(rootDirectoryExists), nameof(this.UploadAsync));
        }

        string          safeName   = storageFile.SafeName ?? this.RemoveInvalidCharacters(storageFile.FileName);
        ShareFileClient file       = rootDirectory.GetFileClient(safeName);
        bool            fileExists = await file.ExistsAsync();

        if (fileExists && !overwrite)
        {
            throw new StorageException(nameof(fileExists), nameof(this.UploadAsync));
        }

        await file.CreateAsync(storageFile.Content.Length);

        using var reader = new BinaryReader(storageFile.Content);
        int  blockSize = 1 * 1024 * 1024; // 1MB
        long offset    = 0;

        while (true)
        {
            byte[] buffer = reader.ReadBytes(blockSize);
            if (buffer.Length == 0)
            {
                break;
            }

            using var uploadChunk = new MemoryStream();
            uploadChunk.Write(buffer, 0, buffer.Length);
            uploadChunk.Position = 0;

            var httpRange = new HttpRange(offset, buffer.Length);
            await file.UploadRangeAsync(httpRange, uploadChunk);

            offset += buffer.Length;
        }

        if (string.IsNullOrWhiteSpace(file.Path))
        {
            throw new StorageException(nameof(file.Path), nameof(this.UploadAsync));
        }
    }
コード例 #26
0
        public async Task UploadRangeFromUriAsync_SourceBearerTokenFail()
        {
            // Arrange
            BlobServiceClient blobServiceClient = InstrumentClient(new BlobServiceClient(
                                                                       new Uri(Tenants.TestConfigOAuth.BlobServiceEndpoint),
                                                                       Tenants.GetOAuthCredential(Tenants.TestConfigOAuth),
                                                                       GetBlobOptions()));
            BlobContainerClient containerClient = InstrumentClient(blobServiceClient.GetBlobContainerClient(GetNewShareName()));

            try
            {
                await containerClient.CreateIfNotExistsAsync();

                AppendBlobClient appendBlobClient = InstrumentClient(containerClient.GetAppendBlobClient(GetNewFileName()));
                await appendBlobClient.CreateAsync();

                byte[] data = GetRandomBuffer(Constants.KB);
                using Stream stream = new MemoryStream(data);
                await appendBlobClient.AppendBlockAsync(stream);

                ShareServiceClient serviceClient = SharesClientBuilder.GetServiceClient_OAuthAccount_SharedKey();
                await using DisposingShare test = await GetTestShareAsync(
                                service : serviceClient,
                                shareName : GetNewShareName());

                ShareDirectoryClient directoryClient = InstrumentClient(test.Share.GetDirectoryClient(GetNewDirectoryName()));
                await directoryClient.CreateAsync();

                ShareFileClient fileClient = InstrumentClient(directoryClient.GetFileClient(GetNewFileName()));
                await fileClient.CreateAsync(Constants.KB);

                HttpAuthorization sourceAuthHeader = new HttpAuthorization(
                    "Bearer",
                    "auth token");

                ShareFileUploadRangeFromUriOptions options = new ShareFileUploadRangeFromUriOptions
                {
                    SourceAuthentication = sourceAuthHeader
                };

                HttpRange range = new HttpRange(0, Constants.KB);

                // Act
                await TestHelper.AssertExpectedExceptionAsync <RequestFailedException>(
                    fileClient.UploadRangeFromUriAsync(
                        sourceUri: appendBlobClient.Uri,
                        range: range,
                        sourceRange: range,
                        options: options),
                    e => Assert.AreEqual("CannotVerifyCopySource", e.ErrorCode));
            }
            finally
            {
                await containerClient.DeleteIfExistsAsync();
            }
        }
コード例 #27
0
        public async Task UploadRangeFromUriAsync_SourceBearerToken()
        {
            // Arrange
            BlobServiceClient blobServiceClient = InstrumentClient(new BlobServiceClient(
                                                                       new Uri(TestConfigOAuth.BlobServiceEndpoint),
                                                                       GetOAuthCredential(TestConfigOAuth),
                                                                       GetBlobOptions()));
            BlobContainerClient containerClient = InstrumentClient(blobServiceClient.GetBlobContainerClient(GetNewShareName()));

            try
            {
                await containerClient.CreateIfNotExistsAsync();

                AppendBlobClient appendBlobClient = InstrumentClient(containerClient.GetAppendBlobClient(GetNewFileName()));
                await appendBlobClient.CreateAsync();

                byte[] data = GetRandomBuffer(Constants.KB);
                using Stream stream = new MemoryStream(data);
                await appendBlobClient.AppendBlockAsync(stream);

                ShareServiceClient serviceClient = GetServiceClient_OAuth_SharedKey();
                await using DisposingShare test = await GetTestShareAsync(
                                service : serviceClient,
                                shareName : GetNewShareName());

                ShareDirectoryClient directoryClient = InstrumentClient(test.Share.GetDirectoryClient(GetNewDirectoryName()));
                await directoryClient.CreateAsync();

                ShareFileClient fileClient = InstrumentClient(directoryClient.GetFileClient(GetNewFileName()));
                await fileClient.CreateAsync(Constants.KB);

                string sourceBearerToken = await GetAuthToken();

                HttpAuthorization sourceAuthHeader = new HttpAuthorization(
                    "Bearer",
                    sourceBearerToken);

                ShareFileUploadRangeFromUriOptions options = new ShareFileUploadRangeFromUriOptions
                {
                    SourceAuthentication = sourceAuthHeader
                };

                HttpRange range = new HttpRange(0, Constants.KB);

                // Act
                await fileClient.UploadRangeFromUriAsync(
                    sourceUri : appendBlobClient.Uri,
                    range : range,
                    sourceRange : range,
                    options : options);
            }
            finally
            {
                await containerClient.DeleteIfExistsAsync();
            }
        }
コード例 #28
0
ファイル: Test.cs プロジェクト: AzureDevelopment/m11
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string connectionString = "DefaultEndpointsProtocol=https;AccountName=m10l2;AccountKey=jKxmGhpm9FWua8lWReXyt9gft5xConbXInXr8IRQj2Z1lWVL6YIWNl/pmqm3EQkdh7YgJlTRPakW8w2GiSfswg==;EndpointSuffix=core.windows.net";
            string containerName    = "test";
            string queueName        = "test";
            string shareName        = "test";
            string blobName         = $"{Guid.NewGuid().ToString()}.json";
            string fileName         = $"{Guid.NewGuid().ToString()}.json";

            BlobContainerClient container = new BlobContainerClient(connectionString, containerName);
            BlobClient          blob      = container.GetBlobClient(blobName);
            Stream uploadStream           = new MemoryStream();

            req.Body.CopyTo(uploadStream);
            uploadStream.Position = 0;
            blob.Upload(uploadStream);
            Stream      result = (await blob.DownloadAsync()).Value.Content;
            QueueClient queue  = new QueueClient(connectionString, queueName);

            Stream messageStream = new MemoryStream();

            req.Body.Position = 0;
            req.Body.CopyTo(messageStream);
            using (StreamReader sr = new StreamReader(messageStream))
            {
                queue.SendMessage(sr.ReadToEnd());
            }

            QueueMessage[] messages = (await queue.ReceiveMessagesAsync()).Value;

            ShareClient          share     = new ShareClient(connectionString, shareName);
            ShareDirectoryClient directory = share.GetRootDirectoryClient();

            Stream fileStream = new MemoryStream();

            req.Body.Position = 0;
            req.Body.CopyTo(fileStream);
            fileStream.Position = 0;
            ShareFileClient file = directory.GetFileClient(fileName);
            await file.CreateAsync(fileStream.Length);

            file.UploadRange(new HttpRange(0, fileStream.Length), fileStream);
            var downloadedFile = file.Download();

            using (StreamReader sr = new StreamReader(downloadedFile.Value.Content))
            {
                string uploadedFile = await sr.ReadToEndAsync();

                return(new OkObjectResult(uploadedFile));
            }
        }
コード例 #29
0
        public IActionResult UploadAzure()
        {
            try
            {
                var file       = Request.Form.Files[0];
                var folderName = Path.Combine("StaticFiles", "Images");
                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

                if (file.Length > 0)
                {
                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    var fullPath = Path.Combine(pathToSave, fileName);
                    var dbPath   = Path.Combine(folderName, fileName);

                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }

                    // Get a reference to a share and then create it
                    ShareClient share = new ShareClient("DefaultEndpointsProtocol=https;AccountName=faceidentity;AccountKey=N/gO9IA0exmgv4yH+ZISlxc0wxv2haDMWi2fZoL2/ErfqM/KHAePM4qkwMjnWEXesDvDidDVYJqKAtv3FvaXnQ==;EndpointSuffix=core.windows.net", "employeesimages");
                    // share.Create();

                    // Get a reference to a directory and create it
                    ShareDirectoryClient directory = share.GetDirectoryClient("auth");
                    // directory.Create();

                    // Get a reference to a file and upload it
                    ShareFileClient fileAzure = directory.GetFileClient(fileName);
                    using (FileStream stream = System.IO.File.OpenRead(fullPath))
                    {
                        fileAzure.Create(stream.Length);
                        fileAzure.UploadRange(
                            new HttpRange(0, stream.Length),
                            stream);
                    }

                    string fileAzurePath = fileAzure.Uri.ToString();
                    //System.IO.File.Delete(fullPath);

                    return(Ok(new { fileAzurePath }));
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(500, $"Internal server error: {ex}"));
            }
        }
コード例 #30
0
        public async Task Sample01b_HelloWorldAsync_TraverseAsync()
        {
            // Create a temporary Lorem Ipsum file on disk that we can upload
            string originalPath = CreateTempFile(SampleFileContent);

            // Get a reference to a share named "sample-share" and then create it
            string      shareName = Randomize("sample-share");
            ShareClient share     = new ShareClient(ConnectionString, shareName);
            await share.CreateAsync();

            try
            {
                // Create a bunch of directories
                ShareDirectoryClient first = await share.CreateDirectoryAsync("first");

                await first.CreateSubdirectoryAsync("a");

                await first.CreateSubdirectoryAsync("b");

                ShareDirectoryClient second = await share.CreateDirectoryAsync("second");

                await second.CreateSubdirectoryAsync("c");

                await second.CreateSubdirectoryAsync("d");

                await share.CreateDirectoryAsync("third");

                ShareDirectoryClient fourth = await share.CreateDirectoryAsync("fourth");

                ShareDirectoryClient deepest = await fourth.CreateSubdirectoryAsync("e");

                // Upload a file named "file"
                ShareFileClient file = deepest.GetFileClient("file");
                using (FileStream stream = File.OpenRead(originalPath))
                {
                    await file.CreateAsync(stream.Length);

                    await file.UploadRangeAsync(
                        ShareFileRangeWriteType.Update,
                        new HttpRange(0, stream.Length),
                        stream);
                }

                await Sample01b_HelloWorldAsync.TraverseAsync(ConnectionString, shareName);
            }
            finally
            {
                await share.DeleteAsync();
            }
        }