eyal
eyal

Reputation: 379

DirectoryInfo.GetFiles Method (String, SearchOption) exception: System.ArgumentException: Illegal characters in path

I'm using the above method, and get the above exception.
I don't see any illegal characters in the Directory name (there're other directories which return results as expected).
When I call the static Directory.GetFiles(String, String, SearchOption) with the same directory that fails on the DirectoryInfo method, there's no problem and the method returns as expected.
Any idea what could cause this misbehavior?

Upvotes: 0

Views: 1060

Answers (2)

Sjors Miltenburg
Sjors Miltenburg

Reputation: 2750

I ran into this problem when I was scanning a directory on a mac (through a network share).

DirectoryInfo.GetFiles(@"//macbook/sharedfolder")

Apperenately it's quite legal on a mac to have chars like <,>,? in a filename, but on windows it's not.

When one of the filenames in the directory had invalid chars I got this "illegal characters" error.

Upvotes: 1

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60503

as stated in msdn, an ArgumentException is raised when

searchPattern contains one or more invalid characters defined by the GetInvalidPathChars method.

(searchPattern is the first String argument of the method).

to test this, you may try

var invalidChars = <yourSearchPattern>.Select(x => x).Intersect(Path.GetInvalidPathChars()).ToList();

if you find something in invalidChars, you'll have found the source of your problem.

EDIT

Why does it work with Directory.GetFiles() ? I must admit I don't understand.

An ArgumentException is raised

if the first argument(path) has invalid chars (or IsNullOrWhiteSpace), or

if the second argument (searchPattern)

does not contain a valid pattern

And a valid pattern is

The parameter cannot end in two periods ("..") or contain two periods ("..") followed by DirectorySeparatorChar or AltDirectorySeparatorChar, nor can it contain any of the characters in InvalidPathChars.

As InvalidPathChars (obsolete) give me the same result as GetInvalidPathChars(), at least in .net 4.5, I must admit I'm stuck.

You may use a different version of .net, where there's a difference between the two ?

Upvotes: 1

Related Questions