使用C#上传到服务器后,Zip文件越来越损坏 [英] Zip file is getting corrupted after uploaded to server using C#
问题描述
我试图上传一个zip使用 C#(Framework 4中)
键,下面是我的代码。文件服务器
I am trying to upload a zip file to server using C# (Framework 4)
and following is my code.
string ftpUrl = ConfigurationManager.AppSettings["ftpAddress"];
string ftpUsername = ConfigurationManager.AppSettings["ftpUsername"];
string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"];
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl + "Transactions.zip");
request.Proxy = new WebProxy(); //-----The requested FTP command is not supported when using HTTP proxy.
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
StreamReader sourceStream = new StreamReader(fileToBeUploaded);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
该zip文件上传成功,但是当我试图从服务器打开压缩文件(手动) ,它向我展示了档案意外结束
错误。结果
。对于我使用的文件压缩 Ionic.zip DLL
。传输压缩文件之前,我是能够成功地提取。
The zip file is uploaded successfully, but when I tried to open the zip file from server(manually), it showed me Unexpected end of archive
error.
For file compression I am using Ionic.zip dll
. Before transferring the zip file, I was able to extract successfully.
任何帮助表示赞赏。谢谢。
Any help appreciated. Thanks.
推荐答案
这就是问题所在:
StreamReader sourceStream = new StreamReader(fileToBeUploaded);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
的StreamReader
(和任何的TextReader
)现在的文本的数据。 。一个zip文件是不是文本数据
StreamReader
(and any TextReader
) is for text data. A zip file isn't text data.
只需使用:
byte[] fileContents = File.ReadAllBytes(fileToBeUploaded);
你不把二进制数据作为文本方式,所以它不应该遭到损坏。
That way you're not treating binary data as text, so it shouldn't get corrupted.
或者,不要将其全部加载到内存中单独 - 只是流中的数据:
Or alternatively, don't load it all into memory separately - just stream the data:
using (var requestStream = request.GetRequestStream())
{
using (var input = File.OpenRead(fileToBeUploaded))
{
input.CopyTo(requestStream);
}
}
另外请注意,你应该使用使用
语句对所有这些流,而不是只调用关闭
- 这样即使有异常抛出的资源将被全部销毁。
Also note that you should be using using
statements for all of these streams, rather than just calling Close
- that way the resources will be disposed even if an exception is thrown.
这篇关于使用C#上传到服务器后,Zip文件越来越损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!