DoloWizard
DoloWizard

Reputation: 25

Why Do I Get 'Illegal characters in path' in My Visual Basic Code?

I have a directory with multiple sub directories that contain .doc files. Example:

C:\Users\tmedina\Documents\testenviroment\Released\500\test0.doc
C:\Users\tmedina\Documents\testenviroment\Released\501\test1.doc
C:\Users\tmedina\Documents\testenviroment\Released\502\test2.doc
...
C:\Users\tmedina\Documents\testenviroment\Released\520\test20.doc

In my code below, I am trying to display in a list box all of the files that end with extension '.doc' that are in sub directories of C:\Users\tmedina\Documents\testenviroment\Released

So for example, I have

Dim root As String = "C:\Users\tmedina\Documents\testenviroment"

For Each fileFound As String In Directory.GetFiles(Path.Combine(root, "Released\*\*.doc"))
        ListBox1.Items.Add(fileFound)
    Next

But it keeps throwing out Illegal characters in path error. Any suggestions on what I'm doing wrong?

Upvotes: 1

Views: 7482

Answers (2)

Steve
Steve

Reputation: 216303

The filesystem doesn't understand the double * in released\*\*.doc
Directory.GetFiles oveload that takes only one argument doesn't like the partial path specification (....*.doc)

Try with this

Dim root As String = "C:\Users\tmedina\Documents\testenviroment\released" 

For Each fileFound As String In Directory.GetFiles(root, "*.doc", SearchOption.AllDirectories)) 
    ListBox1.Items.Add(fileFound) 
Next 

The Visual Basic language doesn't need to escape the \ character.
The Directory.GetFiles has an overload that takes your base path, a wildcard search string, and an option to search all of the subfolders of the base path.

Upvotes: 2

Steven Doggart
Steven Doggart

Reputation: 43743

Your problem is you are misusing the GetFiles method. If you want to pass a search string such as "*.doc", you must do so as a second argument, such as:

Directory.GetFiles(Path.Combine(root, "Released"), "*.doc")

Also, you can't give it a folder path that contains a wildcard, such as "C:\Users\tmedina\Documents\testenviroment\Released*". If you want all sub folders, you will need to specify the third parameter for search options:

Directory.GetFiles(Path.Combine(root, "Released"), "*.doc", SearchOption.AllDirectories)

Unless for some reason you don't want it to search all descendant directories and only want it to search the immediate child directories. In that case, you would have to use Directory.GetDirectories to get a list of all the immediate sub-directories, then loop through them calling GetFiles for each one.

Upvotes: 1

Related Questions