:: On Thu, 31 Mar 2022 17:22:56 -0700 (PDT)
:: (microsoft.public.vb.general.discussion)
:: <
f3951d28-ac6b-4ab2...@googlegroups.com>
:: Kim Hawker <
hawke...@gmail.com> wrote:
> How does one transfer a file from folder1 to folder2 in vb6? I’ve
> tried now for a few days and have not had any success.
Summing up all the stuff discussed, here's a code snippet which allows
to move files to a different folder and optionally rename them, notice
that the code doesn't use APIs and that it tries to leave source and
destination untouched in case of error; to use the code to move a file
just issue something like
sSrcFile = "c:\temp\foobar.txt"
sDstFile = "d:\somedir\readme.txt"
bRet = MoveFile(sSrcFile, sDstFile)
If Not bRet Then
MsgBox "Error:" & Err.Number & " " & Err.Description
' ...handle error condition...
End If
all the above being said, here's the code
Option Explicit
' move a file to a different path and optionally rename it
Public Function MoveFile(ByVal sSrc As String, _
ByVal sDst As String) As Boolean
Dim sPath As String, sTemp As String
Dim bExist As Boolean
' init
On Local Error Resume Next
Err.Clear
MoveFile = False
' setup dst path and temp name
sPath = GetPath(sDst)
sTemp = TempFile(sPath)
' if dst exists rename to temp
If FileExists(sDst) Then
bExist = True
Name sDst As sTemp
If Err.Number <> 0 Then
Exit Function
End If
End If
' move src to dst
Name sSrc As sDst
If Err.Number <> 0 Then
If bExist Then
' restore dst from temp
Name sTemp As sDst
End If
Exit Function
End If
' delete temp (old dst file)
If Not KillFile(sTemp) Then
Exit Function
End If
' all ok
MoveFile = True
End Function
' delete a file
Public Function KillFile(ByVal sPathName As String) As Boolean
Dim bRet As Boolean
' init
On Local Error GoTo Catch
Err.Clear
bRet = False
' set attr to normal and kill the file
SetAttr sPathName, vbNormal
Kill sPathName
bRet = True
BailOut:
KillFile = bRet
Exit Function
Catch:
bRet = False
Resume BailOut
End Function
' generate a temp file name for a given folder
Public Function TempFile(ByVal sPathName As String) As String
Dim sTemp As String
Dim lTemp As Long
Dim bDone As Boolean
bDone = False
Randomize Timer
While Not bDone
lTemp = Int(Rnd * &H7FFFFFFF)
sTemp = sPathName & "~" & Hex(lTemp) & ".tmp"
bDone = IIf(FileExists(sTemp), False, True)
Wend
TempFile = sTemp
End Function
' get the path out of a pathname
Public Function GetPath(ByVal sPathName As String) As String
Dim sPath As String, nPos As Integer
sPath = ".\"
nPos = InStrRev(sPathName, "\")
If nPos < 1 Then
nPos = InStr(sPathName, ":")
End If
If nPos > 0 Then
sPath = Mid(sPathName, 1, nPos)
End If
GetPath = sPath
End Function
' check if a file exists
Public Function FileExists(ByVal sPathName As String) As Boolean
Dim vAttr As VbFileAttribute
Dim bRet As Boolean
On Local Error Resume Next
Err.Clear
vAttr = GetAttr(sPathName)
bRet = IIf(Err.Number = 0, True, False)
Err.Clear
FileExists = bRet
End Function