how can i get the file list of a directory based on some logic

M

Mullin Yu

e.g. c:\test

doc1.txt
doc1.pdf
doc2.txt
doc2.pdf
doc3.txt
doc4.pdf
doc5.txt
doc5.pdf

only doc1, doc and doc5 will be returned as has both .txt and .pdf files

how to implement? i'm not sure whether the DirectoryInfo's GetFileInfo's
seach pattern can do so or not?
 
D

Dan Bass

Use Directory.GetFiles(...);

I'd do this to start with:

ArrayList GetUnionFileList ( string path, string extension1, string
extension2 )
{
ArrayList unionList = new ArrayList();
try
{
string[] filesWithExt1 = Directory.GetFiles ( path,
extension1 );
string[] filesWithExt2 = Directory.GetFiles ( path,
extension2 );

foreach ( string file1 in filesWithExt1 )
{
foreach ( string file2 in filesWithExt2 )
{
if ( Path.GetFileNameWithExtension (
file1 ).ToLower() == Path.GetFileNameWithExtension ( file2 ).ToLower() )
{
unionList.Add ( Path.GetFileNameWithExtension
( file1 ) );
break;
}
}
}
}
catch ( Exception ex )
{
// handle the exception here
}
finally
{
return unionList;
}
}


This will be a slow algorithm for lots of files, so I'd look for ways to
improve it. (EG, removing each found item from the array so they're not
searched again).

Hope that helps.

Dan.
 
?

=?ISO-8859-2?Q?Marcin_Grz=EAbski?=

Hi,

I've got proposition for you:

1) Create two hashtables:
Hashtable txtHTab=new Hashtable();
Hashtable pdfHTab=new Hashtable();

2) Fill these hashtables with file names without extension
e.g. for TXT
string dirPath="c:\\test";
string[] fileNames=Directory.GetFiles(dirPath, "*.txt");
for(int i=0; i<fileNames.Length; i++) {
txtHTab.Add(Path.GetFileNameWithoutExtension(fileNames)
, fileNames);
}

.... do the same thing with PDFs

3) Iterate through txtHTab.Keys to search this key by:
pdfHTab.Contains(fileNameWithoutExt)
-if this key is in PDFs then you're sure that exists
TXT and PDF file with the same name prefix.

HTH
Marcin
 
M

Morten Wennevik

Hi Mullin yu,

A third solution:

ArrayList doubleFiles = new ArrayList();

string[] files = Directory.GetFiles(Application.StartupPath, "*.txt");

foreach(string s in files)
{
string t = Path.GetFileNameWithoutExtension(s);
if(File.Exists(t + ".pdf"))
doubleFiles.Add(t);
}

Substitute the extensions and path as needed, preferrably in a method like
Dan's
 
D

Dan Bass

This is the winner, in my opinion anyway. Faster than 1 and easier to
understand than implementing hash tables.

;o)
 

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