Wednesday, August 29, 2012

FTP Requests with C#

In this post I want to show, how to upload files via C# to a FTP webserver and how to delete them again.
The code for this is pretty simple, for both operations the schema is similiar:
First an instance of the class FtpWebRequest is created, where the target URL is handed over.
Normally this consists of ftp://servername/filename.
Via the propety Method of the instance the operation which is to be executed is set.
The property Credentials defines the login data, user name and password.
With the function GetResponse() the operation finally is executed.
When creating a file, additionally with a stream can be written in it.
With that I want to finish my explanations and directly show the source code (using System.Net is required):


Create and Fill File:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://servername.de/filename");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
WebResponse Response = request.GetResponse();
Stream RequestStream = request.GetRequestStream();
RequestStream.Write(...);
RequestStream.Close();
Response.Close();

Delete File:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://servername.de/filename");
request.Method = WebRequestMethods.Ftp.DeleteFile;
request.Credentials = new NetworkCredential("username", "password");
FtpWebResponse Response = (FtpWebResponse)request.GetResponse();
Response.Close();

No comments:

Post a Comment