首页 > 解决方案 > 下载文件后如何制作文件另存为对话框

问题描述

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

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

我尝试了什么: 我没有尝试任何新代码,但我确实绕过谷歌并尝试找到解决方案。以下是我发现可能有用的一些网站:

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);
   }
}

标签: c#forms

解决方案


也许像什么?

    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);
            }
        }   
    }

推荐阅读