Sunday, August 21, 2005

Using IO.Directory.GetFiles with a filename wildcard

I got an "Illegal characters in path" error on the following statement:
Dim TxtNames As String() = IO.Directory.GetFiles("c:\temp\*.txt")
and from the documentation it was not clear to me why I was getting the error.

Turns out that you must use the second overload version of the GetFiles method with two strings if you want to include a wildcard.

In the example above, the two possible correct versions of the GetFiles method include:

Dim TxtNames As String() = IO.Directory.GetFiles("c:\temp")
Dim TxtNames As String() = IO.Directory.GetFiles("c:\temp","*.txt")

The second statement provides the desired result of returning a string array of all filenames with a txt extension in the c:\temp folder. The first statement returns all files in the c:\temp folder which can be scanned with a loop for further processing.

Note that the single string overload verison of GetFiles can only accept a directory name.

I hope this helps clarify a point that managed to confuse me. As usual, it's obvious once you know the answer!

Joe Kunk


Anonymous said...

That is what my problem is...
Thanks for the clear concise explanation.


Jim Neff said...

Thank you for your blog entry. Had an identical problem. Googled the keywords and your blog entry was the first hit.

Anonymous said...

Thanks! Ran afoul of this today...

Anonymous said...

Thanks for the clarification.