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