I have two methods:
- Uploads files to the FTP Server
- Downloads Files from the Server.
Everything works perfectly with text or xml files. But when I'm trying to upload and then download an archive or an image I get the "windows cannot open the folder. the compressed zip file is invalid" error for the archives and almost the same for the images. What may be the problem?
Here is the listing of my methods:
Upload:
private string Upload(string Login, string Password, string FilePath, string FileName, string uuid, string FTPDir)
{
string CreateDirectory = CreateFTPDirectory(Login, Password, uuid, FTPDir);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(@"ftp://" + FTPDir + uuid + "/" + FileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
StreamReader sourceStream = new StreamReader(FilePath + FileName);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
using (Stream S = request.GetRequestStream())
{
S.Write(fileContents, 0, fileContents.Length);
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
return response.StatusDescription;
}
Download:
private string Download(string Login, string Password, string FileName, string uuid, string FTPDir, string Destination)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + FTPDir + uuid + "/" + FileName);
request.UseBinary = true;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(Login, Password);
byte[] buffer = new byte[1024];
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var fs = new FileStream(Destination, FileMode.OpenOrCreate))
{
int readCount = stream.Read(buffer, 0, 1024);
while (readCount > 0)
{
fs.Write(buffer, 0, readCount);
readCount = stream.Read(buffer, 0, 1024);
}
}
return response.StatusDescription;
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…