4

I want to get all the files uploaded in the storage account file share programatically using c#.

I tried to use this code

IEnumerable fileList = cloudFileShare.GetRootDirectoryReference().ListFilesAndDirectories();

But it is throwing an error cloudfiledirectory' does not contain a definition for 'listfilesanddirectories'.

I am trying to loop through file share and get all the files

Bad_Coder
  • 163
  • 1
  • 3
  • 9

2 Answers2

7

This code will get all files in all folders in Azure Fileshare.

using Azure.Storage.Files.Shares;
using System;
using System.IO;
using System.Threading.Tasks;

namespace GetAllStorageAccountFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var x = GetShareFilesAsync();
            x.Wait();
            Console.WriteLine("Done!");
            Console.ReadKey();
        }

        static async Task GetShareFilesAsync(string dirName = "")
        {
            string connectionString = "";

            // Name of the share, directory
            string shareName = "media";

            // Get a reference to a share
            ShareClient share = new ShareClient(connectionString, shareName);

            ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
            var files = directory.GetFilesAndDirectories();

            foreach (var file in files)
            {
                if (file.IsDirectory)
                {
                    Console.WriteLine("Folder: " + Path.Combine(dirName, file.Name));
                    GetShareFilesAsync(Path.Combine(dirName, file.Name));
                    
                }

                Console.WriteLine("File:" + Path.Combine(dirName, file.Name));
            }


        }

    }
}

As per request adding for Blob too.

static async Task GetBlobFiles()
{


    string blobstorageconnection = "DefaultEndpointsProtocol=https;AccountName=stomyuploadpublic;AccountKey=oSM1+BTK8cKbax6dxslT5Gm1aO9AjoH3oRTl43RkK6ZdcrLWB0FVAwoba1CopPycS0Ng3voVu6UR59UMK7ytsg==;EndpointSuffix=core.windows.net";
    string blobContainer = "public";

    CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);

    // Create the blob client.
    CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference(blobContainer);
    CloudBlobDirectory dirb = container.GetDirectoryReference(blobContainer);


    BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(string.Empty, true, BlobListingDetails.Metadata, 500, null, null, null);

    foreach (var blobItem in resultSegment.Results)
    {
        var blob = (CloudBlob)blobItem;
        Console.WriteLine(blob.Name);

    }

}
Daniel Björk
  • 2,475
  • 1
  • 19
  • 26
  • @Gaurav Mantri-AIS or Daniel Bjork : How can we check whether file with some name exists in the container or not – Bad_Coder Jul 23 '20 at 06:22
  • the above code for blob is getting wrong file name.. I have a file within a folder in a container.. filename is coming as foldername/filename... – Bad_Coder Jul 23 '20 at 07:30
  • @Madhu thats just the output, i have combined the foldername and filename, change that and you will be fine: Console.WriteLine("File:" + Path.Combine(dirName, file.Name)); – Daniel Björk Jul 23 '20 at 07:33
  • am adding all the file names to a list... but getting the files names as wrong... need to get the file name as abc.txt but am getting as foldername/abc.txt.. am asking for blob code... not for file share – Bad_Coder Jul 23 '20 at 07:36
  • @Madhu I just told you how to change that. If you only want the Filename and not folder then you should just add file.Name to your list instead of Path.Combine(dirName, file.Name) – Daniel Björk Jul 23 '20 at 07:50
  • @Daiel Bjork - you are taking about file share code... but am having issue with blob code.. var blob = (CloudBlob)blobItem; Console.WriteLine(blob.Name); am getting issue here... In blob.Name it is coming as flodername/filename – Bad_Coder Jul 23 '20 at 08:41
  • @Madhu ah yes, thats because there is no real concept of folders in Blobstorage. The so called "folder" is just a part of the name. You can try the Path.GetFileName(blob.Name); to see if that works on those strings. – Daniel Björk Jul 23 '20 at 08:44
  • @Daiel Bjork - is there a chance to delete the file within the folder in a container if the file exists with the given name... for blob files code – Bad_Coder Jul 23 '20 at 12:38
  • @Madhu https://stackoverflow.com/questions/36497399/how-to-delete-files-from-blob-container – Daniel Björk Jul 23 '20 at 12:40
  • I have changed my storage account to access from selected networks and added my VM ip address.. but still when i run my c# code am getting an error saying "This request is not authorized to perform this operation." – Bad_Coder Jul 24 '20 at 06:42
0
private async Task<List<string>> GetFiles(ShareDirectoryClient directoryClient)
    {
        List<string> filePaths = new List<string>();
        var remaining = new Queue<ShareDirectoryClient>();
        remaining.Enqueue(directoryClient);
        while (remaining.Count > 0)
        {
            // Get all of the next directory's files and subdirectories
            ShareDirectoryClient dir = remaining.Dequeue();
            await foreach (ShareFileItem item in dir.GetFilesAndDirectoriesAsync())
            {
                // Print the name of the item
                
                // Keep walking down directories
                if (item.IsDirectory)
                {
                    remaining.Enqueue(dir.GetSubdirectoryClient(item.Name));
                }
                else
                {
                    filePaths.Add(dir.Path + "/" + item.Name);
                }
            }
        }
        return filePaths;
    }