0

I created a VB script to recursively list all of its file and subfolder files. The script begins fine but eventually crashes in any folder containing a file with a non-printable character/s in their filenames, i.e. I see little squares when I browse the folder in Explorer. I'm not sure how to change my below error handling to continue when it finds a file with such characters.

Any advice or solutions would be appreciated. Thank you.

Set objFSO = CreateObject("Scripting.FileSystemObject")
strFolder = "C:\Input\"
Set objFolder = objFSO.GetFolder(strFolder)
Set NewFile = objFSO.CreateTextFile("C:\Output\" & objFolder.Name & " FileList.txt", True)
Set colFiles = objFolder.Files

On Error Resume Next

For Each objFile In colFiles
    NewFile.WriteLine(objFile.Path)
    If Err Then
        Err.Clear
    End If
Next

ShowSubFolders(objFolder)

Sub ShowSubFolders(objFolder)
    Set colFolders = objFolder.SubFolders

    For Each objSubFolder In colFolders
        Set colFiles = objSubFolder.Files
            For Each objFile In colFiles
                NewFile.WriteLine(objFile.Path)
                If Err Then
                    Err.Clear
                End If
            Next
        ShowSubFolders(objSubFolder)
    Next
End Sub

NewFile.Close
  • I cannot say anything about VB (I do not use MS-Windows, only few people here at SO do), but here is a general advice: it appears that you do not know what encoding you are actually using. Without that information you are digging in the dark, since you do not know what you are looking for. Find out your setup, and if it varies or is constant from installation to installation. Only then, when you know how characters are encoded inside your setup, then you can start debugging. – arkascha Nov 12 '13 at 07:44
  • Thanks guys. I am trying MC ND's solution. I have removed error handling and will note the error if it appears again. It does appear to be a unicode->ANSI translation error. – user2836826 Nov 14 '13 at 00:28

1 Answers1

1

Create the output text file as unicode so it can handle "non printable" characters. Third parameter of CreateTextFile.

Set NewFile = objFSO.CreateTextFile(" ... ", True, True)

EDITED

If you can not work with unicode files, then file/folder names should be converted from unicode to ansi before writing to output file. This will do the conversion

Function Unicode2Ansi( text )
    Unicode2Ansi = text 
    With (WScript.CreateObject("ADODB.Stream"))
        ' Put data into stream
        .Type = 2 '( adTypeText )
        .Charset = "x-ansi"
        .Open
        .WriteText text
        'Retrieve data from stream
        .Position = 0
        Unicode2Ansi = .ReadText
        .Close
    End With 
End Function

And adapt code to call it NewFile.WriteLine Unicode2Ansi(objFile.Path)

MC ND
  • 69,615
  • 8
  • 84
  • 126