Home > Net >  Directory.GetFiles | Get only the specific file
Directory.GetFiles | Get only the specific file

Time:04-28

I want to copy a specific file only but it copies all files in the directory. Is there any way to achieve it?

here is my code:

    Dim dir As DirectoryInfo = New DirectoryInfo("\\SERVER-PC\BrokerDatabase\BrokerDatabase\Attachments")

    For Each fi As FileInfo In dir.GetFiles()
        fi.CopyTo("D:\"   fi.Name)
    Next

CodePudding user response:

It copies all files in the directory because you're looping the .CopyTo without any condition. If the filename of the file you are looking for is static, add a condition with it so it won't copy all the files.

 Dim dir As DirectoryInfo = New DirectoryInfo("\\SERVER-PC\BrokerDatabase\BrokerDatabase\Attachments")

    For Each fi As FileInfo In dir.GetFiles()
        If fi.Name = "FileToBeCopied.txt" Then
            fi.CopyTo("D:\"   fi.Name)
        End If

    Next
  • Related