0

I am writing a WPF application for disk analisis. I wrote this function to calculate the size of the folders

static long GetDirectorySize(DirectoryInfo root, bool recursive = true)
    {
        FileInfo[] files = null;
        DirectoryInfo[] subDirs = null;
        var startDirectorySize = default(long);

        // First, process all the files directly under this folder
        try
        {
            files = root.GetFiles("*.*");
        }
        // This is thrown if even one of the files requires permissions greater
        // than the application provides.
        catch (UnauthorizedAccessException)
        {
        }

        catch (DirectoryNotFoundException)
        {
        }

        if (files != null)
        {
            //Add size of files in the Current Directory to main size.
            foreach (var fileInfo in files)
                Interlocked.Add(ref startDirectorySize, fileInfo.Length);
        }
        // Now find all the subdirectories under this directory.

        if (recursive)
        {  //Loop on Sub Direcotries in the Current Directory and Calculate it's files size.
            try
            {
                subDirs = root.GetDirectories();
                Parallel.ForEach(subDirs, (subDirectory) =>
                Interlocked.Add(ref startDirectorySize, GetDirectorySize(subDirectory, recursive)));
            }
            catch (UnauthorizedAccessException)
            {                   
            }
            catch (DirectoryNotFoundException)
            {
            }
        }
        return startDirectorySize;
    }

How can I output a current size on kind of label? I understand, that I have to use a dispatcher, but I don't know how to call it every time any thread is changing the current calculated size. Also, I am starting this

private void btnStart_Click(object sender, RoutedEventArgs e)
    {
        Task.Factory.StartNew(() => this.GetDirectorySize(new DirectoryInfo(@"C:\"), true));
    }

Am i right? How should I change my code?

Palamar66
  • 212
  • 1
  • 9

0 Answers0