2012-06-20 43 views
0

我正在開發一個Silverlight自定義控件,我使用WebClient將一些XML數據發送到我的服務器。文件上傳後,我需要運行回調函數。所以,問題是我怎麼知道它已經完成上傳文件? 這裏是我寫的代碼:WebClient和回調函數

WebClient wc = new WebClient(); 
wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted); 
Uri uri = new Uri(myUrl); 
wc.OpenWriteAsync(uri, "POST", data); 

... 


private void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e){ 

     if (e.Error == null) 
     { 

      byte[] fileContent = e.UserState as byte[]; 

      Stream outputStream = e.Result; 

      outputStream.Write(fileContent, 0, fileContent.Length); 
      outputStream.Flush(); 
      outputStream.Close();     
     } 

     HtmlPage.Window.Invoke("callBackFunction"); 

    } 

這一切都看起來很不錯給我,但這裏有兩個問題。一個我不確定當文件完成上傳時wc_OpenWriteCompleted實際上正在運行。我如何確認?回調函數,如果文件沒有完成,它不會執行任何操作。這是否是回撥該電話的正確地點?最後,服務器在調用之後迴應一些測試,我怎樣才能將它傳遞給我的回調函數?

回答

0

您可以嘗試創建服務請求。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(SessionConstants.serviceURL, UriKind.Absolute)); 
request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 
request.BeginGetRequestStream(new AsyncCallback(ObjectListRequestReady), request); 

然後發送服務請求到服務器上傳文件。

void ObjectListRequestReady(IAsyncResult asyncResult) 
{ 

    HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest; 
    Stream stream = request.EndGetRequestStream(asyncResult); 

    Deployment.Current.Dispatcher.BeginInvoke(delegate() 
    { 
      SELECTED_NODE = SPSITETextBox.Text; 
      StreamWriter writer = new StreamWriter(stream); 
      writer.WriteLine("pass your data to upload on server"); 
      writer.Flush(); 
      writer.Close(); 
      request.BeginGetResponse(new AsyncCallback(ObjectListResponseReady), request); 

      // ObjectListResponseReady is the callback method called after uploading the data. 
     }); 
} 

從服務中獲取結果。 ObjectListResponseReady是上傳文件後回覆您的回調方法。

void ObjectListResponseReady(IAsyncResult asyncResult) 
{ 
     try 
     { 
      HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest; 
      HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); 

      Deployment.Current.Dispatcher.BeginInvoke(delegate() 
      { 
       Stream responseStream = response.GetResponseStream(); 
       XmlReader xmlReader = XmlReader.Create(responseStream); 
      }); 
      } 

     catch (Exception ex) 
     { 
      Message.ErrorMessage("error: " + ex); 
     } 
}