File copy to directory when dir name is not available

~OSD~ 2,131 Reputation points
2020-12-02T10:53:42.193+00:00

Hi,

I would like to copy a file (MyFile.txt) to multiple directories with a dynamically created names. In other words, I know the ParentDirectory name but not the child directories as shown in screenshot.

44421-image.png

There may be sub-directories under child directory, but I would like to copy a file to all child directories, possible /supported in vb.net?

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,595 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.9K Reputation points
    2020-12-02T14:33:49.963+00:00

    It seems that you need the immediate child directories only. In this case, try this loop:

    Dim SourceFile = "C:\MyFile.txt"
    Dim TargetDir = "C:\ParentDir"
    
    Dim f = New FileInfo(SourceFile)
    
    For Each d In New DirectoryInfo(TargetDir).EnumerateDirectories("*")
        f.CopyTo(Path.Combine(d.FullName, f.Name), overwrite:=True)
    Next
    
    1 person found this answer helpful.
    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Viorel 112.9K Reputation points
    2020-12-02T12:32:44.587+00:00

    To copy to directories that do not have subdirectories:

    Dim SourceFile = "C:\MyFile.txt"
    Dim TargetDir = "C:\ParentDir"
    
    Dim f = New FileInfo(SourceFile)
    
    For Each d In New DirectoryInfo(TargetDir).EnumerateDirectories("*", SearchOption.AllDirectories)
        If d.EnumerateDirectories().Any() Then Continue For
        f.CopyTo(Path.Combine(d.FullName, f.Name), overwrite:=True)
    Next
    

    Remove ‘If’ if you want to copy to all subdirectories.

    1 person found this answer helpful.
    0 comments No comments

  2. ~OSD~ 2,131 Reputation points
    2020-12-02T13:22:37.2+00:00

    Thanks a lot for your input, appreciated. I think we are very close to solve this... as the example you provided copies the MyFile.txt to ALL Sub-Folders inside the dynamic directory. Means if we have 10 sub-folders, it will copy to all. However, I was looking to copy inside the dynamic folder only (the sub-folders of the Parent folder).

    44397-image.png

    It should be copied to the folders marked green but in this case, it's end-up into sub-directories.

    0 comments No comments

  3. ~OSD~ 2,131 Reputation points
    2020-12-02T15:03:29.717+00:00

    Thanks a Viorel, it's exactly what I was looking for.

    0 comments No comments