如何使用弹出窗口在c#中下载文件,询问保存文件的位置

时间:2015-02-18 05:13:35

标签: c# asp.net webforms

 WebClient webClient = new WebClient();
 webClient.DownloadFile(pdfFilePath, @"D:\DownloadPastPapers.pdf");

我正在下载直接下载到指定路径的pdf文件但是我想打开一个弹出窗口,询问在哪里保存它(因为所有普通网站在下载时都会显示) 它是一个webfroms asp.net应用程序

3 个答案:

答案 0 :(得分:1)

您可以先弹出SaveFileDialog询问保存路径。

然后在DownloadFile()

中使用此路径
SaveFileDialog saveFileDialog1 = new SaveFileDialog(); 
saveFileDialog1.InitialDirectory =     Convert.ToString(Environment.SpecialFolder.MyDocuments); 
saveFileDialog1.Filter = "Your extension here (*.EXT)|*.ext|All Files (*.*)|*.*" ; 
saveFileDialog1.FilterIndex = 1; 

if(saveFileDialog1.ShowDialog() == DialogResult.OK) 
{ 
    Console.WriteLine(saveFileDialog1.FileName);//Do what you want here

    WebClient webClient = new WebClient();
   webClient.DownloadFile(pdfFilePath, saveFileDialog1.FileName");
} 

答案 1 :(得分:1)

    pdfFilePath = pdfFilePath + "/DownloadPastPapers.pdf";
    Response.Clear();
    Response.ContentType = "application/pdf";
    Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
    Response.TransmitFile(pdfFilePath);
    Response.End(); 

答案 2 :(得分:0)

private string SelectDestinationFile()
{
   var dialog = new SaveFileDialog()
   {
       Title = "Select output file"
       //--Filter can also be defined here
   };

   return dialog.ShowDialog() == true ? dialog.FileName : null;
}

private void DownloadFile(string url)
{
    var filePath = SelectDestinationFile();

    if(string.IsNullOrWhiteSpace(filePath))
       throw new InvalidOperationException("invalid file path");

    using (var client = new WebClient())
       client.DownloadFile(url, filePath);
}

我希望它可以帮到你。

P.S。这适用于WPF应用。