我在网络中发送zip文件时遇到问题..我能发送的所有其他格式除了.zip ..
我尝试了很多我不知道如何做到这一点..我在客户端写的代码上传文件,这是微软建议的link
我能够创建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();
请帮帮我......
由于
答案 0 :(得分:1)
主要问题是你正在使用StreamWriter,它是一个TextWriter,专为 text 数据设计,而不是像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);
}