使用C#上传到服务器后,Zip文件已损坏
我正在尝试使用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();
zip文件上传成功,但当我尝试从服务器(手动)打开zip文件时,它显示出Unexpected end of archive
错误。
对于文件压缩,我使用的是Ionic.zip dll
。 在传输zip文件之前,我能够成功提取。
任何帮助赞赏。 谢谢。
这就是问题:
StreamReader sourceStream = new StreamReader(fileToBeUploaded); byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
StreamReader
(和任何TextReader
)用于文本数据。 zip文件不是文本数据。
只需使用:
byte[] fileContents = File.ReadAllBytes(fileToBeUploaded);
这样你就不会将二进制数据视为文本,因此它不应该被破坏。
或者,不要单独将它们全部加载到内存中 – 只是流式传输数据:
using (var requestStream = request.GetRequestStream()) { using (var input = File.OpenRead(fileToBeUploaded)) { input.CopyTo(requestStream); } }
另请注意,您应该对所有这些流使用using
语句,而不是仅调用Close
– 这样即使抛出exception,资源也会被处理掉。