Search code examples
c#azure-storage

How can I get this code to just get the files from an Azure file share?


My code below needs to get a List from my Azure file share.

I can see from the properties of the share that I have 17 files in 5 folders, however this code returns 29.

Sample code shown here, not sure how much extra text this editor wants me to add in before it will let me post.

 class Program
    {
        private static List<CloudFile> files = new List<CloudFile>();

    static void Main(string[] args)
    {
        int xxx = 0;
        string accountName = "#######";
        string key = "#######";
        var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
        var share = storageAccount.CreateCloudFileClient().GetShareReference("xfer");
        IEnumerable<IListFileItem> fileList = share.GetRootDirectoryReference().ListFilesAndDirectories();



        foreach (IListFileItem listItem in fileList)
        {
            if (listItem.GetType() == typeof(CloudFile))
            {
                files.Add((CloudFile)listItem);
            }
            else if (listItem.GetType() == typeof(CloudFileDirectory))
            {
               files.AddRange(list_subdir(listItem));
            }
        }

    }

    public static List<CloudFile>  list_subdir(IListFileItem list)
    {
        CloudFileDirectory fileDirectory = (CloudFileDirectory)list;
        IEnumerable<IListFileItem> fileList = fileDirectory.ListFilesAndDirectories();

        foreach (IListFileItem listItem in fileList)
        {
            if (listItem.GetType() == typeof(CloudFileDirectory))
            {
                list_subdir(listItem);
            }
            else
            {
                if (listItem.GetType() == typeof(CloudFile))
                {
                    files.Add((CloudFile) listItem);
                }
            }
        }
        return files;
    }


}

enter image description here


Solution

  • Your problem lies with files.AddRange. Here's what's happening: Say your root directory has two files, A and B, and a folder Foo. Foo in turn contains files C, D and E.

    Your code finds Foo and calls list_subdir. At this point files is still empty. Your loop inside list_subdir finds C, D and E and adds it to files. At this point files contains C, D and E. Now list_subdir returns files to your loop inside Main, where the AddRange adds the return value to files.

    Now files contains C, D, E, C, D and E.

    The loop continues and adds A and B, making the content of files C, D, E, C, D, E, A, B

    Et voila. 8 files instead of the expected 5.

    If you lose files.AddRange you should be good.

    By the way, Visual Studio allows you to attach your local debugger to an app on Azure, which makes debugging server-side code like this a doddle.