2011-11-22 13 views
5

URLからストリームにファイルを入れている限りです。 OpenReadCompletedイベント内にputtin savefiledialogを置くと、ユーザーのiniatedイベントからsavefiledialogを起動する必要があるため、例外が発生します。 OpenReadCompleted内にsavefiledialogを置かないと、bytes配列がまだ処理されていないため、エラーが発生します。 イベントを使用せずにuriからファイルを保存する別の方法はありますか?取るに絶対URLからファイルをダウンロードして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のままになります。

ダウンロードを呼び出すと、OpenReadCompletedでは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

これはコメントとして適しています。 –

関連する問題