2017-03-03 79 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