2014-05-14 88 views
0

您好我正在使用GZipStream壓縮一個XML文件,並將其上傳到一個web服務,這將返回一個gzipstream,我必須下載。我在C#中使用了使用WebClient的以下方法,但它引發異常「WebClient不支持併發I/O操作」。上傳文件到webservice和下載文件它返回

byte[] data = Encoding.ASCII.GetBytes(xml); 
        MemoryStream input = new MemoryStream(data); 
        MemoryStream output = new MemoryStream(); 
        GZipStream zip = new GZipStream(output, CompressionMode.Compress); 
        input.WriteTo(zip); 
        byte[] gzipStream = output.ToArray(); 
        //Constructing Request 
        var postClient = new WebClient(); 
        Uri uri = new Uri(url); 
        postClient.UploadDataAsync(uri, gzipStream); 
        var resStream = new GZipStream(postClient.OpenRead(url),CompressionMode.Decompress); 
       var reader = new StreamReader(resStream); 
       var textResponse = reader.ReadToEnd(); 
       return textResponse; 

請幫助我。

+2

魔法門與UploadDataAsync()問題?嘗試UploadData() – malkam

+0

您確定需要對執行POST的同一個URI發出GET請求嗎?或者您是否想要閱讀POST響應? – CodeCaster

+0

將gzip文件發佈到Webservice後,服務將處理該文件並返回另一個gzip文件,作爲我已下載的響應。 – user3611366

回答

0

在這種情況下,你不應該使用異步

byte[] data = Encoding.ASCII.GetBytes(xml); 
       MemoryStream input = new MemoryStream(data); 
       MemoryStream output = new MemoryStream(); 
       GZipStream zip = new GZipStream(output, CompressionMode.Compress); 
       input.WriteTo(zip); 
       byte[] gzipStream = output.ToArray(); 
       //Constructing Request 
       var postClient = new WebClient(); 
       Uri uri = new Uri(url); 
       postClient.UploadData(uri, gzipStream); 
       var resStream = new GZipStream(postClient.OpenRead(url),CompressionMode.Decompress); 
      var reader = new StreamReader(resStream); 
      var textResponse = reader.ReadToEnd(); 
      return textResponse; 

還是應該等待異步操作(如果你的方法是異步):

byte[] data = Encoding.ASCII.GetBytes(xml); 
       MemoryStream input = new MemoryStream(data); 
       MemoryStream output = new MemoryStream(); 
       GZipStream zip = new GZipStream(output, CompressionMode.Compress); 
       input.WriteTo(zip); 
       byte[] gzipStream = output.ToArray(); 
       //Constructing Request 
       var postClient = new WebClient(); 
       Uri uri = new Uri(url); 
       await postClient.UploadDataAsync(uri, gzipStream); 
       var resStream = new GZipStream(postClient.OpenRead(url),CompressionMode.Decompress); 
      var reader = new StreamReader(resStream); 
      var textResponse = reader.ReadToEnd(); 
      return textResponse;