我正在尝试将文件从一个目录传输到另一个目录,该目录是该文件夹中的当前和最新文件,但我无法使用Robocopy执行此操作,因为它在服务器注销时失败。还有其他方法可以在Vb.net中执行此操作吗?
谢谢。
答案 0 :(得分:2)
您可以使用File.Copy(Source,Destination,Overwrite?)
覆盖较新的文件或
If File.Exists(destination) Then File.Delete(destination);
' Move the file.
File.Move(source, destination);
移动文件......我个人更喜欢:
File.Copy(Source,Destination,true)
File.Delete(Source)
移动文件并覆盖它(如果存在):(少了代码)
这是将最新文件移动到另一个目录的代码
Dim SourceDirectory As String = "C:\sourcedirectory\"
Dim SaveDirectory As String = "C:\targetdirectory\"
Dim LatestFile as IO.FileInfo = Nothing
'Let's scan the directory and iterate through each file...
Dim DirInfo As New IO.DirectoryInfo(SourceDirectory)
For Each file As IO.FileInfo In DirInfo.GetFiles()
If LatestFile Is Nothing Then
'This is the first time we run any permutations, so let's assign this file as "the latest" until we find one that's newer
LatestFile = file
ElseIf file.CreationTime > LatestFile.CreationTime Then
'Changes the "Latest file" if this file was created after the previous one.
'You can also change the check to .LastAccessTime and .LastWriteTime depending on how you want to define "the newest"...
LatestFile = file
End If
Next
'Now we move the file, but first, check to see if we actually did find any file in the source directory
If NewestFile IsNot Nothing Then
NewestFile.CopyTo(SaveDirectory & NewestFile.Name,true) 'will copy and overwrite existing file
'Now we can delete the old one
NewestFile.Delete()
Else
'Could not find the newest file, or directory might be empty...
End If
'Done!
希望能帮助