Search code examples
vb.netdesktopsubdirectorycreate-directory

Sub-folder inside folder on desktop


I would like to create a sub-folder Y in a folder X which I already created on my desktop (see below).

Dim myFolder As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "X")
If (Not (System.IO.Directory.Exists(myFolder))) Then
     System.IO.Directory.CreateDirectory(myFolder)
End If

I think I should use: System.IO.Directory.CreateDirectory(path), but what will be the path?

I don't know the syntax to use to create a folder "Y" inside the folder "X".

Maybe, path = My.Computer.FileSystem.SpecialDirectories.Desktop & "\X\", but nothing is created.


Solution

  • It may be easier than you think: Directory.CreateDirectory will create all the directories required, so you could use:

    Dim myFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "X", "Y")
    Directory.CreateDirectory(myFolder)
    

    Or if you are using the .NET Framework 1.1 which only allows two items in Path.Combine:

    Dim rootFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "X")
    Dim myFolder = Path.Combine(rootFolder, "Y")
    Directory.CreateDirectory(myFolder)
    

    It is always worth looking at the documentation as it often includes useful comments about some common uses for a method.