In this tutorial I will show you how to use C# to connect to a FTP server and perform basic operations:

• deleting a file

## 1.Connecting & Logging In

Before doing operations on files, you must learn how to connect to the FTP server. For every action, you have to use a FtpWebRequest - and with it, you tell the server what to do. When the FtpWebRequest is created, you have to provide the path to the file:

1
2
// 'ftp://myFtpAddress.tld/myFile.txt' is the path to the file


Now, we have to provide the authentication data (username & password). This data must be included into the FTP request:

1


This is how your code should look like:

1
2
3



After this, you can start doing operations with files.

You have to tell the FTP Server what you want to do - in this case, you want to upload a file. So, you’ll set the WebRequestMethod to UploadFile:

1


The line above tells the server that you want to upload a file - so it’ll wait for file’s content. The file’s content must be sent as a byte array (byte[]):

1
2
3
4
5
6
7
8
9
10
11
byte[] fileContent;  //in this array you'll store the file's content

{
fileContent = Encoding.UTF8.GetBytes(sr.ReadToEnd()); //getting the file's content, already transformed into a byte array
}

using (Stream sw = ftpRequest.GetRequestStream())
{
sw.Write(fileContent, 0, fileContent.Length);  //sending the content to the FTP Server
}


The complete code for file upload will look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;
using System.Net;
using System.IO;
using System.Text;

namespace testProj
{
class Program
{
static void Main(string[] args)
{

byte[] fileContent;

{
}

using (Stream sw = ftpRequest.GetRequestStream())
{
sw.Write(fileContent, 0, fileContent.Length);
}

ftpRequest.GetResponse();
}
}
}


This is easier, this time the server will send to our program the file’s content. But first, we must tell the server that we want to download a file:

1


Then, we’ll get the server’s response - that’s the file we want. To do this, you can use a StreamReader to read from the main Stream.

1
2
3
4
5
using (Stream sw = ftpRequest.GetResponse().GetResponseStream())  //getting the response stream
{
}


And the complete code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Net;
using System.IO;
using System.Text;

namespace testProj
{
class Program
{
static void Main(string[] args)
{

using (Stream sw = ftpRequest.GetResponse().GetResponseStream())
{
}
}
}
}


## 4.Deleting a file

Once again, tell the server what you want to do (delete a file), using WebRequestMethods:

1
ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;


And that’s all ! - no additional code is required to do this.
The complete source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Net;
using System.IO;
using System.Text;

namespace testProj
{
class Program
{
static void Main(string[] args)
{