Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

DirectoryInfo and filtering multiple extensions using FileInfo

Posted on 2009-05-04
13
Medium Priority
?
1,103 Views
Last Modified: 2012-05-06
I have an app that populates a list box with files from a user specified directory.  I have an option to include or exclude hidden files which I filter after using the FileInfo array that is returned by the DirectoryInfo GetFiles method.  

I have read and I realize that the GetFiles method does not allow for filtering by extension, it is simply a search parameter.  Of course this is after I wrote the user updatable feature to add and remove extensions.

Does anyone have a way to take a delimited string get back a FileInfo array sorted alphabetically.

Thanks!!
0
Comment
Question by:tech1984
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
13 Comments
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 24300485
you may try filtering on the stage of retrieving fileinfos:

http://www.dreamincode.net/code/snippet2823.htm
0
 

Author Comment

by:tech1984
ID: 24300529
I saw this code while searching and it looked good.  I am still fairly new to .Net and pretty much only get to program for fun, so please bear with me.  I see that an ArrayList of the files is created and then converted and returned as a string array.  Can I somehow get this into a FileInfo array?  And how about keeping it sorted?

Thanks for the help and quick response!
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 24300596
OK, let me some time to test the code on my computer
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 30

Accepted Solution

by:
anarki_jimbel earned 2000 total points
ID: 24300684
Try the code. It should work. Not exactly sure about sorting - let me know how it goes
            string dir = @"C:\Documents and Settings\dmitry.gakhovich\My Documents";
            //determine our valid file extensions
            string validExtensions = "*.jpg,*.jpeg,*.gif,*.png";
 
            //create a string array of our filters by plitting the
            //string of valid filters on the delimiter
            string[] extFilter = validExtensions.Split(new char[] { ',' });
         
            //ArrayList to hold the files with the certain extensions
            List<FileInfo> files = new List<FileInfo>();
 
            //DirectoryInfo instance to be used to get the files
            DirectoryInfo dirInfo = new DirectoryInfo(dir);
 
             //loop through each extension in the filter
            foreach (string extension in extFilter)
            {
                //add all the files that match our valid extensions
                //by using AddRange of the ArrayList
                files.AddRange(dirInfo.GetFiles(extension));
            }
 
            files.Sort();
            
            foreach(FileInfo fi in files){
                // send to output window, open from View menu or Ctrl-Alt-O
                System.Diagnostics.Debug.WriteLine(fi.Name);
            }

Open in new window

0
 

Author Comment

by:tech1984
ID: 24300763
Ok, I have to comment out Sort or it error out at that point each time.   Also, I know is sounds stupid, but I can't seem to figure out how to change the scope of the FileInfo variable.

Really need the sorting working if you have any ideas.  I get the following error:
"Failed to compare two elements in the array"

Thanks again!
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 24300900
Not sure I understand the question about changing the scope. Could you pls explain.

I have a problem on my computer now - it does not allow me to search directories - not enough privileges.
Need to fix but can't right now.

Sort is not a proble. There are some overloads for sort. What you need to do is to create a comparer object. Let me think and I'll give you a solution (but can't test myself).
0
 
LVL 30

Assisted Solution

by:anarki_jimbel
anarki_jimbel earned 2000 total points
ID: 24300913
OK, let's try the following:

replace sort line with:

            MyFileInfoComparer comparer = new MyFileInfoComparer();
            files.Sort(comparer);

And you need to add a comparer class to your solution. See in the snippet. It sorts by a filename.
You may change the behaviour. To read more - see the link:
http://www.devx.com/dotnet/Article/21089/0/page/3
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
 
namespace TestProj
{
    public class MyFileInfoComparer : IComparer<FileInfo>
    {
        /// <summary>
        /// Be aware - it may throw an exception if fi1 or fi2 are null
        /// </summary>
        /// <param name="fi1"></param>
        /// <param name="fi2"></param>
        /// <returns></returns>
        public int Compare(FileInfo fi1, FileInfo fi2)
        {
            return fi1.Name.CompareTo(fi2.Name);
        }
 
    }
}

Open in new window

0
 

Author Comment

by:tech1984
ID: 24301106
I will try the compare in just a bit..

What I mean by scope is that after the for loop, the "fi" variable can't be accessed.  I have more code that needs to call it.  I tried to declare it before the for loop and just but

FileInfo fi;
for (fi in files)

but this didn't work.
0
 

Author Comment

by:tech1984
ID: 24301181
The compare worked great!!!!

Now I just need to fix the scope on the FileInfo variable.  Any thoughts?
0
 

Author Comment

by:tech1984
ID: 24301258
Instead of the foreach I think I need to do something like a " do while" but I can't figure out the syntax to get the files array into the FileInfo.
0
 

Author Comment

by:tech1984
ID: 24301311
I figured it out.

Thanks for all the help!!!!
     FileInfo [] fi =new FileInfo[files.Count];
     int iFiles = 0;
     do
     {
           fi[iFiles] = files[iFiles];
                
           iFiles++;
     } while (iFiles < files.Count);

Open in new window

0
 

Author Closing Comment

by:tech1984
ID: 31577822
Thanks for quick responses and great help!!!
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 24301493
Sorry  - missed your last few comments.

Good luck!
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question