vb.net 如何将文件从一个目录传输到另一个目录中的最新文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35614377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:44:36  来源:igfitidea点击:

How to transfer a file from one directory to another that is the newest file

vb.net

提问by Carl D.

I am trying to transfer a file from one directory to another that is the current and latest file in that folder, however I cannot use Robocopy to do this, since it fails when the server is logged out. Is there another way I can do this in Vb.net?

我试图将文件从一个目录传输到另一个目录中的当前和最新文件,但是我不能使用 Robocopy 来执行此操作,因为它在服务器注销时失败。有没有另一种方法可以在 Vb.net 中做到这一点?

Thank you.

谢谢你。

回答by Valerie

you can use File.Copy(Source,Destination,Overwrite?)to overwrite the file with a newer one, or

您可以使用File.Copy(Source,Destination,Overwrite?)更新的文件覆盖文件,或者

If File.Exists(destination) Then File.Delete(destination);
' Move the file.
File.Move(source, destination);

to move the file... I pesonally prefer:

移动文件...我个人更喜欢:

File.Copy(Source,Destination,true)
File.Delete(Source)

To move the file and overwrite it if it exists :)... less code

移动文件并在它存在时覆盖它:)...更少的代码

Here's the code to move the latest file to another directory

这是将最新文件移动到另一个目录的代码

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!

Hope that Helps

希望有帮助