2016-01-22 39 views
0

即时通讯做一个应用程序,检查或比较文件是否存在于另一个文件夹的备份文件夹中。我可以通过声明特定的文件或数组来完成它。像这个。检查文件夹中的多个文件是否存在,但没有特定的文件名VB.NET

" = file1.txt"
" = file2.txt"
"etc..."

但如何没有特定的文件或数组?

这是我的代码:

Imports System.IO 
Public Class Form3 
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    check() 
End Sub 
Sub check() 

    Dim src As String = "D:\test" 
    Dim dest As String = "D:\test2" 

    Dim srcdir As New DirectoryInfo(src) 
    Dim destdir As New DirectoryInfo(dest) 
    Dim srcfile As FileInfo() = srcdir.GetFiles 
    Dim destfile As FileInfo() = destdir.GetFiles 

    Dim fi As FileInfo 

    For Each fi In srcfile 
     If fi.Name = fi.Name(destfile) Then 
      MsgBox("no new files") 
     Else 
      MsgBox("new files detected") 
     End If 
    Next 

    For Each fi In srcfile 
     File.Copy(fi.FullName, dest & fi.Name) 
    Next 

End Sub 
+0

我不知道如果我得到它的权利,但你想,如果它不复制文件目标文件中不存在? –

+0

如果它有一个新文件,那么是的。但我想先检查主文件夹是否与备份文件夹有相同的文件。 – Dhan

+0

试试我的答案。我还没有测试过,因为我没有在我的电脑上。 –

回答

0

试试这个:

Dim filesToCopy As New ArrayList() 
    For Each Dir As String In System.IO.Directory.GetFiles(src) ' This will check every file from src or (D:\Test) 
     Dim dirInfo As New System.IO.DirectoryInfo(Dir) 
     If Not System.IO.File.Exists(dest & "\" & dirInfo.Name) Then 'This will check if the file from src exists in dest (D:\Test2) 
      filesToCopy.Add(dirInfo.Name) 
     End If 
    Next 

    If filesToCopy.Count > 0 Then 
     If MsgBox("There are new files found. Do you want to sync it now?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm") = MsgBoxResult.Yes Then 
      For i = 0 To filesToCopy.Count - 1 
       System.IO.File.Copy(src & "\" & filesToCopy(i), dest & "\" & filesToCopy(i)) 
      Next 
     End If 
    End If 

编辑,以便你可以得到最你需要什么。

+0

当我尝试执行时没有任何反应。我认为它需要一个'FileInfo'来获取文件? – Dhan

+0

再次尝试我的更新代码。对不起,迟到的回复,我的电脑刚刚完成更新.. –

+0

谢谢!它现在正在工作! :)但我认为这不是我想要的输出。但没关系。 – Dhan

0

试试这个 我们的代码是工作的罚款JST改变它的逻辑我下面的代码alredy给出

Imports System.IO 
    Public Class Form3 
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     check() 
    End Sub 
    Sub check() 

    Dim src As String = "D:\test" 
    Dim dest As String = "D:\test2" 

    Dim srcdir As New DirectoryInfo(src) 
    Dim destdir As New DirectoryInfo(dest) 
    Dim srcfile As FileInfo() = srcdir.GetFiles 
    Dim destfile As FileInfo() = destdir.GetFiles 

    Dim fi As FileInfo 

    For Each fi In srcfile 
     If If Not System.IO.File.Exists(fi.Name) Then 
      MsgBox("no new files") 
      Exit sub 
     Else 
      For Each fi In srcfile 
       File.Copy(fi.FullName, dest & fi.Name) 
      Next 
     End If 
    Next 



End Sub 
+0

其实我对'destfile'错误fi.Name()''的括号下,我已经尝试过,'因为Each'里面的'Else' if语句的,但它有下埃罗fi'下'并且它表示'For循环控制变量'fi'已被封闭for循环使用。 – Dhan

相关问题