FTP through FTP proxy - c#

I am trying to download a file using FTP through a FTP proxy (on my side).
This is script I am trying to implement in C#:
On Commandline:
ftp -i -s:get.ini CORPORATE_PROXY.com
-----------get.ini------------
CORPORATE_PROXY_USER#CLIENT_FTP.com abc/user_name
CORPORATE_PROXY_PASSWORD
user_name_password
cd pub/linux/knoppix
get packages.txt
bye
-----------get.ini------------
abc/user_name is my user name who was granted by permissions to FTP through my corporate proxy.
I want to implement above script in C#, but after playing with many types of code found on Internet I cannot do that.
FtpWebRequest request = FtpWebRequest.Create(new Uri(#"ftp://" + CORPORATE_PROXY.com + #"/" + Path.GetFileName(fileToUpload))) as FtpWebRequest;
request.UseBinary = true;
request.KeepAlive = false;
request.Method = WebRequestMethods.Ftp.UploadFile;
if (!string.IsNullOrEmpty(CORPORATE_PROXY_USER) && !string.IsNullOrEmpty(CORPORATE_PROXY_PASSWORD ))
request.Credentials = new NetworkCredential(CORPORATE_PROXY_USER, CORPORATE_PROXY_PASSWORD );
//Get physical file
FileInfo fi = new FileInfo(fileToUpload);
Byte[] contents = new Byte[fi.Length];
//Read file
FileStream fs = fi.OpenRead();
fs.Read(contents, 0, Convert.ToInt32(fi.Length));
fs.Close();
request.Proxy = new WebProxy("CLIENT_FTP.com");
request.Proxy.Credentials = new NetworkCredential(abc/user_name, user_name_password);
//Write file contents to FTP server
Stream rs = request.GetRequestStream();
rs.Write(contents, 0, Convert.ToInt32(fi.Length));
rs.Close();
FtpWebResponse response = request.GetResponse() as FtpWebResponse;
string statusDescription = response.StatusDescription;
response.Close();
return statusDescription;
The main problem is that for the proxy I am using WebProxy, while I suspect I should use FTPProxy - which I cannot find anythere? Any ideas which direction should I go, or maybe WebProxy is fine?

In the past I have used Indy Project to get through FTP proxies.

Try using WebRequest instead of FtpWebRequest in your code example.
By doing so, the connection from client to proxy can be HTTP whereas the connection from proxy to destination server is FTP. The proxy will handle the protocol translation, this technique is referred to as FTP over HTTP.
It is also possible to use a native FTP Proxy where client to proxy and proxy to server connections are FTP. Make sure your proxy supports this.
The proxy offers a separate proxy port to serve native FTP proxy connections.

Related

How to continue or resume FTP upload after interruption of internet

I am using below code (C# .NET 3.5) to upload a file:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://someweb.mn/altanzulpharm/file12.zip");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.KeepAlive = true;
request.UseBinary = true;
request.Credentials = new NetworkCredential(username, password);
FileStream fs = File.OpenRead(FilePath);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = request.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
But the upload breaks when internet interrupted. Interruption occurs for a very small amount of time, almost a millisecond. But uploading breaks forever!
Is it possible to continue or resume uploading after interruption of internet?
I don't believe FtpWebRequest supports re-connection after losing connection. You can resume upload from given position if server supports it (this support is not required and presumably less common that retry for download).
You'll need to set FtpWebRequet.ContentOffset upload. Part of sample from the article:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.ContentOffset = offset;
Internal details of restore in FTP protocol itself - RFC959: 3.5 - Error recovery and restart. Question showing retry code for download - Downloading from FTP with c#, can't retry when fail
The only way to resume transfer after a connection is interrupted with FtpWebRequest, is to reconnect and start writing to the end of the file.
For that use FtpWebRequest.ContentOffset.
A related question for upload with full code (although for C#):
How to download FTP files with automatic resume in case of disconnect
Or use an FTP library that can resume the transfer automatically.
For example WinSCP .NET assembly does. With it, a resumable upload is as trivial as:
// Setup session options
var sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "ftp.example.com",
UserName = "user",
Password = "mypassword"
};
using (var session = new Session())
{
// Connect
session.Open(sessionOptions);
// Resumable upload
session.PutFileToDirectory(#"C:\path\file.zip", "/home/user");
}
(I'm the author of WinSCP)

Download file from secure FTP via REST

I'm trying to get my head around how to download a file from a secure FTP server from my AngularJS application using REST.
Thing is, that for security reasons, I can't just append an iframe or set window.location to ftp://myip:81/myfolder/myfile.pdf, so I have to find a way to trigger the download without this. My initial thought was to create a Generic handler which takes the filename and the folder name as parameters and then serve the file to the user through the context.Response somehow.
What I have so far is this:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path);
request.UsePassive = false;
request.Credentials = new NetworkCredential(ftpHelper.Username, ftpHelper.Password);
request.Method = WebRequestMethods.File.DownloadFile;
using (var response = (FtpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
// stuck here ...
}
}
request.Abort();
I've got a feeling that this isn't possible, though ;-) Can anyone confirm/disprove? And if it can be done, I'd love a small example/hint on this :-)
Thanks!

FTP Connection Failing "Unable to connect to the remote server"

I am trying to connect to an FTP server to upload a file. I am getting the "
Unable to connect" error. If I use command line and open an FTP connection, I am able to connect. Not sure why I get error when connecting programatically. Any help will surely be appreciated.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://1.23.84.2");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("user","password");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(path);
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();
So after a few hours of trouble shooting, It was McAfee blocking the ftp port. had to temporarily disable the services on a local machine.
I think the FtpWebReqest needs to point to the target path, not just the server's address, like the following:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://1.23.84.2/myFile.zip");
The correct usage for FTP uploads in context of FtpWebRequest can be found here.

Transfering a file using ftp from one server to another in different location

I have a requirement of transferring a document file (.txt, .xls, .doc, .bmp, .jpg etc) from one server to another server. Both servers are at different locations. My main application is running on second server. And I have to deploy this functionality on the first server from where the files in any fixed folder (say D:\documents) will be transferred to second server periodically at any timer event.
I am using a code like as follows
WebClient wc = new WebClient();
wc.UploadFile("ftp://1.23.153.248//d://ftp.bmp",
#"C:\Documents and Settings\varun\Desktop\ftp.bmp");
I am getting the error as
unable to connect to remote server
or
sometime underlying connection was closed
Could you tell me what's wrong.
The URI of your FTP location seems to be off: you shouldn't have to double all the forward slashes, and I don't think drive letters are supported.
If you do:
WebClient wc = new WebClient();
wc.UploadFile("ftp://1.23.153.248/ftp.bmp",
#"C:\Documents and Settings\varun\Desktop\ftp.bmp");
The file will be sent to the directory set as the FTP location for the anonymous user. If you configure the FTP service on 1.23.153.248 so that location is D:\, everything should work as planned.
Is your ftp public? if no you should define credentials like this
wc.Credentials = new NetworkCredential ("username","password");
before sending file, and try to remove d: from ftp path. ftp clients don't have to know where on server files should be saved... shortly try this
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential ("username","password");
wc.UploadFile("ftp://1.23.153.248/ftp.bmp", #"C:\Documents and Settings\varun\Desktop\ftp.bmp");
There are also classes created specially for ftp request in .net, here is sample from MSDN
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("testfile.txt");
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();

Using .NET 2.0, how do I FTP to a server, get a file, and delete the file?

Does .NET (C#) have built in libraries for FTP? I don't need anything crazy... very simple.
I need to:
FTP into an account
Detect if the connection was refused
Obtain a text file
Delete the text file
What's the easiest way to do this?
Use the FtpWebRequest class, or the plain old WebClient class.
FTP into an account and retrieve a file:
WebClient request = new WebClient();
request.Credentials =
new NetworkCredential("anonymous", "janeDoe#contoso.com");
try
{
// serverUri here uses the FTP scheme ("ftp://").
byte[] newFileData = request.DownloadData(serverUri.ToString());
string fileString = Encoding.UTF8.GetString(newFileData);
}
catch (WebException ex)
{
// Detect and handle login failures etc here
}
Delete the file:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Delete status: {0}", response.StatusDescription);
response.Close();
(Code examples are from MSDN.)
This article implements a GUI for an FTP client using .NET 2.0 and has full source with examples.
Sample code includes connection, download and upload as well as good comments and explanations.
Just use the FtpWebRequest class. It already handles all the things you require.
Use System.Net.FtpWebRequest/FtpWebResponse
Use edtFTPnet, a free, open source .NET FTP library that will do everything you need.

Categories

Resources