Exemplo n.º 1
0
        /// <summary>
        /// Returns the length of a file exists in the current directory
        /// </summary>
        /// <param name="filename">The name of the file to check</param>
        /// <returns>The length of the file. Any exceptions are thrown.</returns>
        public long FileLength(string filename)
        {
            if (FileShare == null || Directory == null)
            {
                throw new Exception("Cannot check to Azure file exists: " + filename + " (null share or directory).");
            }

            // Get a reference to the file
            ShareFileClient file = Directory.GetFileClient(filename);

            // Get the file length.
            ShareFileProperties props = file.GetProperties();

            return(props.ContentLength);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Copy a file from the current directory
        /// </summary>
        /// <param name="filename">The name of the file to copy</param>
        /// <param name="target">The name of the directory to copy the file to</param>
        /// <returns>Any exceptions are thrown.</returns>
        public void FileCopy(string filename, string target)
        {
            if (!this.FileExists(filename))
            {
                throw new Exception("Failed to Copy File: '" + filename + "' from '" + Directory.Name + ". File was missing.");
            }

            // Get a reference to the file
            ShareFileClient fileFrom = Directory.GetFileClient(filename);

            // Get a reference to the target directory.
            ShareDirectoryClient targetDir = FileShare.GetDirectoryClient(target);

            // Ensure that the directory exists.
            if (!targetDir.Exists())
            {
                throw new Exception("Cannot copy file to Azure directory: " + targetDir + ".");
            }
            try
            {
                ShareFileClient fileTo = targetDir.GetFileClient(filename);

                // Copy the file
                fileTo.StartCopy(fileFrom.Uri);
                ShareFileProperties props = fileTo.GetProperties();

                do
                {
                    Thread.Sleep(5);
                    //Console.WriteLine("Copy Progress: " + props.CopyProgress);
                } while (props.CopyStatus == CopyStatus.Pending);

                if (props.CopyStatus != CopyStatus.Success)
                {
                    throw new Exception("Failed to copy file: '" + filename + "' Error was: " + props.CopyStatusDescription);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to copy file: '" + filename + "' Error was: " + ex.Message);
            }
        }
        /// <summary>
        /// Manage file metadata
        /// </summary>
        /// <param name="shareServiceClient"></param>
        /// <returns></returns>
        private static async Task FileMetadataSample(ShareServiceClient shareServiceClient)
        {
            Console.WriteLine();

            // Create the share name -- use a guid in the name so it's unique.
            string      shareName   = "demotest-" + Guid.NewGuid();
            ShareClient shareClient = shareServiceClient.GetShareClient(shareName);

            try
            {
                // Create share
                Console.WriteLine("Create Share");
                await shareClient.CreateIfNotExistsAsync();

                // Create directory
                Console.WriteLine("Create directory");
                ShareDirectoryClient rootDirectory = shareClient.GetRootDirectoryClient();

                ShareFileClient file = rootDirectory.GetFileClient("demofile");

                // Create file
                Console.WriteLine("Create file");
                await file.CreateAsync(1000);

                // Set file metadata
                Console.WriteLine("Set file metadata");
                var metadata = new Dictionary <string, string> {
                    { "key1", "value1" }, { "key2", "value2" }
                };

                await file.SetMetadataAsync(metadata);

                // Fetch file attributes
                ShareFileProperties properties = await file.GetPropertiesAsync();

                Console.WriteLine("Get file metadata:");
                foreach (var keyValue in properties.Metadata)
                {
                    Console.WriteLine("    {0}: {1}", keyValue.Key, keyValue.Value);
                }
                Console.WriteLine();
            }
            catch (RequestFailedException exRequest)
            {
                Common.WriteException(exRequest);
                Console.WriteLine(
                    "Please make sure your storage account is specified correctly in the app.config - then restart the sample.");
                Console.WriteLine("Press any key to exit");
                Console.ReadLine();
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("    Exception thrown creating share.");
                Common.WriteException(ex);
                throw;
            }
            finally
            {
                // Delete share
                Console.WriteLine("Delete share");
                await shareClient.DeleteIfExistsAsync();
            }
        }
        /// <summary>
        /// Manage file properties
        /// </summary>
        /// <param name="shareServiceClient"></param>
        /// <returns></returns>
        private static async Task FilePropertiesSample(ShareServiceClient shareServiceClient)
        {
            Console.WriteLine();

            // Create the share name -- use a guid in the name so it's unique.
            string      shareName   = "demotest-" + Guid.NewGuid();
            ShareClient shareClient = shareServiceClient.GetShareClient(shareName);

            try
            {
                // Create share
                Console.WriteLine("Create Share");
                await shareClient.CreateIfNotExistsAsync();

                // Create directory
                Console.WriteLine("Create directory");
                ShareDirectoryClient rootDirectory = shareClient.GetRootDirectoryClient();

                ShareFileClient file = rootDirectory.GetFileClient("demofile");

                // Create file
                Console.WriteLine("Create file");
                await file.CreateAsync(1000);

                // Set file properties
                var headers = new ShareFileHttpHeaders
                {
                    ContentType     = "plain/text",
                    ContentEncoding = new string[] { "UTF-8" },
                    ContentLanguage = new string[] { "en" }
                };

                await file.SetHttpHeadersAsync(httpHeaders : headers);

                // Fetch file attributes
                ShareFileProperties shareFileProperties = await file.GetPropertiesAsync();

                Console.WriteLine("Get file properties:");
                Console.WriteLine("    Content type: {0}", shareFileProperties.ContentType);
                Console.WriteLine("    Content encoding: {0}", string.Join("", shareFileProperties.ContentEncoding));
                Console.WriteLine("    Content language: {0}", string.Join("", shareFileProperties.ContentLanguage));
                Console.WriteLine("    Length: {0}", shareFileProperties.ContentLength);
            }
            catch (RequestFailedException exRequest)
            {
                Common.WriteException(exRequest);
                Console.WriteLine(
                    "Please make sure your storage account is specified correctly in the app.config - then restart the sample.");
                Console.WriteLine("Press any key to exit");
                Console.ReadLine();
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("    Exception thrown creating share.");
                Common.WriteException(ex);
                throw;
            }
            finally
            {
                // Delete share
                Console.WriteLine("Delete share");
                await shareClient.DeleteIfExistsAsync();
            }

            Console.WriteLine();
        }
Exemplo n.º 5
0
 /// <summary>
 /// Azure storage file constructor from Track2 get file properties output
 /// </summary>
 /// <param name="file">Cloud file object</param>
 public AzureStorageFile(ShareFileClient shareFileClient, AzureStorageContext storageContext, ShareFileProperties shareFileProperties = null, ShareClientOptions clientOptions = null)
 {
     Name = shareFileClient.Name;
     this.privateFileClient = shareFileClient;
     CloudFile = GetTrack1FileClient(shareFileClient, storageContext.StorageAccount.Credentials);
     if (shareFileProperties != null)
     {
         privateFileProperties = shareFileProperties;
         Length       = shareFileProperties.ContentLength;
         LastModified = shareFileProperties.LastModified;
     }
     Context            = storageContext;
     shareClientOptions = clientOptions;
 }
Exemplo n.º 6
0
        public override void ExecuteCmdlet()
        {
            CloudFileDirectory baseDirectory;

            switch (this.ParameterSetName)
            {
            case Constants.DirectoryParameterSetName:
                baseDirectory = this.Directory;
                break;

            case Constants.ShareNameParameterSetName:
                baseDirectory = this.BuildFileShareObjectFromName(this.ShareName).GetRootDirectoryReference();
                break;

            case Constants.ShareParameterSetName:
                baseDirectory = this.Share.GetRootDirectoryReference();
                break;

            default:
                throw new PSArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", this.ParameterSetName));
            }

            // when only track1 object input, will miss storage context, so need to build storage context for prepare the output object.
            if (this.Context == null)
            {
                this.Context = GetStorageContextFromTrack1FileServiceClient(baseDirectory.ServiceClient, DefaultContext);
            }

            ShareDirectoryClient baseDirClient = AzureStorageFileDirectory.GetTrack2FileDirClient(baseDirectory, ClientOptions);

            if (string.IsNullOrEmpty(this.Path))
            {
                ShareDirectoryGetFilesAndDirectoriesOptions listFileOptions = new ShareDirectoryGetFilesAndDirectoriesOptions();
                if (!this.ExcludeExtendedInfo.IsPresent)
                {
                    listFileOptions.Traits = ShareFileTraits.All;
                    listFileOptions.IncludeExtendedInfo = true;
                }
                Pageable <ShareFileItem>            fileItems     = baseDirClient.GetFilesAndDirectories(listFileOptions, this.CmdletCancellationToken);
                IEnumerable <Page <ShareFileItem> > fileitempages = fileItems.AsPages();
                foreach (var page in fileitempages)
                {
                    foreach (var file in page.Values)
                    {
                        if (!file.IsDirectory) // is file
                        {
                            ShareFileClient shareFileClient = baseDirClient.GetFileClient(file.Name);
                            WriteObject(new AzureStorageFile(shareFileClient, (AzureStorageContext)this.Context, file, ClientOptions));
                        }
                        else // Dir
                        {
                            ShareDirectoryClient shareDirClient = baseDirClient.GetSubdirectoryClient(file.Name);
                            WriteObject(new AzureStorageFileDirectory(shareDirClient, (AzureStorageContext)this.Context, file, ClientOptions));
                        }
                    }
                }
            }
            else
            {
                if (ExcludeExtendedInfo.IsPresent)
                {
                    WriteWarning("'-ExcludeExtendedInfo' will be omit, it only works when list file and directory without '-Path'.");
                }
                bool foundAFolder = true;
                ShareDirectoryClient     targetDir     = baseDirClient.GetSubdirectoryClient(this.Path);
                ShareDirectoryProperties dirProperties = null;

                try
                {
                    dirProperties = targetDir.GetProperties(this.CmdletCancellationToken).Value;
                }
                catch (global::Azure.RequestFailedException e) when(e.Status == 404)
                {
                    foundAFolder = false;
                }

                if (foundAFolder)
                {
                    WriteObject(new AzureStorageFileDirectory(targetDir, (AzureStorageContext)this.Context, dirProperties));
                    return;
                }

                ShareFileClient     targetFile     = baseDirClient.GetFileClient(this.Path);
                ShareFileProperties fileProperties = targetFile.GetProperties(this.CmdletCancellationToken).Value;

                WriteObject(new AzureStorageFile(targetFile, (AzureStorageContext)this.Context, fileProperties, ClientOptions));
            }
        }