-1

I would like to know how to download a file from a url into your downloads folder. I already tried doing this:

private void guna2Button1_Click(object sender, EventArgs e)
{
        using (var client = new WebClient())
        {
            client.DownloadFile("https://test.com/hello.txt", "hello.txt");
        }
    }

When I actually put in a valid url and file, it would go where my project would be located. I would like it to be saved in my downloads folder, how would I do this?

filths
  • 1
  • 1
  • did you look where you _project_ is, or where the _compiled binary_ is? also: to save it in your downloads folder - have you tried _providing the full path to your downloads folder_? – Franz Gleichmann Feb 06 '22 at 19:05
  • 1
    Does this answer your question? [How to programmatically derive Windows Downloads folder "%USERPROFILE%/Downloads"?](https://stackoverflow.com/questions/3795023/how-to-programmatically-derive-windows-downloads-folder-userprofile-downloads) – Hunter Tran Feb 06 '22 at 19:06

1 Answers1

0

There are several solutions:

  1. If you just need to work on your computer and your session, replace your second parameter "hello.txt" by something like that: @"c:\users\yourname\downloads\hello.txt", where 'yourname' is the folder corresponding to your session, and @ indicates \ won't escape chars in the following string so this string would be verbatim. But this will work only on your computer and your session, of course.
  2. Use The NuGet package Syroot.Windows.IO.KnownFolders: right-clic on References on the solutions explorer and add this nugget package. Then, do this:

Add the following at the beginning:

using Syroot.Windows.IO;
using System.IO;

Modify your method:

 private void guna2Button1_Click(object sender, EventArgs e)
 {
     using (var client = new WebClient())
     {
         string downloadFolder = KnownFolders.Downloads.Path;
         string destFile = Path.Combine(downloadFolder, "hello.txt");
         client.DownloadFile("https://test.com/hello.txt", destFile);
     }
 }
Fredy
  • 532
  • 3
  • 11