コード例 #1
0
        /// <summary>
        /// Retrieve files and folders under the current folder from XStore
        /// </summary>
        /// <param name="blobContainer">Blob container</param>
        /// <param name="srcPath">XStore path</param>
        /// <param name="files">String array of file names in the folder</param>
        /// <param name="folders">String array of subfolder names in the folder</param>
        /// <param name="helper">The timeout helper object.</param>
        private void GetFilesAndSubfoldersFromXStore(
            CloudBlobContainer blobContainer,
            string srcPath,
            out string[] files,
            out string[] folders,
            TimeoutHelper helper)
        {
            List <string> fileList   = new List <string>();
            List <string> folderList = new List <string>();

            CloudBlobDirectory cloudBlobDirectory = blobContainer.GetDirectoryReference(this.ConvertUriToBlobReference(srcPath));

            // Azure storage team has a bug that the same BlobDirectory can be duplicated in return
            // to work around this issue we always check if the same directory has been added
            // [TO DO] this is to be removed once azure storage team fixes this issue
            HashSet <string> blobDirectories = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

#if !DotNetCoreClr
            IEnumerable <IListBlobItem> blobItems = helper != null
                ? cloudBlobDirectory.ListBlobs(false, BlobListingDetails.None, GetRequestOptions(helper))
                : cloudBlobDirectory.ListBlobs();
#else
            BlobContinuationToken continuationToken = null;
            do
            {
                BlobResultSegment resultSegment = helper != null
                    ? cloudBlobDirectory.ListBlobsSegmentedAsync(false, BlobListingDetails.None, null, continuationToken, GetRequestOptions(helper), null).Result
                    : cloudBlobDirectory.ListBlobsSegmentedAsync(continuationToken).Result;

                IEnumerable <IListBlobItem> blobItems = resultSegment.Results;
                continuationToken = resultSegment.ContinuationToken;
#endif
            foreach (IListBlobItem blobItem in blobItems)
            {
                Uri uri = blobItem.Uri;
                if (blobItem is CloudBlobDirectory)
                {
                    if (!blobDirectories.Contains(uri.LocalPath.Trim()))
                    {
                        blobDirectories.Add(uri.LocalPath.Trim());
                        folderList.Add(this.ConvertUriToBlobReference(uri.LocalPath));
                    }
                }
                else
                {
                    fileList.Add(this.ConvertUriToBlobReference(uri.LocalPath));
                }
            }
#if DotNetCoreClr
        }

        while (continuationToken != null)
        {
            ;
        }
コード例 #2
0
        /// <summary>
        /// List all directories directly parented to this directory.
        /// </summary>
        /// <returns>A list of directory references.</returns>
        public IEnumerable<FileStoreDirectory> GetDirectories()
        {
            List<FileStoreDirectory> Entries = new List<FileStoreDirectory>();

            foreach (var Entry in Directory.ListBlobs())
            {
                if (Entry.GetType() == typeof(CloudBlobDirectory))
                    Entries.Add(new AzureFileStoreDirectory((CloudBlobDirectory)Entry));
            }

            return Entries;
        }
コード例 #3
0
 public Task DeleteAsync(CancellationToken cancellationToken = default)
 {
     return(Task.Run(async() =>
     {
         foreach (IListBlobItem listItem in _directory.ListBlobs())
         {
             ICloudBlob blob = await _client.GetBlobReferenceFromServerAsync(
                 listItem.Uri, cancellationToken)
                               .ConfigureAwait(false);
             await blob.DeleteIfExistsAsync(cancellationToken)
             .ConfigureAwait(false);
         }
     }, cancellationToken));
 }
コード例 #4
0
        public IEnumerable <IStorageDirectory> GetDirectories()
        {
            if (_directory != null)
            {
                return
                    (_directory.ListBlobs()
                     .OfType <CloudBlobDirectory>()
                     .Select(blob => new AzureStorageDirectory(_container, blob)));
            }

            return(_container.ListBlobs()
                   .OfType <CloudBlobDirectory>()
                   .Select(blob => new AzureStorageDirectory(_container, blob)));
        }
コード例 #5
0
        public override List <FileSystem.ItemInfo> EnumerateFiles(string path, bool recurse = false)
        {
            List <ItemInfo>    result = new List <ItemInfo>();
            CloudBlobDirectory topDir = container.GetDirectoryReference(NormalizePath(path));

            foreach (IListBlobItem item in topDir.ListBlobs(recurse))
            {
                if (item.GetType() == typeof(CloudBlockBlob))
                {
                    CloudBlockBlob blob = (CloudBlockBlob)item;
                    blob.FetchAttributes();
                    if (!System.IO.Path.GetFileName(blob.Uri.AbsolutePath).Equals("void"))
                    {
                        result.Add(new ItemInfo {
                            Name = recurse ? UnNormalizePath(blob.Uri.AbsolutePath.Replace(topDir.Uri.AbsolutePath, "")) :
                                   blob.Uri.Segments[blob.Uri.Segments.Length - 1],
                            CreationTime  = blob.Properties.LastModified.Value.DateTime,
                            LastWriteTime = blob.Properties.LastModified.Value.DateTime,
                            Length        = blob.Properties.Length
                        });
                    }
                }
            }
            return(result);
        }
コード例 #6
0
        public static string ProcessText(CloudBlobContainer blobContainer, string blobDirectory, string tableName, string sqlConnString)
        {
            // decompress, replace any back-to-back double quotes,
            // grab columns for processing, delete decompressed blobs
            // or compress and overwrite if text was manipulated
            string             oldContent       = "";
            string             newContent       = "";
            string             processStep      = "Process Text";
            string             formattedColumns = "";
            CloudBlobDirectory dir = blobContainer.GetDirectoryReference(blobDirectory);

            try
            {
                foreach (var item in dir.ListBlobs(useFlatBlobListing: true))
                {
                    CloudBlockBlob compBlob   = (CloudBlockBlob)item;
                    CloudBlockBlob decompBlob = DecompressBlob(blobContainer, compBlob);

                    // read contents of blob
                    using (StreamReader readStream = new StreamReader(decompBlob.OpenRead()))
                    {
                        if (formattedColumns == "")
                        {
                            formattedColumns = ProcessColumns(readStream.ReadLine(), tableName, sqlConnString);
                        }
                    }

                    using (StreamReader readStream = new StreamReader(decompBlob.OpenRead()))
                        oldContent = readStream.ReadToEnd();

                    // if blob contains "" in any lines, replace with "
                    // polybase doesn't support escaping quotes
                    if (oldContent.Contains("\"\""))
                    {
                        newContent = oldContent.Replace("\"\"", "");

                        // upload altered blob
                        using (StreamWriter writeStream = new StreamWriter(decompBlob.OpenWrite()))
                            writeStream.Write(newContent);

                        int compressStatus = CompressBlob(blobContainer, decompBlob);

                        if (compressStatus == 0)
                        {
                            decompBlob.Delete();
                        }
                    }
                    else
                    {
                        decompBlob.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error at step: " + processStep + " :: " + ex.Message);
            }

            return(formattedColumns);
        }
コード例 #7
0
        /// <summary>
        /// Check to see if the specified blob folder exists
        /// </summary>
        /// <param name="blobContainer">Container item</param>
        /// <param name="blobUri">Blob uri of the blob folder</param>
        /// <param name="checkXStoreFolderManifest">Indicates whether to check XStore folder manifest.</param>
        /// <param name="requestOptions">Represents the Azure blob request option.</param>
        /// <returns>
        /// Returns true if exists
        /// </returns>
        public static bool XStoreFolderExists(CloudBlobContainer blobContainer, string blobUri, bool checkXStoreFolderManifest, BlobRequestOptions requestOptions)
        {
            bool folderExists = false;
            CloudBlobDirectory cloudBlobDirectory = blobContainer.GetDirectoryReference(blobUri);

#if !DotNetCoreClr
            IEnumerable <IListBlobItem> blobItems = cloudBlobDirectory.ListBlobs(false, BlobListingDetails.None, requestOptions);
#else
            BlobContinuationToken continuationToken = null;
            do
            {
                BlobResultSegment           resultSegment = cloudBlobDirectory.ListBlobsSegmentedAsync(continuationToken).Result;
                IEnumerable <IListBlobItem> blobItems     = resultSegment.Results;
                continuationToken = resultSegment.ContinuationToken;
#endif

            // Windows Azure storage has strong consistency guarantees.
            // As soon the manifest file is ready, all users are guaranteed
            // to see the complete folder
            if ((!checkXStoreFolderManifest || XStoreFileExists(blobContainer, GetXStoreFolderManifest(blobUri), requestOptions)) &&
                (blobItems.Count() > 0))
            {
                folderExists = true;
            }
#if DotNetCoreClr
        }

        while (!folderExists && (continuationToken != null))
        {
            ;
        }
コード例 #8
0
        /// <summary>
        /// Get losting of blobs in a given directory
        /// </summary>
        /// <param name="directoryName">
        /// Name of the directory
        /// </param>
        /// <returns>
        /// Collection of BlobItems
        /// </returns>
        protected ICollection <IListBlobItem> RetrieveFilesInDirectory(string directoryName)
        {
            CloudBlobDirectory   directory = Container.GetDirectoryReference(directoryName);
            List <IListBlobItem> blobs     = directory.ListBlobs().ToList();

            return(blobs);
        }
コード例 #9
0
        private static Dictionary <string, List <UserScore> > GetWkwScores(string connectionString, string containerName, string filePath)
        {
            var wkwScores = new Dictionary <string, List <UserScore> >();

            CloudStorageAccount  storageAccount = CloudStorageAccount.Parse(connectionString);
            CloudBlobClient      blobClient     = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer   container      = blobClient.GetContainerReference(containerName);
            CloudBlobDirectory   directory      = container.GetDirectoryReference(filePath);
            List <IListBlobItem> blobs          = directory.ListBlobs().ToList();

            foreach (var blob in blobs)
            {
                if (blob.GetType() == typeof(CloudBlockBlob))
                {
                    CloudBlockBlob blockBlob = (CloudBlockBlob)blob;
                    using (var reader = new StreamReader(blockBlob.OpenRead()))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            JObject          obj    = JObject.Parse(line);
                            string           user   = obj.SelectToken("User")?.ToString();
                            List <UserScore> scores = JsonConvert.DeserializeObject <List <UserScore> >(obj.SelectToken("WkwScore")?.ToString());
                            wkwScores[user] = scores;
                        }
                    }
                }
            }

            return(wkwScores);
        }
コード例 #10
0
        public string ListFilesInSpecificFolder(string cloudDirectoryName)
        {
            CloudBlobDirectory dir     = connectContainer("zycontainer").GetDirectoryReference(cloudDirectoryName);
            var           list         = dir.ListBlobs();
            List <string> fileNameList = new List <string>();

            foreach (var item in list)
            {
                if (item.GetType() == typeof(CloudBlockBlob))
                {
                    CloudBlockBlob file = (CloudBlockBlob)item;
                    fileNameList.Add(file.Name);
                }

                /* allthough we don't upload pageBlob in WCF Test Client,
                *  but we could upload pageBlob in Server Explorer->Azure->Storage->Development->Blobs->zycontainer(right cilck this)-->View Blob Container-->Upload Blob
                *  so we take the condition of pageblob into consideration*/
                if (item.GetType() == typeof(CloudPageBlob))
                {
                    CloudPageBlob file = (CloudPageBlob)item;
                    fileNameList.Add(file.Name);
                }
                if (item.GetType() == typeof(CloudBlobDirectory))
                {
                    CloudBlobDirectory dir1             = (CloudBlobDirectory)item;
                    string             foldername1      = dir1.Prefix.ToString();
                    string             clearfoldername1 = foldername1.Remove(foldername1.Length - 1, 1);
                    fileNameList.Add(clearfoldername1);
                }
            }
            return(JsonConvert.SerializeObject(fileNameList));
        }
コード例 #11
0
        protected void GetChildItems(List <FileDir> list, IEnumerable <IListBlobItem> items, GetItemsOptions options, FileDir parentDir)
        {
            foreach (IListBlobItem item in items)
            {
                if (item.GetType() == typeof(CloudBlockBlob))
                {
                    if (options.HasFlag(GetItemsOptions.IncludeFiles))
                    {
                        list.Add(FromBlob((CloudBlockBlob)item));
                    }

                    if (parentDir != null)
                    {
                        parentDir.Length++;
                    }
                }
                else if (options.HasFlag(GetItemsOptions.IncludeDirectories) && item.GetType() == typeof(CloudBlobDirectory))
                {
                    CloudBlobDirectory bdir     = (CloudBlobDirectory)item;
                    string             pname    = bdir.Parent == null?"":bdir.Parent.Prefix;
                    FileDir            childDir = new FileDir()
                    {
                        Name = bdir.Prefix.Substring(pname.Length, bdir.Prefix.Length - pname.Length - 1), IsDirectory = true, Path = pname
                    };
                    list.Add(childDir);
                    if (options.HasFlag(GetItemsOptions.Deep))
                    {
                        GetChildItems(list, bdir.ListBlobs(), options, childDir);
                    }
                }
            }
        }
コード例 #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="connectionString">String de conexão com a conta Azure Blob Storage</param>
        /// <param name="containerName">Nome do Container onde o sub diretório estará armazenado/param>
        /// <param name="directoryName">Nome do sub diretório onde os arquivos estarão aramazenados</param>
        /// <returns></returns>
        public static List <string> ListBobsUriInDirectoty(string connectionString, string containerName, string directoryName)
        {
            IEnumerable <IListBlobItem> listBlobItem = null;
            List <string> blobsUri = new List <string>();

            try
            {
                // Retrieve storage account from connection string.
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

                // Create the blob client.
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

                // Retrieve a reference to a container.
                CloudBlobContainer container = blobClient.GetContainerReference(containerName);

                // Retrieve a reference to a directoty.
                CloudBlobDirectory directory = container.GetDirectoryReference(directoryName);

                // List blobs in the directoty.
                listBlobItem = directory.ListBlobs(true).ToList();

                foreach (var blobItem in listBlobItem)
                {
                    blobsUri.Add(blobItem.Uri.AbsoluteUri);
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(blobsUri);
        }
コード例 #13
0
        /// <summary>
        /// Delete's all blobs within the container, under the specified virtual directory, that are older than the number of days specified.
        /// </summary>
        public void ExpireBlobs(string containerName, string virtualDirectoryRoot, int expirationDays)
        {
            try
            {
                // Retreive the container
                CloudBlobContainer container = _blobClient.GetContainerReference(containerName);

                // If the container exists, then grab it
                if (container.Exists())
                {
                    CloudBlobDirectory directory = container.GetDirectoryReference(virtualDirectoryRoot);

                    // Get all blobs under the specified virtual directory that are older than the
                    // specified number of days.
                    var blobList = directory
                                   .ListBlobs(true)
                                   .OfType <CloudBlockBlob>()
                                   .Where(x => x.Properties.LastModified.HasValue &&
                                          x.Properties.LastModified.Value.AddDays(expirationDays) < DateTime.Today)
                                   .ToList();

                    // Delete 'em all!
                    blobList.ForEach(x => x.DeleteIfExists());
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError(ex.ToString());
                throw;
            }
        }
コード例 #14
0
        /// <summary>
        /// Returns the name/path of all blobs in a container, under the specified virtual directory
        /// </summary>
        public List <BlobInfo> GetBlobsInDirectory(string containerName, string directoryPath)
        {
            List <BlobInfo> blobList = new List <BlobInfo>();

            try
            {
                // Retreive the container
                CloudBlobContainer container = _blobClient.GetContainerReference(containerName);

                // If the container exists, then grab it
                if (container.Exists())
                {
                    CloudBlobDirectory directory = container.GetDirectoryReference(directoryPath);
                    blobList = directory
                               .ListBlobs()
                               .OfType <CloudBlockBlob>()
                               .Select(BlobInfo.FromBlob)
                               .ToList();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError(ex.ToString());
                throw;
            }

            return(blobList);
        }
コード例 #15
0
ファイル: Cluster.cs プロジェクト: shruthi-kr/HadoopSDK
 /// <summary>
 /// Deletes a directory in Azure Blob
 /// </summary>
 /// <param name="directory">The directory.</param>
 private void DeleteDirectory(CloudBlobDirectory directory)
 {
     try
     {
         foreach (var item in directory.ListBlobs())
         {
             var blockBlob = item as CloudBlockBlob;
             if (blockBlob != null)
             {
                 blockBlob.DeleteIfExists();
             }
             else
             {
                 var dir = item as CloudBlobDirectory;
                 if (dir != null)
                 {
                     this.DeleteDirectory(dir);
                 }
             }
         }
     }
     catch (Exception e)
     {
         AvroHdiSample.ReportError("Error while cleaning the cluster\n" + e);
     }
 }
コード例 #16
0
        /// <summary>
        /// Gets the directory listing of all blobs within the parent container specified.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns></returns>
        public CloudDirectoryCollection GetDirectoryListing(string path)
        {
            path = ParsePath(path);
            CloudBlobContainer container = _blobClient.GetContainerReference(ContainerName);
            var directories = new CloudDirectoryCollection();

            if (path == "")
            {
                directories.AddRange(
                    container.ListBlobs().OfType <CloudBlobDirectory>().Select(
                        dir => new CloudDirectory {
                    Path = dir.Uri.ToString()
                }));
            }
            else
            {
                CloudBlobDirectory parent = container.GetDirectoryReference(path);
                directories.AddRange(
                    parent.ListBlobs().OfType <CloudBlobDirectory>().Select(
                        dir => new CloudDirectory {
                    Path = dir.Uri.ToString()
                }));
            }

            return(directories);
        }
コード例 #17
0
ファイル: PageService.cs プロジェクト: BoxedSauce/Gloop
        public GloopPageData GetPageData(string path)
        {
            if (path[0] == '/')
            {
                path = path.ReplaceFirst("/", "");
            }

            CloudBlobContainer container = BlobClient.GetContainerReference("gloopdata");
            CloudBlobDirectory directory = container.GetDirectoryReference(path);

            var blob = directory.ListBlobs()
                       .OfType <CloudBlob>()
                       .LastOrDefault();

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

            GloopPageData pageData;

            using (var memoryStream = new MemoryStream())
            {
                blob.DownloadToStream(memoryStream);
                pageData = memoryStream.Deserialize <GloopPageData>();
            }

            return(pageData);
        }
コード例 #18
0
        public IEnumerable <string> ListDirectories(string baseDirectory = "")
        {
            CloudBlobDirectory dir = inputsContainer.GetDirectoryReference(baseDirectory);

            return(dir.ListBlobs(false, BlobListingDetails.None,
                                 options: new BlobRequestOptions
            {
                RetryPolicy = new Microsoft.WindowsAzure.Storage.RetryPolicies.ExponentialRetry(TimeSpan.FromMilliseconds(50), 5)
            })
                   .Where(d => d is CloudBlobDirectory)
                   .Select(d =>
            {
                string prefix;
                CloudBlobDirectory cd = d as CloudBlobDirectory;
                if (cd.Parent != null && cd.Parent.Prefix != null)
                {
                    prefix = cd.Prefix.Substring(cd.Parent.Prefix.Length, cd.Prefix.Length - cd.Parent.Prefix.Length - 1);
                }
                else
                {
                    prefix = cd.Prefix.Substring(0, cd.Prefix.Length - 1);
                }
                return prefix;
            })
                   .Distinct());
        }
コード例 #19
0
 private static void DirectoryFile(CloudBlobContainer container)
 {
     foreach (var item in container.ListBlobs(null, false))
     {
         dynamic name = item;
         if (item.GetType() == typeof(CloudBlobDirectory))
         {
             CloudBlobDirectory subFolder = (CloudBlobDirectory)item;
             Console.WriteLine("Is a folder with name " + subFolder.Prefix);
             foreach (var sa in subFolder.ListBlobs())
             {
                 if (sa.GetType() == typeof(CloudBlobDirectory))
                 {
                     CloudBlobDirectory subFolder1 = (CloudBlobDirectory)item;
                     Console.WriteLine("Is a folder with name " + subFolder1.Prefix);
                 }
                 else if (item.GetType() == typeof(CloudBlockBlob))
                 {
                     Console.WriteLine("Is a file with name" + name.Name);
                 }
             }
         }
         else
         {
             if (item.GetType() == typeof(CloudBlockBlob))
             {
                 Console.WriteLine("Is a file with name" + name.Name);
             }
         }
     }
 }
コード例 #20
0
        public override List <FileSystem.ItemInfo> EnumerateDirectories(string path)
        {
            List <ItemInfo> result = new List <ItemInfo>();

            CloudBlobDirectory dir = container.GetDirectoryReference(NormalizePath(path));

            foreach (IListBlobItem item in dir.ListBlobs())
            {
                if (item.GetType() == typeof(CloudBlobDirectory))
                {
                    CloudBlobDirectory directory = (CloudBlobDirectory)item;
                    CloudBlockBlob     blob      = directory.GetBlockBlobReference("void");
                    blob.FetchAttributes();

                    String dirName = directory.Uri.Segments[directory.Uri.Segments.Length - 1];
                    if (dirName.EndsWith("/"))
                    {
                        dirName = dirName.Substring(0, dirName.Length - 1);
                    }
                    result.Add(new ItemInfo {
                        Name = dirName, CreationTime = blob.Properties.LastModified.Value.DateTime, LastWriteTime = blob.Properties.LastModified.Value.DateTime, Length = 0
                    });
                }
            }
            return(result);
        }
コード例 #21
0
        private void BuildDirNode(CloudBlobDirectory cloudDir, DirNode dirNode)
        {
            foreach (IListBlobItem item in cloudDir.ListBlobs(false, BlobListingDetails.Metadata, HelperConst.DefaultBlobOptions))
            {
                CloudBlob          cloudBlob   = item as CloudBlob;
                CloudBlobDirectory subCloudDir = item as CloudBlobDirectory;

                if (cloudBlob != null)
                {
                    if (CloudBlobHelper.MapStorageBlobTypeToBlobType(cloudBlob.BlobType) == this.BlobType)
                    {
                        FileNode fileNode = new FileNode(cloudBlob.GetShortName());
                        this.BuildFileNode(cloudBlob, fileNode);
                        dirNode.AddFileNode(fileNode);
                    }
                }
                else if (subCloudDir != null)
                {
                    var     subDirName = subCloudDir.GetShortName();
                    DirNode subDirNode = dirNode.GetDirNode(subDirName);

                    // A blob directory could be listed more than once if it's across table servers.
                    if (subDirNode == null)
                    {
                        subDirNode = new DirNode(subDirName);
                        this.BuildDirNode(subCloudDir, subDirNode);
                        dirNode.AddDirNode(subDirNode);
                    }
                }
            }
        }
コード例 #22
0
        public int Delete(BlobUrl url)
        {
            int itemsDeleted = 0;

            PrepareConnection(url);

            if (url.Kind == BlobUrlKind.Account)
            {
                throw new Exception("Deletion of storage account is not implemented.");
            }
            else if (url.Kind == BlobUrlKind.Container)
            {
                CloudBlobContainer container = this._currentClient.GetContainerReference(url.Url);
                if (container == null)
                {
                    throw new Exception(string.Format("Container '{0}' not found.", url.Url));
                }

                container.Delete();

                itemsDeleted++;
            }
            else if (url.Kind == BlobUrlKind.SubfolderOrBlob)
            {
                CloudBlob blob = this._currentClient.GetBlobReference(url.Url);

                if (blob != null && this.Exists(blob))
                {
                    blob.Delete();
                    itemsDeleted++;
                }
                else
                {
                    CloudBlobContainer container = this._currentClient.GetContainerReference(url.ContainerUrl);
                    if (container == null)
                    {
                        throw new Exception(string.Format("Container '{0}' not found.", url.ContainerUrl));
                    }

                    CloudBlobDirectory dir = container.GetDirectoryReference(url.BlobName);
                    if (dir == null)
                    {
                        throw new Exception("Directory not found. Container Url=" + container.Uri.AbsoluteUri + "; Directory=" + url.BlobName);
                    }

                    var matchedBlobs = dir.ListBlobs(new BlobRequestOptions()
                    {
                        BlobListingDetails = BlobListingDetails.None, UseFlatBlobListing = true
                    });
                    foreach (IListBlobItem listBlobItem in matchedBlobs)
                    {
                        CloudBlockBlob b = container.GetBlockBlobReference(listBlobItem.Uri.AbsoluteUri);
                        b.Delete();
                        itemsDeleted++;
                    }
                }
            }

            return(itemsDeleted);
        }
コード例 #23
0
        /// <summary>
        /// Gets the file tree.
        /// </summary>
        /// <param name="blobName">The blob name.</param>
        /// <returns>The file tree.</returns>
        private List <FileDescription> GetFileTree(string blobName)
        {
            CloudBlobDirectory     directory = _container.GetDirectoryReference(blobName);
            List <FileDescription> fileTree  = new List <FileDescription>();

            foreach (IListBlobItem blob in directory.ListBlobs())
            {
                FileDescription    fileDescription;
                CloudBlobDirectory blobDirectory = blob as CloudBlobDirectory;
                if (blobDirectory != null)
                {
                    fileDescription = new FileDescription(blobDirectory.Prefix, true);
                }
                else
                {
                    ICloudBlob blobFile = (ICloudBlob)blob;
                    fileDescription = new FileDescription(blobFile.Name, false)
                    {
                        Size = blobFile.Properties.Length,
                        LastModificationDate = GetDateTimeOrEmptyDate(blobFile.Properties.LastModified)
                    };
                }
                fileTree.Add(fileDescription);
            }
            return(fileTree);
        }
コード例 #24
0
        /// <summary>
        /// Determines whether the specified directory exists.
        /// </summary>
        /// <param name="path">The directory to check.</param>
        /// <returns>
        /// <c>True</c> if the directory exists and the user has permission to view it; otherwise <c>false</c>.
        /// </returns>
        public bool DirectoryExists(string path)
        {
            string             fixedPath = this.FixPath(path);
            CloudBlobDirectory directory = this.cloudBlobContainer.GetDirectoryReference(fixedPath);

            return(directory.ListBlobs().Any());
        }
コード例 #25
0
        private async Task <string> GetPlayerImageUri()
        {
            if (imageLoadedFromLocalFilesystem)
            {
                //// Upload new image as BlockBlob if not already in any of the container's folders

                // Set the blob's content type so that the browser knows to treat it as an image.
                string imageType     = Path.GetExtension(AvatarImagePictureBox.ImageLocation);
                string imageFileName = Path.GetFileName(AvatarImagePictureBox.ImageLocation);
                //Upload new image as blockBlob
                CloudBlockBlob blockBlob = customDir.GetBlockBlobReference(imageFileName);
                blockBlob.Properties.ContentType = "image/" + imageType;
                await blockBlob.UploadFromFileAsync(AvatarImagePictureBox.ImageLocation);

                return(blockBlob.Uri.AbsoluteUri);
            }
            else
            {
                // Image with same name already in storage?
                bool isInDefaultFolder = defaultBlobs.Contains(new CloudBlockBlob(new Uri(AvatarImagePictureBox.ImageLocation)));

                customDir   = clickycratesBlobContainer.GetDirectoryReference("custom");
                customBlobs = customDir.ListBlobs().ToList();
                bool isInCustomFolder = customBlobs.Contains(new CloudBlockBlob(new Uri(AvatarImagePictureBox.ImageLocation)));
                if (isInCustomFolder || isInDefaultFolder)
                {
                    return(AvatarImagePictureBox.ImageLocation);
                }
                else
                {
                    return(string.Empty);
                }
            }
        }
コード例 #26
0
        /// <summary>
        /// Deletes the specified directory and, if indicated, any subdirectories and files in the directory.
        /// </summary>
        /// <remarks>Azure blob storage has no real concept of directories so deletion is always recursive.</remarks>
        /// <param name="path">The name of the directory to remove.</param>
        /// <param name="recursive">
        /// <c>true</c> to remove directories, subdirectories, and files in path; otherwise, <c>false</c>.
        /// </param>
        public void DeleteDirectory(string path, bool recursive)
        {
            path = this.FixPath(path);

            if (!this.DirectoryExists(path))
            {
                return;
            }

            CloudBlobDirectory directory = this.GetDirectoryReference(path);

            IEnumerable <CloudBlockBlob> blobs = directory.ListBlobs().OfType <CloudBlockBlob>();

            if (recursive)
            {
                foreach (CloudBlockBlob blockBlob in blobs)
                {
                    try
                    {
                        blockBlob.Delete(DeleteSnapshotsOption.IncludeSnapshots);
                    }
                    catch (Exception ex)
                    {
                        this.LogHelper.Error <AzureBlobFileSystem>(string.Format("Unable to delete directory at {0}", path), ex);
                    }
                }

                return;
            }

            // Delete the directory.
            // Force recursive since Azure has no real concept of directories
            this.DeleteDirectory(path, true);
        }
コード例 #27
0
ファイル: AzureFileSystem.cs プロジェクト: xubinvc/MrCMS
        public IEnumerable <string> GetFiles(string filePath)
        {
            EnsureInitialized();
            CloudBlobDirectory cloudBlobDirectory = Container.GetDirectoryReference(filePath);

            return(cloudBlobDirectory.ListBlobs().Select(item => item.Uri.ToString()));
        }
 public override object Rename(string path, string oldName, string newName, IEnumerable <CommonFileDetails> commonFiles, IEnumerable <object> selectedItems = null)
 {
     //bool isFile = false;
     //foreach (string item in newName)
     //{
     //    if(item != '')
     //    isFile = true;
     //    break;
     //}
     if (newName != "")
     {
         CloudBlob existBlob = container.GetBlobReference(path + oldName);
         CloudBlob newBlob   = container.GetBlobReference(path + newName);
         newBlob.StartCopy(existBlob.Uri);
         existBlob.DeleteIfExists();
     }
     else
     {
         CloudBlobDirectory sampleDirectory = container.GetDirectoryReference(path + oldName);
         var items = sampleDirectory.ListBlobs(true, BlobListingDetails.Metadata);
         foreach (var item in items)
         {
             string    name    = item.Uri.AbsolutePath.Replace(sampleDirectory.Uri.AbsolutePath, "");
             CloudBlob newBlob = container.GetBlobReference(path + newName + "/" + name);
             newBlob.StartCopy(item.Uri);
             container.GetBlobReference(path + oldName + "/" + name).Delete();
         }
     }
     return("success");
 }
 public override object Paste(string sourceDir, string targetDir, string[] names, string option, IEnumerable <CommonFileDetails> commonFiles, IEnumerable <object> selectedItems = null, IEnumerable <object> targetFolder = null)
 {
     foreach (string s_item in names)
     {
         if (s_item != "")
         {
             string    sourceDir1 = sourceDir + s_item;
             CloudBlob existBlob  = container.GetBlobReference(sourceDir1);
             CloudBlob newBlob    = container.GetBlobReference(targetDir + s_item);
             newBlob.StartCopy(existBlob.Uri);
             if (option == "move")
             {
                 existBlob.DeleteIfExists();
             }
         }
         else
         {
             CloudBlobDirectory sampleDirectory = container.GetDirectoryReference(sourceDir + s_item);
             var items = sampleDirectory.ListBlobs(true, BlobListingDetails.None);
             foreach (var item in items)
             {
                 string    name    = item.Uri.ToString().Replace(sampleDirectory.Uri.ToString(), "");
                 CloudBlob newBlob = container.GetBlobReference(targetDir + s_item + "/" + name);
                 newBlob.StartCopy(item.Uri);
                 if (option == "move")
                 {
                     container.GetBlobReference(sourceDir + s_item + "/" + name).Delete();
                 }
             }
         }
     }
     return("success");
 }
コード例 #30
0
        /// <summary>
        /// Determines whether the specified path is a valid blob folder.
        /// </summary>
        /// <param name="dirPath">a directory path, final char is '/'</param>
        /// <returns></returns>
        public bool IsValidDirectory(string dirPath)
        {
            if (dirPath == null)
            {
                return(false);
            }

            // Important, when dirPath = "/", the behind HasDirectory(dirPath) will throw exceptions
            if (dirPath == "/")
            {
                return(true);
            }

            // error check
            if (!dirPath.EndsWith(@"/"))
            {
                Trace.WriteLine($"Invalid parameter {dirPath} for function IsValidDirectory", "Error");
                return(false);
            }

            // remove the first '/' char
            string blobDirPath = dirPath.ToAzurePath();

            // get reference
            CloudBlobDirectory blobDirectory = _container.GetDirectoryReference(blobDirPath);

            // non-exist blobDirectory won't contain blobs
            if (!blobDirectory.ListBlobs().Any())
            {
                return(false);
            }

            return(true);
        }
コード例 #31
0
ファイル: VHDLocation.cs プロジェクト: virmitio/VHDProvider
 public static IEnumerable<CloudBlobDirectory> ListSubdirectories(CloudBlobDirectory cloudBlobDirectory)
 {
     throw new NotImplementedException();
     var l = cloudBlobDirectory.Uri.AbsolutePath.Length;
     return (from blob in cloudBlobDirectory.ListBlobs().Select(each => each.Uri.AbsolutePath.Substring(l + 1))
         let i = blob.IndexOf('/')
         where i > -1
         select blob.Substring(0, i)).Distinct().Select(cloudBlobDirectory.GetSubdirectoryReference);
 }