C# 需要帮助:zip文件流
我在网络中发送zip文件时遇到问题。。除了.zip以外,我可以发送的所有其他格式 我试了很多我不知道怎么做。。我在客户端写的上传文件的代码,这是微软建议的 我能够创建zip文件,若我试图打开它,它会显示损坏..文件的大小也会变化很多 这是代码C# 需要帮助:zip文件流,c#,.net,windows-mobile,client-server,C#,.net,Windows Mobile,Client Server,我在网络中发送zip文件时遇到问题。。除了.zip以外,我可以发送的所有其他格式 我试了很多我不知道怎么做。。我在客户端写的上传文件的代码,这是微软建议的 我能够创建zip文件,若我试图打开它,它会显示损坏..文件的大小也会变化很多 这是代码 public void UploadFile(string localFile, string uploadUrl) { HttpWebRequest req = (HttpWebRequest)WebRequest.Crea
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,这是一种文本编写器,专为文本数据而设计,而不是像zip文件这样的二进制文件 此外,还有Jacob提到的问题,还有一个事实,即在收到响应之前,您不会关闭请求流-尽管这不会有任何区别,因为StreamWriter将首先关闭它 下面是固定的代码,改为使用
和语句(以避免流处于打开状态),对文件
类的简单调用,以及更有意义的名称(IMO)
请注意,您可以轻松地将while循环提取到helper方法中:
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);
}
using (Stream output = req.GetRequestStream())
using (Stream input = File.OpenRead(localFile))
{
CopyStream(input, output);
}