需要帮助: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); }
- 在C#中使用相同的COM接口在2个不同的库之间进行转换
- 通缉:DateTime.TryNew(年,月,日)或DateTime.IsValidDate(年,月,日)
- 十进制ToString格式,至少给出1位数,没有上限
- 对于需要引用其他类的类,C#中的优秀设计模式是什么?
- 为什么我需要使用get和set?
- 用于x64应用程序的Microsoft.ACE.OLEDB.12.0驱动程序 – 如何使其与x86 MS Office一起安装?
- 使用ReaderWriterLock的真正缺点是什么?
- 数组中的不同类型,如何在将它们从数组中取出时知道将它们转换为什么?
- entity .ToList()生成一个System.OutOfMemoryException