从绝对uri下载文件到streamFileDialog

tut*_*utu 5 silverlight uri absolute savefiledialog silverlight-4.0

我已经将文件放入来自URL的流中了.但是事件OpenReadCompleted中的puttin savefiledialog给出了一个例外,因为需要从用户推断的事件中触发savefiledialog.将savefiledialog NOT置于OpenReadCompleted内会产生错误,因为bytes数组为空,尚未处理.是否有另一种方法可以保存文件以便在不使用事件的情况下从uri流式传输?

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

}
Run Code Online (Sandbox Code Playgroud)

Ant*_*nes 7

采取的方法是首先 打开SaveFileDialog一些用户交互的结果,如按钮单击.让用户确定保存下载的位置并且SaveDialog方法已经返回,您可以保留该实例SaveFileDialog.

然后,OpenReadCompleted您可以调用下载,然后您可以使用该SaveFileDialog OpenFile方法获取可以为其提供结果的流.

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); 
} 
Run Code Online (Sandbox Code Playgroud)

您会注意到,不仅代码更清晰,更简单,而且如果用户最终取消SaveFileDialog,您还没有浪费时间或带宽下载文件.