Directory.GetFiles()

G

Guest

Hi

I am using

Directory.GetFiles(DirName, "*.tif");

to get all tif files in the directory. But it'll also give the other files
i.e. *.tif1,*.tif_old,*.tif2.

Please suggest a way to get *.tif files only.

Regards
Sameer Gupta
C# Designer & Developer
Siemens
UK
 
C

Carl Daniel [VC++ MVP]

Sameer said:
Hi

I am using

Directory.GetFiles(DirName, "*.tif");

to get all tif files in the directory. But it'll also give the other
files i.e. *.tif1,*.tif_old,*.tif2.

Please suggest a way to get *.tif files only.

You'll have to filter them yourself - the behavior you describe is exactly
what you'd see if you did 'dir *.tif' at a command prompt. (It comes from
the fact that the OS is matching the wildcard against both the long and the
short filename, and the short filename for all of those files will end in
..tif).

You could also use my FileSystemEnumerator class, which uses a regex to
match wildcards instead of the OS pattern matching. See

http://www.codeproject.com/cs/files/FileSystemEnumerator.asp

-cd
 
G

Gabriele G. Ponti

That's the intended behavior (see the Note in the Remarks section for the
method http://msdn2.microsoft.com/en-us/library/wz42302f.aspx), albeit
questionable.

Since you're probably going to process the list of files somehow anyway you
can add some logic there, or write a helper method.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
class Program
{
static void Main( string[] args )
{
string[] files = GetFilesWithExactExtension( ".", "*.tif" );

foreach( string file in files )
{
Console.WriteLine( file );
}

Console.Write( "Press any key to continue . . . " );
Console.ReadKey();

}
static string[] GetFilesWithExactExtension( string path, string
searchPattern )
{
string[] candidates = Directory.GetFiles( path, searchPattern );
List<string> files = new List<string>();

foreach( string candidate in candidates )
{
if( Path.GetExtension( candidate ) ==
searchPattern.Substring( searchPattern.IndexOf( "." ) ) )
{
files.Add( candidate );
}
}
return files.ToArray();
}

}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top