Home > Net >  How do i set where i file downloads to
How do i set where i file downloads to

Time:11-14

on c# i have created a button to automatically download the SpotifySetup.exe and its all fine but it downloads to a folder at "\bin\Debug\net6.0-windows" but i dont want that i want to set a location to where i want the file to download.

this is the code i have bellow

        private void FileDownloadComplete(object sender, AsyncCompletedEventArgs e)
        {
            MessageBox.Show("Download Completed");
        }

        private void DownloadSpotify_Click(object sender, EventArgs e)
        {
            wc.DownloadFileCompleted  = new AsyncCompletedEventHandler(FileDownloadComplete);
            Uri fileurl = new Uri("https://download.scdn.co/SpotifySetup.exe");
            wc.DownloadFileAsync(fileurl, "SpotifySetup.exe");
        }

i want to set where the file downloads to, i do not want the file to download to the default location.

CodePudding user response:

maybe you can add path to 2nd parameter like "E:\User\Download\SpotifySetup.exe"

CodePudding user response:

You can get the Content stream, and copy it to a FileStream to save the file.

I wrote some sample code which you can use. I haven't tested it, though.

public async Task DownloadToLocation(Uri uri, string downloadPath)
{
    HttpClient httpClient = GetHttpClient();

    if (File.Exists(downloadPath))
    {
        // TODO: Handle file already exists.
    }

    using (var response = await httpClient.GetAsync(uri))
    {
        response.EnsureSuccessStatusCode();

        using (var f = File.OpenWrite(downloadPath))
        {
            await response.Content.CopyToAsync(f);
        }
    }
}
  • Related