I have two methods (C# 4.8): one that uploads a file to a server directory using FTP, and one that downloads a file from a server using FTP. Each of these work fine independently. However, when I call the UploadFile(...)
method followed by the Download method, an exception is thrown on the FtpWebRequest.Create(...)
method in the DownloadFile(...)
method.
I can call DownloadFile(...)
successively without problems.
Am I missing something, perhaps to close the connection?
The exception is:
Message: "The remote server returned an error: 226-File successfully transferred\r\n226 1.707 seconds (measured here), 4.59 Mbytes per second\r\n."
InnerException: null
Status: ProtocolError
My code is:
public void UploadFile(FileInfo SourceFile, string Domain, string TargetFileName, string Username, string Password)
{
FtpWebRequest _FTPRequest = (FtpWebRequest)WebRequest.Create(Domain + TargetFileName);
_FTPRequest.Credentials = new NetworkCredential(Username, Password);
_FTPRequest.Method = WebRequestMethods.Ftp.UploadFile;
_FTPRequest.UseBinary = true;
_FTPRequest.KeepAlive = false;
_FTPRequest.UsePassive = true;
using (FileStream fileStream = SourceFile.OpenRead())
using (FtpWebResponse response = (FtpWebResponse)_FTPRequest.GetResponse())
using (Stream ftpStream = _FTPRequest.GetRequestStream())
{
byte[] buffer = new byte[1024];
int iRead;
while ((iRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
ftpStream.Write(buffer, 0, iRead);
}
}
public void DownloadFile(ref byte[] TargetArray, string Domain, string SourceFileName, string Username, string Password)
{
FtpWebRequest _FTPRequest = (FtpWebRequest)WebRequest.Create(Domain + SourceFileName); // exception is thrown here //
_FTPRequest.Credentials = new NetworkCredential(Username, Password);
_FTPRequest.Method = WebRequestMethods.Ftp.DownloadFile;
_FTPRequest.UseBinary = true;
_FTPRequest.KeepAlive = false;
_FTPRequest.UsePassive = true;
using (FtpWebResponse response = (FtpWebResponse)_FTPRequest.GetResponse())
using (Stream ftpStream = response.GetResponseStream())
{
byte[] buffer = new byte[1024];
int totalRead = 0;
int iRead;
while ((iRead = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
if (buffer.Length > iRead) Array.Resize<byte>(ref buffer, iRead);
Array.Resize<byte>(ref TargetArray, TargetArray.Length + iRead);
buffer.CopyTo(TargetArray, totalRead);
totalRead += iRead;
}
}
}