tags:

views:

1108

answers:

1

Can anyone please tell me how to copy a file from one folder to another using vbscripting I had tried this below one from the information provide in the internet.

dim filesys

set filesys=CreateObject("Scripting.FileSystemObject")

If filesys.FileExists("c:\sourcefolder\anyfile.txt") Then

filesys.CopyFile "c:\sourcefolder\anyfile.txt", "c:\destfolder\"

When I execute this one, I get that the permission is denied.

+1  A: 

Try this. It will check to see if the file already exists in the destination folder, and if it does will check if the file is read-only. If the file is read-only it will change it to read-write, replace the file, and make it read-only again.

Const DestinationFile = "c:\destfolder\anyfile.txt"
Const SourceFile = "c:\sourcefolder\anyfile.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
    'Check to see if the file already exists in the destination folder
    If fso.FileExists(DestinationFile) Then
     'Check to see if the file is read-only
     If Not fso.GetFile(DestinationFile).Attributes And 1 Then 
      'The file exists and is not read-only.  Safe to replace the file.
      fso.CopyFile SourceFile, "C:\destfolder\", True
     Else 
      'The file exists and is read-only.
      'Remove the read-only attribute
      fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
      'Replace the file
      fso.CopyFile SourceFile, "C:\destfolder\", True
      'Reapply the read-only attribute
      fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
     End If
    Else
     'The file does not exist in the destination folder.  Safe to copy file to this folder.
     fso.CopyFile SourceFile, "C:\destfolder\", True
    End If
Set fso = Nothing
Tester101
Thanks tester,This solved my probs.Actually i had some probs with the path of the file name given-