需要帮助:zip文件流

我在网络中发送zip文件有问题..我能发送的所有其他格式除了.zip ..

我尝试了很多我不知道如何做到这一点..我在客户端写的代码上传文件,这是微软建议这里的链接

我能够创建zip文件,如果我尝试打开它说corrupted..size的文件也变化很多。

这是代码

public void UploadFile(string localFile, string uploadUrl) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl); req.Method = "PUT"; req.AllowWriteStreamBuffering = true; // Retrieve request stream and wrap in StreamWriter Stream reqStream = req.GetRequestStream(); StreamWriter wrtr = new StreamWriter(reqStream); // Open the local file Stream Stream = File.Open(localFile, FileMode.Open); // loop through the local file reading each line // and writing to the request stream buffer byte[] buff = new byte[1024]; int bytesRead; while ((bytesRead = Stream.Read(buff, 0,1024)) > 0) { wrtr.Write(buff); } Stream.Close(); wrtr.Close(); try { req.GetResponse(); } catch(Exception ee) { } reqStream.Close(); 

请帮我…

谢谢

主要问题是你正在使用StreamWriter,它是一个TextWriter,专为文本数据而设计,而不是像zip文件这样的二进制文件。

另外还有雅各布提到的问题,以及你在收到回复之前没有关闭请求流的事实 – 虽然这不会有任何区别,因为StreamWriter会先关闭它。

这是固定代码,更改为使用using语句(以避免使流打开),更简单的调用File类,以及更有意义的名称(IMO)。

 using (Stream output = req.GetRequestStream()) using (Stream input = File.OpenRead(localFile)) { // loop through the local file reading each line // and writing to the request stream buffer byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = input.Read(buffer, 0, 1024)) > 0) { output.Write(buffer, 0, bytesRead); } } 

请注意,您可以轻松地将while循环提取到辅助方法中:

 public static void CopyStream(Stream input, Stream output) { // loop through the local file reading each line // and writing to the request stream buffer byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = input.Read(buffer, 0, 1024)) > 0) { output.Write(buffer, 0, bytesRead); } } 

从其他地方使用,只留下:

 using (Stream output = req.GetRequestStream()) using (Stream input = File.OpenRead(localFile)) { CopyStream(input, output); }