Search code examples
vb.netfolderbrowserdialog

FolderBrowserDialog not saving files where selected


I'm trying to make a YouTube downloader for fun. I saw some tutorials and I finished it, but when I download it and select the path if I choose "Desktop", it doesn't download but if I choose a folder on the desktop, it downloads it but not in the folder, in the desktop. I tried to fix it but nothing worked.

How can I resolve that?

Here's my code:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles download.Click
    If url.Text <> "" Then
        If FolderBrowserDialog1.ShowDialog = DialogResult.OK Then
            stato.Text = "Downloading"
            Dim video = YouTube.Default.GetVideo(url.Text)
            FolderBrowserDialog1.RootFolder = Environment.SpecialFolder.DesktopDirectory
            File.WriteAllBytes(FolderBrowserDialog1.SelectedPath & video.FullName, video.GetBytes())
            stato.Text = "Done!"
        End If
    Else
        MsgBox("Enter an URL!")
    End If
End Sub

Solution

  • If the SelectedPath doesn't have the file, go one level up because the file is most likely there. Here's your fix so it goes to the right folder:

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles download.Click
        If url.Text <> "" Then
            FolderBrowserDialog1.RootFolder = Environment.SpecialFolder.DesktopDirectory
            If FolderBrowserDialog1.ShowDialog = DialogResult.OK Then
                stato.Text = "Downloading"
                Dim video = YouTube.Default.GetVideo(url.Text)
                File.WriteAllBytes(System.IO.Path.Combine(FolderBrowserDialog1.SelectedPath, video.FullName), video.GetBytes())
                stato.Text = "Done!"
            End If
        Else
            MsgBox("Enter an URL!")
        End If
    End Sub
    

    Note that I'd recommend you use a backgroundworker component for the download instead. Also, ideally, you should be saving the bytes to the file in the background worker as you save, so the bytes don't all go into memory, but directly into your file instead. Those recommendations are outside the scope of your question though.