System.IO.File.Delete with Wildcards

May 19, 2006 at 7:36 pm 12 comments

I came across this earlier in the week, working on QualTrax code.  In our application, we have a class for all our file handling operations.  The class is pretty much a wrapper for standard System.IO.File calls  (Copy, Delete, FileExists, etc).  The wrapper class has been working quite well until this week, when I came across a need to delete a whole group of files.  Without a second thought, I passed in wildcards in with my filename.  For example:

C:\MyFolder\Prefix*.PDF

Lo and Behold, when I unsuspectingly ran the System.IO.File.Delete method, I got an error:

{"Illegal characters in path."}

It is fairly easy to workaround.  The System.IO.Directory.GetFiles command does support wildcards in its searchPattern parameter.  GetFiles returns an array of strings with the full paths to all the matching files.  Instead of doing a straight File.Delete call, we want to get all the matching files, iterate through those and delete them. 

There are a lot of examples floating around.  However, all the sample code I found was in VB.NET, so I thought I'd go ahead and share C# code in case it is of value to anyone.

Note: You'll want to access the differences between System.IO.File/System.IO.FileInfo and System.IO.Directory/System.IO.DirectoryInfo and determine which one is best for your needs.

  1. I kept the parameters to our wrapper function the same.  We are still passing in a full path that includes our file name such as C:\MyFolder\Prefix*.PDF
  2. In my wrapper function, I check our parameter (fullPath) for the presence of an astericks.  If I find one, then I'm not going to do a straight File.Delete call. 
  3. Before I use the System.IO.Directory.GetFiles command I want to seperate out the directory path from the actual file name.  So some quick substring action takes place.
  4. Finally I call the System.IO.Directory.GetFiles command– passing in my filename (with the wildcards) as the second parameter. 
  5. If my array has no items– then there were no matching files.  Hooray for that– we achieved the desired result without any work at all.  Otherwise, we cycle through the array and now we call our friend File.Delete.
  6. I surrounded the File.Delete calls with a try/catch clause so we can be meticulous with logging the details of the transaction (that code not pictured).

 

About these ads

Entry filed under: .NET, C#, System.IO.File, Web Development. Tags: .

Milwaukee Pictures Single Sided Stories

12 Comments Add your own

  • 1. John Douglas  |  June 20, 2006 at 7:45 am

    Nice bit of code which helped me out of a small problemette.

    Would have been nice to have a cut&paste-able code sample rather than a bitmap – but it worked okay.

    Your screenshot is missing a section of code on the far right hand side as well.

    Many thanks,
    John.

    Reply
  • 2. tgaw  |  June 20, 2006 at 8:40 am

    Thanks John. I’ve been trying to settle on a better means to communicate the code. Optimally, I’d like to use DIV tag with scrollbars, but it looks like the WordPress engine doesn’t quite approve of that notion! :)

    Thanks for posting!

    Reply
  • 3. gola khan  |  March 10, 2007 at 2:19 am

    it’s a nice code.it will hepl me to solve a important code.thank you.

    Reply
  • 4. gola khan  |  March 10, 2007 at 2:20 am

    it’s a nice code.it will help me to solve a important code.thank you

    Reply
  • 5. Chris Mullins  |  April 11, 2007 at 1:46 pm

    If you are looking for a good way to post your code there is an add in tool for Visual Studio 2005 that does a good job of converting source code to html while retaining all of the formatting and syntax highlighting. Once you install it you have a second copy function in the edit menu called Copy As HTML.

    http://www.jtleigh.com/people/colin/software/CopySourceAsHtml/

    Reply
  • 6. tgaw  |  April 11, 2007 at 6:01 pm

    Thanks Chris! That tool may come in handy!!!

    Reply
  • 7. Recursieve  |  August 30, 2009 at 5:53 am

    foreach (string file in Directory.GetFiles(@”C:\test\”, “Log*.txt”)) {
    File.Delete(file);
    }

    Reply
    • 8. Terry H  |  September 4, 2009 at 6:14 am

      I like this even better. Just what I was looking for GREAT.

      Reply
  • 9. PL Sharma  |  September 24, 2009 at 4:09 am

    I am sending you proposal for affiliate marketing through your website to other advertisers. This is a performance based networking and we pay affiliate commissions on per lead or per sale basis. We are currently working for big brands in India for Retail, travel and Education sector. Few Major Brands are as below :

    1. Jet airways
    2. Indiatimes Shopping
    3. Yatra.com
    4. GoIbibo Travel
    5. Lear Next
    6. Toppers
    7. Ferns N petals
    And many more. You can find more details on our website : http://network.shoogloo.com

    We wants to promote education advertisers through your website. We are offering good affiliate commissions on per sale and lead basis. Below are the details :
    Merchant Category CPA CPL Status
    Learnnext.com CBSE Courses 15% 30 Live
    Toppers.com MBA course To be live
    TopCatCoaching.com MBA course To be live
    Career Launcher MBA course To be live
    http://www.meritnation.com
    CBSE Courses To be live

    Reply
  • 10. Patrick  |  September 25, 2010 at 2:15 pm

    Shorter version.

    string DownloadPath = Server.MapPath(“~/MyPath”);
    foreach (string file in Directory.GetFiles(@DownloadPath, “*.csv”))
    {
    File.Delete(file);
    }

    Reply
  • 11. BenWah  |  September 1, 2011 at 4:52 pm

    Simpler way to handle wildcards: Don’t check for them. Here’s some code I was writing for deleting codes using params to allow multiple filemasks. It does make the assumption that if you don’t specify a directory, you are deleting from your current directory, so be careful:

    private static void DeleteFiles(params string[] strFilesToDeleteAr)
    {
    List strFilesToDeleteList = new List();

    foreach (string strFileMask in strFilesToDeleteAr)
    {
    string strDirectory = Path.GetDirectoryName(strFileMask);

    if (String.IsNullOrEmpty(strDirectory))
    {
    strDirectory = Directory.GetCurrentDirectory();
    }

    string strMask = strFileMask.Replace(strDirectory, String.Empty);
    strMask = strMask.Replace(“\\”, String.Empty);

    strFilesToDeleteList.AddRange(Directory.GetFiles(strDirectory, strMask));
    }

    foreach (string strFile in strFilesToDeleteList)
    {
    File.Delete(strFile);
    }
    }

    It works because if the filemask you are supplying doesn’t have wildcards, it just makes Directory.GetFiles job easier by giving it a completely specified name. Either way, no need to check for wildcards.

    Reply
  • 12. shanthichennamshetty  |  November 24, 2011 at 5:28 am

    Notemonk provides NCERT solutions, CBSE online study material, ICSE online study material, CBSE revision notes, CBSE model test papers, CBSE guess papers, interactive puzzles. Get top marks in exams with Notemonk’s CBSE, ICSE and NCERT online study materials,online tuition and online video tutorials.

    http://www.notemonk.com

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Flickr Photos

Failed Family Run at Mason Neck State Park - Sunset at 1921 (Portrait)

Failed Family Run at Mason Neck State Park - Sunset at 1920

Failed Family Run at Mason Neck State Park - Sunset at 1846

View While Nursing for September 21, 2014 - Changing Virginia Creeper.  Burke, Virginia  http://viewswhilenursing.tumblr.com

Deck Staining - Sagan and Dyson Want to Help Daddy with Privacy Screen

More Photos

3D Printed Products

Tweets


Follow

Get every new post delivered to your Inbox.

Join 69 other followers

%d bloggers like this: