Example #1
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);
            }
        }
        // </snippet_CopyFile>

        // <snippet_CopyFileToBlob>
        //-------------------------------------------------
        // Copy a file from a share to a blob
        //-------------------------------------------------
        public async Task CopyFileToBlobAsync(string shareName, string sourceFilePath, string containerName, string blobName)
        {
            Uri fileSasUri = GetFileSasUri(shareName, sourceFilePath, DateTime.UtcNow.AddHours(24), ShareFileSasPermissions.Read);

            // Get a reference to the file we created previously
            ShareFileClient sourceFile = new ShareFileClient(fileSasUri);

            // Ensure that the source file exists
            if (await sourceFile.ExistsAsync())
            {
                // Get the connection string from app settings
                string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

                // Get a reference to the destination container
                BlobContainerClient container = new BlobContainerClient(connectionString, containerName);

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

                BlobClient destBlob = container.GetBlobClient(blobName);

                await destBlob.StartCopyFromUriAsync(sourceFile.Uri);

                if (await destBlob.ExistsAsync())
                {
                    Console.WriteLine($"File {sourceFile.Name} copied to blob {destBlob.Name}");
                }
            }
        }
        // <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");
            }
        }
    /// <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));
        }
    }
        private static async Task <bool> InternalExistsAsync(ShareFileClient client, CancellationToken token)
        {
            try
            {
                return(await client.ExistsAsync(token));
            }
            catch (RequestFailedException rex)
            {
                if (rex.ErrorCode == ShareErrorCode.ParentNotFound)
                {
                    return(false);
                }

                throw;
            }
        }
    /// <summary>
    /// Downloads the asynchronous.
    /// </summary>
    /// <param name="fileName">Name of the file.</param>
    /// <returns></returns>
    /// <exception cref="System.ArgumentNullException">fileName</exception>
    /// <exception cref="CloudFileSystem.Core.V1.FileManagement.Storage.StorageException">
    /// shareExists - DownloadAsync or rootDirectoryExists - DownloadAsync or fileExists -
    /// DownloadAsync or downloadResponse - DownloadAsync
    /// </exception>
    public async Task <StorageFile> DownloadAsync(string fileName)
    {
        if (string.IsNullOrWhiteSpace(fileName))
        {
            throw new ArgumentNullException(nameof(fileName));
        }

        bool shareExists = await this._shareClient.ExistsAsync();

        if (!shareExists)
        {
            throw new StorageException(nameof(shareExists), nameof(this.DownloadAsync));
        }

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

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

        string          safeName   = this.RemoveInvalidCharacters(fileName);
        ShareFileClient file       = rootDirectory.GetFileClient(safeName);
        bool            fileExists = await file.ExistsAsync();

        if (!fileExists)
        {
            throw new StorageException(nameof(fileExists), nameof(this.DownloadAsync));
        }

        var downloadResponse = await file.DownloadAsync();

        if (downloadResponse is null || downloadResponse.Value is null)
        {
            throw new StorageException(nameof(downloadResponse), nameof(this.DownloadAsync));
        }

        return(new StorageFile(downloadResponse.Value.Content, downloadResponse.Value.ContentType, fileName, safeName));
    }
        // </snippet_SetMaxShareSize>

        // <snippet_CopyFile>
        //-------------------------------------------------
        // Copy file within a directory
        //-------------------------------------------------
        public async Task CopyFileAsync(string shareName, string sourceFilePath, string destFilePath)
        {
            // Get the connection string from app settings
            string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

            // Get a reference to the file we created previously
            ShareFileClient sourceFile = new ShareFileClient(connectionString, shareName, sourceFilePath);

            // Ensure that the source file exists
            if (await sourceFile.ExistsAsync())
            {
                // Get a reference to the destination file
                ShareFileClient destFile = new ShareFileClient(connectionString, shareName, destFilePath);

                // Start the copy operation
                await destFile.StartCopyAsync(sourceFile.Uri);

                if (await destFile.ExistsAsync())
                {
                    Console.WriteLine($"{sourceFile.Uri} copied to {destFile.Uri}");
                }
            }
        }