需要帮助:zip文件流 [英] Help required: zip files streaming
问题描述
我有在网络发送zip文件的问题..所有其他格式我能够发送除了.zip ..
i have problem in sending zip file in network.. all other formats i am able to send except .zip..
我试过了很多我不知道做这个..代码我已经写在客户端上传文件,这是由microsoft建议这里是链接
i tried a lot i dont no how to do this.. the code i have written at client side to upload file, this is suggested by microsoft here is the link
我可以创建zip文件,如果我试图打开它说corrupt..size的文件
i am able to create zip file, if i try to open it says corrupted..size of the file also varying lot.
这里是代码
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, / em>数据,而不是像zip文件这样的二进制文件。
The main problem is that you're using a StreamWriter, which is a TextWriter, designed for text data, not binary files like zip files.
此外,还有Jacob提到的问题,以及你没有关闭请求流直到你已经收到响应 - 虽然这不会有什么不同,因为 StreamWriter
会先关闭它。
Additionally there's the problem Jacob mentioned, and also the fact that you're not closing the request stream until after you've received the response - although that won't make any difference because the StreamWriter
will close it first.
这里是固定的代码,更改为使用使用
语句(以避免流打开),更简单的调用文件
类和更有意义的名称(IMO)。
Here's the fixed code, changed to use using
statements (to avoid leaving streams open), a simpler call to the File
class, and more meaningful names (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循环提取到帮助方法:
Note that you can easily extract the while loop into a helper method:
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);
}
}
/ p>
to be used from other places, leaving just:
using (Stream output = req.GetRequestStream())
using (Stream input = File.OpenRead(localFile))
{
CopyStream(input, output);
}
这篇关于需要帮助:zip文件流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!