Tôi đã nhận được quá xa khi đưa tệp vào luồng từ url. Tuy nhiên puttin savefiledialog bên trong sự kiện OpenReadCompleted đưa ra một ngoại lệ vì savefiledialog cần phải được kích hoạt từ một sự kiện iniated của người dùng. Đặt savefiledialog NOT bên trong OpenReadCompleted đưa ra một lỗi vì mảng byte trống, chưa được xử lý. Có cách nào khác để lưu tệp để phát trực tiếp từ một thiết bị không cần sử dụng sự kiện không?tải xuống tệp từ uri tuyệt đối để phát trực tuyến tới 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());
}
}
Nó hoạt động hoàn hảo! Tại sao tôi không nghĩ về điều đó. Có lẽ vì tôi là một người mới. Cảm ơn rất nhiều. – tutu