简体   繁体   中英

How do I download a file given the URL in C#

I am trying to download a file from a URL and I want to have a Popup where I can decide where to save the file on my pc. I know how to save it to a setlocation but that's not what I want.

WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri("URL"), @"d:\location");

So I get that this is how I download it so a set location but I need to be able to save it to a location of choice with the usual popup you normally get when you download anything.

To give more sight into this I have 2 radiobuttonlists in which the user can check what topics he wants then he can choose from a dropdownlist which file he wants to download and then he click on a downloadbutton which should trigger the download of that file.

Use DownloadFileAsync and listen to DownloadFileFinished. First download it to temp file and at event DownloadFileFinished, show popup and ask where to save. Then just copy the file from temp file to the filename from user. -or- Show SaveFileDialog before you start DownloadFileAsync.

Talking about a desktop app you can use SaveFileDialog .

The msdn code example :

    private void button1_Click(object sender, System.EventArgs e)
 {
     Stream myStream ;
     SaveFileDialog saveFileDialog1 = new SaveFileDialog();

     saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"  ;
     saveFileDialog1.FilterIndex = 2 ;
     saveFileDialog1.RestoreDirectory = true ;

     if(saveFileDialog1.ShowDialog() == DialogResult.OK)
     {
         if((myStream = saveFileDialog1.OpenFile()) != null)
         {
             // Code to write the stream goes here.
             myStream.Close();
         }
     }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM