2017-03-03 42 views
-1

我在使用FileSystemObject.CopyFile时遇到问题。我想我正确地使用它,从我读过的论坛,但我仍然得到以下编译器错误:FileSystemObject CopyFile:Unhanded Exception

ArgumentException was unhandled: Value does not fall within expected range

下面是代码:

Public Class Form1 
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    Dim fso As New Scripting.FileSystemObject 
    Dim testfolderchk 
    testfolderchk = Dir("C:\Test\") 
    Dim inforeader As System.IO.FileInfo 
    Dim filedestinationcheck = Dir("C:\Test2\") 

    If testfolderchk <> "" Then 
     If Microsoft.VisualBasic.Left(testfolderchk, 4) = "test" Then 
      inforeader = My.Computer.FileSystem.GetFileInfo("C:\Test" & testfolderchk) 
      filetime = (inforeader.LastWriteTime) 
      If testfolderchk = filedestinationcheck Then GoTo skipfile 
      If testfolderchk = filedestinationcheck2 Then GoTo skipfile 

     Else : GoTo skipfile 
     End If 
    End If 

fso.CopyFile(testfolderchk, filedestinationcheck, True) 
+3

的'系统.IO'命名空间具有各种与FileSystemObject相比更适合.NET代码的文件相关方法。 – Plutonix

+0

建议?任何人? – user2644085

+0

'建议?'是的,不要使用FSO并且不要使用'GoTo'。只需进行一点研究,您可以在这里找到数百个文件副本小程序 – Plutonix

回答

2

正如建议评论你应该放弃使用FileSystemObject,并使用替代System.IO命名空间,特别是FileInfo

Provides properties and instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects. This class cannot be inherited.

随着FileInfo你CA n使用方法CopyTo (String, Boolean)

Copies an existing file to a new file, allowing the overwriting of an existing file.

我起草了一些代码向你展示我的意思:

Dim folderToCheck As String = "C:\Test" 
Dim destinationFolder As String = "C:\Test2" 

Dim file As IO.FileInfo = New IO.FileInfo(IO.Path.Combine(folderToCheck, "test.txt")) 

Dim filetime As Date = file.LastWriteTime 

file.CopyTo(IO.Path.Combine(destinationFolder, file.Name), True) 

注意使用Path.Combine

Combines two strings into a path.

+1

谢谢。我做了类似的事情,结果很好。我很感激。 @Bugs – user2644085