Vbs CopyFile a la carpeta seleccionada por el usuario no funciona correctamente

My Vbscript is for prompt to select a folder and then copy a file to the seleted folder My Code is:

Option Explicit
Dim strPath, pth, fso

strPath = SelectFolder( "" )
pth = """" & strPath & "\" & """"

If strPath = vbNull Then
  WScript.Echo "Cancelled"
Else
  Set fso = CreateObject("Scripting.FileSystemObject")

fso.CopyFile "H:\new\file.txt", strPath

' fso.CopyFile "H:\new\file.txt", pth

msgbox("Copy DONE")
End If


Function SelectFolder( myStartFolder )

Dim objFolder, objItem, objShell

On Error Resume Next
SelectFolder = vbNull

Set objShell  = CreateObject( "Shell.Application" )
Set objFolder = objShell.BrowseForFolder( 0, "Select Folder Please", 0, myStartFolder )

If IsObject( objfolder ) Then SelectFolder = objFolder.Self.Path

Set objFolder = Nothing
Set objshell  = Nothing
On Error Goto 0
End Function

Cuando estoy usando fso.CopyFile "H:\new\file.txt", strPath it only copies to the path if the path is like c:\ or d:\ but does not copying file to like 'd:\folder\test\' if selected, it showing error - " PERMISSON DENIED ", but the path has not set any attribute

Cuando estoy usando fso.CopyFile "H:\new\file.txt", pth , it showing error - " Bad File Name or Number " for any folder selection

what should i do? Please Help

preguntado el 28 de mayo de 14 a las 12:05

2 Respuestas

I changed line 5 to the following:

pth = strPath & "\"

and then used the 'fso.CopyFile "H:\new\file.txt", pth' line to do the copy. That worked.

contestado el 28 de mayo de 14 a las 18:05

Ok Thanks @bluebearr ,but will it work on chosing C drive . for this after adding the \ sign pth will be look like C:\\ , will it work? – - BK

It worked on my tests on Windows 7. But remember that by default you can't copy to the root of C: without running as an Administrator. If the doubled up backslash concerns you, you can use pth = strPath & "\" if Right(pth, 1) <> "\" Then pth = pth & "\" - Bluebearr

If you always want a path to end with a single backslash, you can also use the BuildPath() función. Por ejemplo, fso.BuildPath(strPath, "\"). - Bono

Thank you guys. but I go with Bluebearr and its workd. - BK

i discovered that if user select d:\ drive then its lenth is 3 so my edited code is

dim ptlen,finalpatg
ptlen=len(strPath)
if ptlen = 3 then //for only drive selection the ptlen will be 3 so no need to add \
finalpath=strPath
else
 finalpath=strPath & "\" //add slash to path if ptlen not =3
end if

fso.CopyFile "H:\new\file.txt",finalpath

its workd successfully

contestado el 29 de mayo de 14 a las 20:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.