2011-11-22 52 views
5

我已经得到了尽可能从一个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()); 
     } 

} 

回答

7

的办法就是让使用第一打开SaveFileDialog像点击一个按钮一些用户交互的结果。让用户确定下载的保存位置,并且SaveDialog方法返回后,您将手中的SaveFileDialog保留为该实例。您可以使用SaveFileDialogOpenFile方法获取可以抽取结果的流。

public void SaveAs() 
{ 
    SaveFileDialog dialog = new SaveFileDialog(); 
    dialog.Filter = "All Files|*.*"; 

    bool? dialogResult = dialog.ShowDialog(); 

    if (dialogResult != true) return; 

    WebClient webClient = new WebClient(); 
    webClient.OpenReadCompleted += (s, e) => 
    { 
     try 
     {  
      using (Stream fs = (Stream)dialog.OpenFile()) 
      { 
       e.Result.CopyTo(fs); 
       fs.Flush(); 
       fs.Close(); 
      } 

     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
    }; 
    webClient.OpenReadAsync(new Uri("http://testurl/test.docx"), UriKind.Absolute); 
} 

您会注意到,不仅是代码更清洁,简单,但如果用户最终取消SaveFileDialog你没有浪费自己的时间和带宽下载文件。

+0

它很完美!为什么我没有想到这一点。可能因为我是新手。非常感谢。 – tutu

0

我发现从silverlight应用程序下载文件的简单方法。 使用HyperLinkBut​​ton控件。

您也可以使用“TargetName”propery指定目标。

+1

这更适合作为评论。 –