1

For some reason, this statement completely bypasses folders which contain said text, what am I doing wrong?

For Each fold As String In Directory.GetDirectories("C:\documents")
    If fold.Contains("pdf") Then

I have folders in the c:\documents folder with names such as:

pdfone
pdfretrieve
extrapdf

When VS reads through, I see the strings:

"c:\documents\pdfone"
"c:\documents\pdfretrieve"
"c:\documents\extrapdf"

But it reads right past them and doesn't enter the If statement.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Gmac
  • 169
  • 2
  • 14
  • 1
    Are you sure that it isn't `PDFone`? – Tim Schmelter Jun 02 '15 at 13:57
  • Yes, it's PDFone. Is the .Contains property case sensitive? – Gmac Jun 02 '15 at 13:58
  • This works great here. Are you sure your "fold" contains what you think? – the_lotus Jun 02 '15 at 14:00
  • 2
    It's actually PDFone?! You lied in your question! :) – the_lotus Jun 02 '15 at 14:01
  • can also change to `If fold.ToLower().Contains("pdf") Then`, although the answer below is a better approach – RianBattle Jun 02 '15 at 14:35
  • @RianBattle: apart from the fact that this creates unnecessary string garbage in memory it is also prone to localization issues like the [turkish i problem](http://www.moserware.com/2008/02/does-your-code-pass-turkey-test.html). So using `ToUpper`/`ToLower` [is not the best approach](http://stackoverflow.com/questions/234591/upper-vs-lower-case) to provide case-insensitivity. – Tim Schmelter Jun 02 '15 at 14:40
  • @TimSchmelter I wasn't aware of that at all, thanks for the info (this is why I like StackOverflow!) – RianBattle Jun 02 '15 at 15:00

1 Answers1

2

Yes, it's PDFone. Is the .Contains property case sensitive?

String.Contains is case-sensitive (like most methods in the .NET framework). You have to use String.IndexOf if you want to ignore the case:

If fold.IndexOf("pdf", StringComparison.InvariantCultureIgnorecase) >= 0 Then

MSDN mentions it here:

this method performs an ordinal (case-sensitive and culture-insensitive) comparison. The search begins at the first character position of this string and continues through the last character position.

As an aside, GetDirectories returns the directory-name including their paths. So searching for substrings on the complete path is error-prone. Instead you could use Path.GetFileName(yes, not GetDirectoryName since that returns the parent directory, that's mentioned in the remarks):

If Path.GetFileName(fold).IndexOf("pdf", StringComparison.InvariantCultureIgnorecase) >= 0 Then
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939