我已经得到了尽可能从一个URL放入一个文件流。 但是,事件OpenReadCompleted中的puttin savefiledialog会导致异常,因为savefiledialog需要从用户引发的事件中触发。 把savefiledialog放在OpenReadCompleted里面会给出错误,因为字节数组是空的,尚未处理。 有没有另一种方法来保存文件从uri流而不使用事件?从绝对uri下载文件流到SaveFileDialog
public void SaveAs()
{
WebClient webClient = new WebClient(); //Provides common methods for sending data to and receiving data from a resource identified by a URI.
webClient.OpenReadCompleted += (s, e) =>
{
Stream stream = e.Result; //put the data in a stream
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
bytes = ms.ToArray();
}; //Occurs when an asynchronous resource-read operation is completed.
webClient.OpenReadAsync(new Uri("http://testurl/test.docx"), UriKind.Absolute); //Returns the data from a resource asynchronously, without blocking the calling thread.
try
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "All Files|*.*";
//Show the dialog
bool? dialogResult = dialog.ShowDialog();
if (dialogResult != true) return;
//Get the file stream
using (Stream fs = (Stream)dialog.OpenFile())
{
fs.Write(bytes, 0, bytes.Length);
fs.Close();
//File successfully saved
}
}
catch (Exception ex)
{
//inspect ex.Message
MessageBox.Show(ex.ToString());
}
}
它很完美!为什么我没有想到这一点。可能因为我是新手。非常感谢。 – tutu