[英]Zip file is getting corrupted after uploaded to server using C#
I am trying to upload a zip file to server using C# (Framework 4)
and following is my code. 我正在尝试使用
C# (Framework 4)
将zip文件上传到服务器,以下是我的代码。
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();
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. zip文件上传成功,但是当我尝试从服务器(手动)打开zip文件时,它显示出
Unexpected end of archive
错误。
For file compression I am using Ionic.zip dll
. 对于文件压缩,我使用的是
Ionic.zip dll
。 Before transferring the zip file, I was able to extract successfully. 在传输zip文件之前,我能够成功提取。
Any help appreciated. 任何帮助赞赏。 Thanks.
谢谢。
This is the problem: 这就是问题:
StreamReader sourceStream = new StreamReader(fileToBeUploaded);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
StreamReader
(and any TextReader
) is for text data. StreamReader
(和任何TextReader
)用于文本数据。 A zip file isn't text data. zip文件不是文本数据。
Just use: 只需使用:
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. 另请注意,您应该对所有这些流使用
using
语句,而不是仅调用Close
- 这样即使抛出异常,资源也会被处理掉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.