C# Com Object cast to interface for file

168 views Asked by At

I'm encountering a problem I don't seem to quite understand.

I have this code I found Here which I tried to modify to my needs:

Folder objFolder;
LoadHeader(path, out arrHeaders, out objFolder);
foreach (Shell32.FolderItem2 item in objFolder.Items())
{ 
            List<DateTime> tmp = new List<DateTime>();
            DateTime SelectedDate;
            foreach (int h in date)
            {
                string l = objFolder.GetDetailsOf(item, h);
                if (!string.IsNullOrEmpty(l))
                {
                    string asAscii = Encoding.ASCII.GetString(
                        Encoding.Convert(
                            Encoding.UTF8,
                            Encoding.GetEncoding(
                                Encoding.ASCII.EncodingName,
                                new EncoderReplacementFallback(string.Empty),
                                new DecoderExceptionFallback()),
                            Encoding.UTF8.GetBytes(l)
                            ));
                    tmp.Add(DateTime.Parse(asAscii.Substring(0, 11)));
                }
            }
            if (tmp.Count == 0)
                SelectedDate = File.GetCreationTime(item.Path);
            else
                SelectedDate = tmp.Min();
            FileToSort.Add(new FileToSort(item.Name, item.Path, SelectedDate));
        }
}

The problem appeared when I tried to speed up the foreach using the Parallel.ForEach() since it get strangely slow when confronted with a large number of file

 Folder objFolder;
 LoadHeader(path, out arrHeaders, out objFolder);
 Parallel.ForEach(/*(IEnumerable<FolderItem2>)*/objFolder.Items(),
 (Shell32.FolderItem2 item) =>
 {
  /*Some work*/
 });

This code even with the suggested Visual Studio cast throws an exception of type System.InvalidCastException

Cannot cast object of type System.__ComObject to interface type System.Collections.Generic.IEnumerable`1[Shell32.FolderItem2]

So what I'm wondering is what the 2 foreach differentiate from each other, and if I can replicate the classic foreach behavior to use the parallel one, or is it something that can't be done?

0

There are 0 answers