Conrad Jagger
Conrad Jagger

Reputation: 643

Vb.Net - Copy files based on pattern

I have got table named FILELISTS

Table Name - Filelists
Field - FileNames

Data Value

  1. File1.txt
  2. File2.csv
  3. File3*.csv

I'm struggling to write the code, as per above if it has a file name (like file1.txt and file2.txt) it needs to copy from source to destination. If file name is pattern (like File3*.csv) then copy all files that matches this pattern from source to destination.

I'm enumerating through above row in Vb.net using data reader.

Upvotes: 2

Views: 1250

Answers (2)

Paul Ishak
Paul Ishak

Reputation: 1093

DirectoryInfo, FileInfo - - You deleted your other question before I could click post... but this works with .net framework 2.0, like you asked

Option Strict On
Imports sO = System.IO.SearchOption
Imports dI = System.IO.DirectoryInfo
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        For Each F In (New dI("C:\")).GetFiles("*.*", sO.TopDirectoryOnly)
            MsgBox(F.FullName)
            'Do your copy here
        Next
    End Sub
End Class

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460380

You can use Directory.EnumerateFiles and File.Copy, for example:

var filePatterns = database.GetFileNamePattern(); // your method that returns the list of files
// assuming you've stored the source- and dest.-directories in the app-settings
string sourceFolder = Properties.Settings.Default.SourceFolder;      
string destFolder = Properties.Settings.Default.DestinationFolder;
foreach (string pattern in filePatterns)
{
    var files = Directory.EnumerateFiles(
        sourceFolder,
        pattern,
        SearchOption.TopDirectoryOnly);
    foreach (string file in files)
    {
        File.Copy(file, Path.Combine(destFolder, Path.GetFileName(file)), true);
    }
}

Edit: Sorry, here the VB.NET version:

' your method that returns the list of files:
Dim filePatterns = database.GetFileNamePattern()  
' assuming you've stored the source- and dest.-directories in the app-settings
Dim sourceFolder As String = My.Settings.SourceFolder
Dim destFolder As String = My.Settings.DestinationFolder
For Each pattern As String In filePatterns
    Dim files = Directory.EnumerateFiles(sourceFolder, pattern, SearchOption.TopDirectoryOnly)
    For Each file As String In files
       IO.File.Copy(file, IO.Path.Combine(destFolder, IO.Path.GetFileName(file)), True)
    Next
Next

Upvotes: 2

Related Questions