0

I got the problem in my pet-project. Totally I wanna counting the files in some directory filtering them by some options (length). It works good for me when "reading" of files or directories occured where I have access.In other way it crashed my loop. For example of AggregateException handling I used msdn https://msdn.microsoft.com/en-us/library/dd460695(v=vs.110).aspx (this example works good)

I got exception with the first call of unreachable file. Could you recommend best way to implement my requirement? Below you can see my code.

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace app
{
    class Program
    {
        public static int CountOfGetAccessFiles { get; set; }
        public static int NotCountOfGetAccessFiles { get; set; }
        public static void ToDo()
        {
            //get files 
            DirectoryInfo dir = new DirectoryInfo(@"E:\");

            var str = dir.EnumerateFiles("*.*", SearchOption.AllDirectories);
            var quantFiles = str.Select(x => x);

            //need to save exceptions
            var exceptions = new ConcurrentQueue<Exception>();
            try
            {
                Parallel.ForEach(quantFiles, item =>
                {
                    CountOfGetAccessFiles++;
                    Console.WriteLine(CountOfGetAccessFiles);
                });
            }
            catch (Exception e)
            {
                NotCountOfGetAccessFiles++;
                exceptions.Enqueue(e);
            }

            if (exceptions.Count > 0) throw new AggregateException(exceptions);

        }

        static void Main(string[] args)
        {

            try
            {
                ToDo();
            }
            catch (AggregateException ae)
            {
                //This is where you can choose which exceptions to handle.
                foreach (var ex in ae.InnerExceptions)
                {
                    if (ex is ArgumentException)
                        Console.WriteLine(ex.Message);
                    //else
                    //    throw ex;
                }
            }

            Console.WriteLine("Count {0}, aggregate {1}", CountOfGetAccessFiles, NotCountOfGetAccessFiles);
            Console.ReadLine();
        }
    }
}

Sorry if repeated this topic

  • Mmm, just one question, Why is your `try-catch` outside of the `Parallel.ForEach` statement? You have to capture the exceptions inside of the `Parallel.ForEach` method. – mijail May 20 '16 at 23:33
  • @mijail, I have tried like you says, but got the same result. The main problem that I got exception when it's called in variable, for example `Parallel.ForEach(quantFiles, item =>` so the loop didn't started –  May 20 '16 at 23:48

0 Answers0