Search code examples
unicodevb6filenames

How to read / write binary file with Unicode filename in VB6


I have this code:

Function cpyBIN(cpFilename As String)
    Dim litefile() As Byte
    Dim FN As Integer
    Dim xlof As Long

    FN = 1
    Open cpFilename For Binary As FN
    xlof = LOF(FN)
    ReDim litefile(xlof)

    Get FN, , litefile
    Open cpFilename & "Backup" For 
    Binary As #2

    Put #2, , litefile
    Close #2
    Close FN
End Function

and I use it in a Form like this :

Private Sub cmdBackup_Click()
Dim strComputer, objWMIService, colFiles, objfile

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    

Set colFiles = objWMIService.ExecQuery("Select * from CIM_Datafile where Drive='D:' and path='\\contoh\\'")

For Each objfile In colFiles
cpyBIN (objfile.Name)
Next


End Sub

in the contoh folder there are 2 sample files:

  • namafile.exe
  • namafile♣♣♠.exe

when I run the code there is an error message like in the picture:

enter image description here

the error is in the line as shown in the picture:

enter image description here

how to make it supports unicode filename? or is there any replacement for this function??


Solution

  • There are several ways to make a copy of a file with Unicode file names. The first way is by using the Windows API:

    Declare Function CopyFileW Lib "kernel32.dll" (ByVal lpExistingFileName As Long, _
       ByVal lpNewFileName As Long, Optional ByVal bFailIfExists As Long) As Long
    
    For Each objfile In colFiles
       CopyFileW StrPtr(objfile.Name), StrPtr(objfile.Name & ".Backup")
    Next
    

    The second way is by using a FileSystemObject:

    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    
    For Each objfile In colFiles
       fso.CopyFile objfile.Name, objfile.Name & ".Backup", True
    Next
    

    The third way is by using an ADO Stream:

    Dim s As ADODB.Stream
    Set s = New ADODB.Stream
       
    s.Open
    s.Type = adTypeBinary
    
    For Each objFile In colFiles
       s.LoadFromFile objFile.Name
       s.SaveToFile objFile.Name & ".Backup", adSaveCreateOverWrite
    Next
    
    s.Close
    

    If you want to read data, I would use an ADO Stream:

    Dim s As ADODB.Stream
    Set s = New ADODB.Stream
    
    s.Open
    s.Type = adTypeBinary
    
    For Each objFile In colFiles
       s.LoadFromFile objFile.Name
       data = s.Read()
       'use the data somehow
    Next
    
    s.Close