I'm trying to write a C# program to upload a file to an FTP passing through a Proxy.
Here's the code I wrote:
public new bool Upload(string localFilePath, string pathUpload)
{
Stream FStream = null;
bool retval = false;
FileStream FlStream;
try
{
FtpWebRequest FtpRequest =
(FtpWebRequest) FtpWebRequest.Create(Uri + pathUpload);
FtpRequest.Credentials = new NetworkCredential(User, Password);
if (ProxyAddress != "" && ProxyAddress != null)
{
WebProxy ftpProxy = new WebProxy();
ftpProxy.Address = new System.Uri(ProxyAddress);
ftpProxy.Credentials =
new System.Net.NetworkCredential(ProxyUserId, ProxyPassword);
FtpRequest.Proxy = ftpProxy;
}
FtpRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
FStream = FtpRequest.GetRequestStream();
FileStream fs = File.OpenRead(localFilePath);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
FStream.Write(buffer, 0, buffer.Length);
FStream.Close();
FStream.Dispose();
return retval = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.ToString());
return false;
}
}
If I pass the proxy address it says that the FTP command is not supported when using an HTTP Proxy.
I already tried forcing FtpRequest.Proxy = null
as suggested elsewhere (for example http://www.codeproject.com/Questions/332730/FTP-proxy-problem-in-Csharp-application) but it gives me the Exception "Unable to connect to the remote server".
I also tried using the WebClient
class instead of FtpWebRequest
but it gives me the same problems.
Thanks in advance for your help.
The
FtpWebRequest
does not support an HTTP proxy for some operations, including file upload. It's clearly documented on MSDN:The comment on CodeProject is simply nonsense. You cannot believe everything that you find on the Internet.
The
WebClient
usesFtpWebRequest
internally, so you cannot use it either.There's no way to upload a file to FTP over an HTTP proxy with the standard .NET framework libraries.
You have to use a 3rd party FTP library.
For example with WinSCP .NET assembly, you can use:
For the options for
SessionOptions.AddRawSettings
, see raw settings.(I'm the author of WinSCP)