Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  1. FTP into an account
  2. Detect if the connection was refused
  3. Obtain a text file
  4. Delete the text file

What's the easiest way to do this?

like image 974
Jason Avatar asked Mar 04 '09 20:03

Jason


1 Answers

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", "[email protected]");
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.)

like image 93
bzlm Avatar answered Sep 28 '22 19:09

bzlm