我正在使用下面的代码将zip文件上传到我的ftp服务器:
string zipPath = @"d:\files\start.zip";
string ftpPath = ("ftp://######/start.zip");
WebRequest request = WebRequest.Create(ftpPath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("######", "######");
StreamReader sourceStream = new StreamReader(zipPath);
byte[] fileContents = Encoding.Unicode.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse makeFileUploadResponse = (FtpWebResponse)request.GetResponse();
}
catch
{
MessageBox.Show("ftp failed!");
}
我的zip存档绝对有效(我可以打开它并解压缩)但是当我下载上传的zip文件时,我收到存档损坏的错误。
更新1 :我的源代码来自MSDN文章:How to: Upload Files with FTP
答案 0 :(得分:1)
您应该将请求转发给FtpWebRequest
(如MSDN示例中所示)
然后将请求指定为二进制(您正在上传二进制文件,而不是文本)。
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("aa");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
答案 1 :(得分:0)
我不能说问题是什么,但我可以提供替代解决方案。您可以使用WebClient代替WebRequest
string zipPath = @"d:\files\start.zip";
string ftpPath = ("ftp://######/start.zip");
WebClient ftpClient = new WebClient();
ftpClient.Credentials = new NetworkCredential("####", "######");
try{
ftpClient.UploadFile(ftpPath, WebRequestMethods.Ftp.AppendFile, zipPath);
}
catch(WebException ex){
MessageBox.Show("ftp failed");
}