下载文件后如何制作“另存为”对话框

时间:2019-02-14 02:40:46

标签: c# forms

说明: 因此,我使用以下脚本从Internet上下载文件,并显示进度条和自定义消息框,其中显示了下载的百分比。现在,我已将文件保存到用户%TEMP%路径。并且它使用事件来防止人们再次单击该按钮并开始新的下载。

问题: 我想为用户提供将文件保存到何处的选择,但将其临时路径显示为默认位置。 (就像一个保存文件对话框) 我对编码还很陌生,也不知道从哪里开始。

我尝试过的事情: 我没有尝试任何新代码,但我确实在Google周围搜索并尝试找到解决方案。以下是一些我发现可能有用的网站:

https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-save-files-using-the-savefiledialog-component

https://www.c-sharpcorner.com/UploadFile/mahesh/savefiledialog-in-C-Sharp/

他们解释得很好。但是我不知道如何将其合并到此脚本中。 而且我不想写一个全新的脚本。任何帮助将不胜感激!

private bool _isBusy = false;

private void button1_Click(object sender, EventArgs e)
  => DownloadFile("someurl1", "somefilename1.exe");

private void button2_Click(object sender, EventArgs e)
  => DownloadFile("someurl2", "somefilename2.exe");

private void button3_Click(object sender, EventArgs e)
  => DownloadFile("someurl3", "somefilename3.exe");

private void button4_Click(object sender, EventArgs e)
  => DownloadFile("someurl4", "somefilename4.exe");

private void DownloadFile(string url, string fileName)
{

   if(_isBusy) return;

   _isBusy = true;

   var output = Path.Combine(Path.GetTempPath(), fileName);
   MessageBox.Show($"{fileName} will start downloading from {url}");

   using (WebClient client = new WebClient())
   {

      client.DownloadFileCompleted += (sender, args) =>
                                      {
                                         MessageBox.Show($"{fileName} Complete!");
                                         Process.Start(output);
                                         _isBusy = false;
                                      };

  client.DownloadProgressChanged += (sender, args) => progressBar1.Value = args.ProgressPercentage;
  client.DownloadFileAsync(new Uri(url), output);
   }
}

1 个答案:

答案 0 :(得分:0)

也许有点像?

    private SaveFileDialog save = new SaveFileDialog();

    private void DownloadFile(string url, string fileName)
    {
        if (_isBusy) return;

        save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        save.FileName = fileName;
        if (save.ShowDialog() == DialogResult.OK)
        {
            _isBusy = true;

            var output = save.FileName;
            MessageBox.Show($"{fileName} will start downloading from {url}");

            using (WebClient client = new WebClient())
            {

                client.DownloadFileCompleted += (sender, args) =>
                {
                    MessageBox.Show($"{fileName} Complete!");
                    Process.Start(output);
                    _isBusy = false;
                };

                client.DownloadProgressChanged += (sender, args) => progressBar1.Value = args.ProgressPercentage;
                client.DownloadFileAsync(new Uri(url), output);
            }
        }   
    }