Jason
Jason

Reputation: 17089

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?

Upvotes: 6

Views: 2433

Answers (5)

Bruce Blackshaw
Bruce Blackshaw

Reputation: 1006

Use edtFTPnet, a free, open source .NET FTP library that will do everything you need.

Upvotes: 0

bzlm
bzlm

Reputation: 9727

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.)

Upvotes: 7

Alex Fort
Alex Fort

Reputation: 18821

Just use the FtpWebRequest class. It already handles all the things you require.

Upvotes: 2

Ben S
Ben S

Reputation: 69342

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.

Upvotes: 2

Joel Coehoorn
Joel Coehoorn

Reputation: 415765

Use System.Net.FtpWebRequest/FtpWebResponse

Upvotes: 1

Related Questions