将文件上传到webservice并下载它返回的文件

时间:2014-05-14 11:52:21

标签: c# webclient

您好我正在使用GZipStream压缩xml文件并将其上传到webservice,这将返回我必须下载的gzipstream。我在C#中使用了以下使用WebClient的方法但它抛出了异常" WebClient不支持并发I / O操作"。

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;

请帮助我。

1 个答案:

答案 0 :(得分:0)

在这种情况下,您不应该使用 async

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;

或者您应该等待 异步操作(如果您的方法是 async ):

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;