从网上下载文件并使用保存文件对话框保存?

4

我该如何下载文件并保存到想要的位置?我正在使用Windows Form和Web应用程序。

我知道可以使用以下代码下载文件:

WebClient wClient = new WebClient();
wClient.DownloadFile("WebLinkHere", @"C:\File.txt");

但我想要一个像按下CTRL+S时出现的保存框。


1
你是在使用WinForms\WPF吗?这是一个Web应用程序吗?如果能提供一些完整的场景描述会更好。 - Ilya Ivanov
我正在使用 Windows Form,是的,Web 应用程序! - user2944342
2个回答

5
你可以使用SaveFileDialog类。示例:
var dialog = new SaveFileDialog();
dialog.Filter = "Archive (*.rar)|*.rar";

var result = dialog.ShowDialog(); //shows save file dialog
if(result == DialogResult.OK)
{
    Console.WriteLine ("writing to: " + dialog.FileName); //prints the file to save

    var wClient = new WebClient();
    wClient.DownloadFile("WebLinkHere", dialog.FileName);
}

下一个对话框将显示,如果您搜索下一个文件夹 输入图像描述
应用程序将打印:
writing to: C:\Temp\archiveName.rar

如果我只想将它保存为.rar格式,该怎么办? - user2944342
刚刚完成了。感谢帮助! - user2944342

2

这将有效地打开文件下载弹窗。

String FileName = "FileName.xls";
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", FileName));
            Response.ContentType = "application/ms-excel";
            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
            Response.Write(stringWriter.ToString());
            Response.End();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接