Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Directory.GetFiles() sees TIFs but not JPGs 1

Status
Not open for further replies.

IlyaRabyy

Programmer
Nov 9, 2010
571
US
Colleagues,
Subject line says it. Here's the code:

Code:
'====================================================================================================================================
Sub GetFilesList(ByRef taFiles() As String, ByVal tsDir As String, tsPattern As String, Optional tlIncludePath As Boolean = False)
'====================================================================================================================================
' Purpose       : Fills out the given String Array with the found files' names of the given pattern in the given directory.
' Description   : Essentially - wrapper around Directory.GetFiles(Dir as String, File Pattern as String) built-in function.
'		  The difference is that additional parameter: Include [full] Path flag.
' Parameters	 : Pointer on the String array to fill out.
'		   Directory to search as String.
'		   File name's pattern (e.g. "PO*.XML") to seek.
'		   Include or not include the full path to the found files, optional, default - just files' names.
' Returns	 : N/A.
' Side effects  : The parameter-array will be resized, all the previous rows will be deleted and replaced with the new ones.
' Notes         : 1. Generic.
'                 2. Complies with .NET Framework ver. 1.1 and higher, .NET Core ver. 1.0 and higher.
'		  3. All String parameters are mandatory.
'		  4. String parameters are case-sensitive.
'		  5. No String parameters' verification (except if empty), presumed valid.
' Author        : Ilya
' Revisions     : by Ilya on 2022-06-29 - completed 1st draft.
'====================================================================================================================================
' Check if String params are blank, if so - just return.
If (IsNothing(taFiles) Or IsNothing(tsDir) Or tsDir.Trim() = "" Or IsNothing(tsPattern) Or tsPattern.Trim(tsPattern) = "") Then
 Return
End If

' Does directory exist? If not - just return.
If Not Directory.Exists(tsDir) Then Return

' Adjust params
Dim lsDir As String = AddBackSlash(tsDir), lsPattern As String = tsPattern.Trim()
Dim laFiles(0) As String, liCnt As Int32 = 0, lsErrMsg As String = "", llGoOn As Boolean = True

' Let's get 'em!
Try
   laFiles = Directory.GetFiles(lsDir, lsPattern)
Catch loErr As Exception
   llGoOn = False
   lsErrMsg = Read_Exception(loErr)
   MsgBox(lsErrMsg, vbCritical, "Error occurred!")
End Try

If Not llGoOn Then Return

' Path or no Path?
If Not tlIncludePath Then
   For liCnt = 0 To laFiles.Length() - 1
      laFiles(liCnt) = laFiles(liCnt).Replace(lsDir, "")
   Next ' liCnt
End If

' And we're done here!
taFiles = laFiles

End Sub
'====================================================================================================================================

This above procedure is called from this code snippet:

Code:
For Each lcExt In gaExtensions
   CheckFileSizes(laOversizedImgFiles, giMaxImgSize, gsLastTargetDir, lcExt)

' Were the any oversized image files with this extension?
   If laOversizedImgFiles.Length = 0 Then Continue For

' We've gotten oversized files' list for one, current extension only.
' Transfer them to the Totals array, but preserve the current Totals' array's size:
   AppendArray1Dim(laTtlOversizedImgFiles, laOversizedImgFiles)
   ReDim laOversizedImgFiles(0)
Next

Just in case, AddBackSlash() function (mimics the ADDBS() in VFP)

Code:
'===================================================================================================================================
Public Function AddBackSlash(ByVal tsPath As String) As String
'===================================================================================================================================
' Purpose       : Ensures the given path string has backslash at the end.
' Description   : Checks if the passed parameter's data type match those of the Function's argument; if not – throws error message 
'                 and returns unchanged parameter.
'                 Checks if it's an empty string, if it is - returns it As-Is.
'                 Checks if it's only a file name, if it is - returns it As-Is.
'                 Checks the given parameter-string in case it's full path to a file, cuts off the file name if it is.
'                 Checks if the given parameter-string has backslash at the end, adds it if it has not.
' Parameters    : Path as String - mandatory
' Returns       : Path with the backslash at the end, as String.
' Side effects  : None.
' Notes         : 1. Generic, applies with .NET Framework ver. 1.1, .NET Core 1.0, .NET Standard 1.0 and higher.
'                 2. Verbose on errors, silent otherwise.
' Author        : Ilya
' Revisions     : 2020-03-09 by Ilya – completed 1st draft.
'===================================================================================================================================
Dim lsPath As String = "", lsRet As String = ""

' Parameter's verification
If VarType(tsPath) <> VariantType.String Then
	MsgBox("Invalid parameter passed: " & Chr(34) & "tsPath" & Chr(34) & " must be of type String", MsgBoxStyle.Critical, "Fatal Error: INVALID PARAMETER")
	Return lsRet
End If

If String.IsNullOrEmpty(tsPath) Then
	Return lsRet
End If

If Path.GetFileName(tsPath) <> "" And Path.GetExtension(tsPath) <> "" Then 'Path + File name? Strip off that latter
   lsPath = tsPath.Replace(Path.GetFileName(tsPath), "")
Else
   lsPath = tsPath
End If

If String.IsNullOrEmpty(lsPath) Then ' Only the file name was passed? Return blank string
   Return lsPath
End If

' Check for the closing backslash
If Strings.Right(lsPath, 1) <> Path.DirectorySeparatorChar Then
   lsRet = lsPath & Path.DirectorySeparatorChar
Else
   lsRet = lsPath
End If

Return lsRet
End Function
'===================================================================================================================================

What's frustrating is that Directory.GetFiles() in the code above does "see" TIF type files, but flat refuses to "see" JPG files - and they are there!

2023_03_10_10_42_Directory.GetFiles_Sees_TIF_but_not_JPG_s6p4qo.jpg


What's even more frustrating is that, when it's run alone, Directory.GetFiles() does see JPGs:

2023_03_10_10_42_Directory.GetFiles_Sees_TIF_but_not_JPG_02_hjfutg.jpg


Any idea, anyone, what might cause this behavior?
AHWBGA!
 
See the difference:
In the not working code you first declare one-element array and then try to store in it the the result of the method, which seems to have more that one element (two JPG files)
Code:
Dim laFiles(0) As String
...
laFiles = Directory.GetFiles(lsDir, lsPattern)

In the working example you declare array of unknown size and initialize it with result of the method
Code:
Dim laFiles() As String = Directory.GetFiles(lsDir, lsPattern)

 
Maybe I was not clear enough:
The problem is that the same code "sees" TIF ("*.TIF") but doesn't "see" JPEG ("*.JPG").
Here's the latest versions of the code:

Code:
'====================================================================================================================================
Sub CheckFileSizes(ByRef taImgFiles() As String, ByVal tiMaxFSize As Int32, ByVal tsDir As String, ByVal tcExt As String) 
'====================================================================================================================================
ReDim taImgFiles(-1) ' Clearing the gotten array
Dim laImgFiles() As String = Directory.GetFiles(gsLastTargetDir, "*." & tcExt), I As Int32, J As Int32 = -1
' Check if there any files of this type, Return if none.
If IsNothing(laImgFiles) Then Return
Dim liListLen As Int32 = laImgFiles.Length, liFileSize As Int32 = 0
For I As Int32 = 0 To liListLen - 1
	liFileSize = GetFileSize(laImgFiles(I))
	If liFileSize > tiMaxFSize Then
	   J+= 1
		ReDim Preserve taImgFiles(J)
	   taImgFiles(J) = laImgFiles(I)
	End If
Next I
End Sub
'====================================================================================================================================

This Sub is called from Main() in the cycle, 1st time with tcExt = "TIF", 2nd time with tcExt = "JPG", 3rd time with tcExt = "PNG", etc..

Code:
For Each lcExt In gaExtensions
	CheckFileSizes(laOversizedImgFiles, giMaxImgSize, gsLastTargetDir, lcExt)
' Were the any oversized image files with this extension?
	If laOversizedImgFiles.Length = 0 Then Continue For
' We've gotten oversized files' list for one, current extension only. Transfer them to the Totals array, but preserve the current Totals' array's size:
	AppendArray1Dim(laTtlOversizedImgFiles, laOversizedImgFiles)
Next

As you can see, the declaration of the local array is the same for each call. However, when I added a PNG file into the same directory with image files, that same code didn't see PNG as well.
The impression I've gotten is that Directory.GetFiles() works only once, with that 1st file name pattern and keeps it, thus being unable to "see" files with another file name pattern... (or- am I getting' crazy? :-()

Regards,

Ilya
 
I would first make sure the extension you hope you are getting is what you actually get:

Code:
For Each lcExt In gaExtensions[blue]
    MessageBox.Show(lcExt)[/blue]
    CheckFileSizes(laOversizedImgFiles, giMaxImgSize, gsLastTargetDir, lcExt)[green]
' Were the any oversized image files with this extension?[/green]
    If laOversizedImgFiles.Length = 0 Then Continue For[green]
' We've gotten oversized files' list for one, current extension only. Transfer them to the Totals array, but preserve the current Totals' array's size:[/green]
    AppendArray1Dim(laTtlOversizedImgFiles, laOversizedImgFiles)
Next

---- Andy

"Hmm...they have the internet on computers now"--Homer Simpson
 
Andrzejek said:
make sure the extension you hope you are getting is what you actually get

They are (this is the 2nd iteration in the For K cycle):

2023_03_13_14_44_Directory.GetFiles_Sees_TIF_but_not_JPG_03_pbsfbg.jpg


Note that even ReDim laImgFiles(-1) before Next doesn't help.
Moreover: I changed the order of the extensions in the INI file so that JPG would be first in the list, and now Directory.GetFiles() sees only JPGs...
IOW, it seems this function cannot work in a cycle with the same array.

Regards,

Ilya
 
You didn't show the content of the array gaExtensions, maybe the 1. extension is ok but the other are not.

Or declare the array immediately before the loop with your extensions and try something like this
Code:
Dim gaExtensions() As String = {"*.jpg", "*.png", "*.tif"}
For Each lcExt In gaExtensions
    CheckFileSizes(laOversizedImgFiles, giMaxImgSize, gsLastTargetDir, lcExt)
...
Next

 
mikrom said:
You didn't show the content of the array gaExtensions, maybe the 1. extension is ok but the other are not.

They are all there. (Never mind that I changed the array's scope from "ga" (Public, Global) to "la" (Local).)

2023_03_14_10_48_Directory.GetFiles_Sees_TIF_but_not_JPG_04_c1ayz4.jpg


so, the problem boils down to this: why Directory.GetFiles() doesn't update the array on second, third, and so on, calls?

Regards,

Ilya
 
There is something else going on...
What I did - placed a button and a list box on a Form

Code:
Imports System.IO
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Call FillListBox("E:\Andrzej\", "*.xls")
        Call FillListBox("E:\Andrzej\", "*.txt")
    End Sub

    Private Sub FillListBox(ByRef strDir As String, ByRef strExt As String)
        Dim laImgFiles() As String = Directory.GetFiles(strDir, strExt)

        For x As Integer = LBound(laImgFiles) To UBound(laImgFiles)
            ListBox1.Items.Add(laImgFiles(x))
        Next
    End Sub
End Class

and I get all xls files and txt files in a list box. If I click button again, I get those files again.

Is it possible you clear some data somewhere else in your code... [ponder]

---- Andy

"Hmm...they have the internet on computers now"--Homer Simpson
 
On your screenshot it looks like the second and third array elements begin with space, i.e. like "_JPG", "_TIF". Isn't it so ?
 
Mikrom said:
the second and third array elements begin with space, i.e. like "_JPG", "_TIF"

Right!
The Split() doesn't trim the leading spaces, and I haven't noticed it till I read your post here.
Thank you, colleague!
[thanks]
Problem solved.
Case closed.

Regards,

Ilya
 
Hi IlyaRabyy,
I suspected something sneaky was going on and just installed Visual Studio on my Windows PC to try out the code you provided. Then you posted the picture and I noticed the mistake.
But now VS is ready on my Windows box, so I'm more prepared than before.
:)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top