Non-printable characters in file names break my recursive file listing VB Script

353 Views Asked by At

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
1

There are 1 best solutions below

1
MC ND On

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)