How to: Upload Files with FTP

Switch View :
ScriptFree
How to: Upload Files with FTP

This sample shows how to upload a file to an FTP server.

Example

C#
using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // 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();
            }
        }
    }
}
Compiling the Code

This example requires:

  • References to the System.Net namespace.

Community Content

ArkonRogg
Your Ignorance also is...
If you would be a "programer", not just a script kiddie, you would have no problem converting an C#-Code into VB-Code, because the are both .NET languages...
As long as you are fixed on only one language of the .NET family, you could not call yourself a "programer"... Think about it.

ArkonRogg
The arrogance of the anti-VB crowd is really getting old...
You should get together with anti-iPad crowd and have a little party celebrating how superior you all are

CodeToad
*PLEASE* give (at least 1) example in visual basic... the most popular language on the planet.
*PLEASE* give (at least 1) example in visual basic... the most popular language on the planet.

How about becoming a real programer and learn a language.  Visual Basic for the Very Basic programmers. Try that for a *pointer.

Bearcat9
VB Example
Enter comment here.While its not the most popular language on the planet as stated up above but here is an example:





'below code will return a listing of the files in your FTP site



  Dim request As FtpWebRequest = FtpWebRequest.Create("Your FTP Site main root folder")



        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails







        'assumes the FTP site uses anonymous logon.



        request.Credentials = New NetworkCredential("username", "password")







        Dim response As FtpWebResponse = request.GetResponse()







        Dim responseStream As Stream = response.GetResponseStream()



        Dim reader As StreamReader = New StreamReader(responseStream)











        'Puts the response string into a string variable



        Dim responseString As String = reader.ReadToEnd()







        reader.Close()



        response.Close()   'below request download of single File



'below the code will request a download of a signel File



        'string below would look like ftp://IP/rootfolder/somefile



        Dim serverUri As Uri = New Uri("ftpsite" + " I append a file name here because i give user optio to choose the file they want")                   If (serverUri.Scheme = Uri.UriSchemeFtp) = True Then



                 Dim requestDownload As WebClient = New WebClient()



                 requestDownload.Credentials = New NetworkCredential("username", "password")



                 Try               



                         Dim newFileData As Byte() = requestDownload.DownloadData(serverUri.ToString())



                         Dim fileString As String = System.Text.Encoding.UTF8.GetString(newFileData)             



                         Using file As System.IO.StreamWriter = new System.IO.StreamWriter("Path to file that you want to save it as"))



                                               file.WriteLine(fileString)



                         End Using                 



                Catch ex As WebException                       MessageBox.Show(ex.ToString())                   End Try



        Else



            MessageBox.Show("Failed, site not FTP")



        End If







This should atleast get you started.

Matthew Liberty
VB.NET Version
Here's the VB.Net equivalent of the Main Function: $0$0 $0 $0 $0            'Get the object used to communicate with the server.$0 $0            request = CType(WebRequest.Create("ftp://www.contoso.com/test.htm"), FtpWebRequest)$0 $0            request.Method = WebRequestMethods.Ftp.UploadFile$0 $0$0 $0 $0            'This example assumes the FTP site uses anonymous logon.$0 $0            request.Credentials = New NetworkCredential("anonymous", "janeDoe@contoso.com")$0 $0$0 $0 $0            'Copy the contents of the file to the request stream.$0 $0            Dim sourceStream As New StreamReader("testfile.txt")$0 $0            Dim fileContents As Byte() = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd())$0 $0            sourceStream.Close()$0 $0            request.ContentLength = fileContents.Length$0 $0$0 $0 $0            Dim requestStream As Stream = request.GetRequestStream()$0 $0            requestStream.Write(fileContents, 0, fileContents.Length)$0 $0            requestStream.Close()$0 $0$0 $0 $0            Dim response As FtpWebResponse = CType(myFtpWebRequest.GetResponse(), FtpWebResponse)$0 $0$0 $0 $0            Console.WriteLine("Upload File Complete, status {0}", Response.StatusDescription)$0 $0

Omar Elsherif
FTP Uploader
public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }

        const int BUFFER_SIZE = 4096;

        string filePath = string.Empty;
        string fileName = string.Empty;

        private void browseButton_Click(object sender, EventArgs e)
        {
            if (uploadOpenFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fileNameTextBox.Text = uploadOpenFileDialog.FileName;

                filePath = uploadOpenFileDialog.FileName;
                fileName = uploadOpenFileDialog.SafeFileName;
            }
        }

        private void uploadButton_Click(object sender, EventArgs e)
        {
            if ((filePath != string.Empty) && (fTPServerTextBox.Text != string.Empty) &&
                (usernameTextBox.Text != string.Empty) && (passwordTextBox.Text != string.Empty))
            {
                FtpWebRequest request;
                FtpWebResponse response;

                Stream sourceStream = new MemoryStream();
                Stream requestStream = sourceStream;

                try
                {
                    request = (FtpWebRequest)WebRequest.Create(fTPServerTextBox.Text + '/' + fileName);
                    request.Method = WebRequestMethods.Ftp.UploadFile;
                    request.Credentials = new NetworkCredential(usernameTextBox.Text, passwordTextBox.Text);

                    sourceStream = new FileStream(filePath, FileMode.Open);
                    
                    requestStream = request.GetRequestStream();
                    request.ContentLength = sourceStream.Length;
                   
                    byte[] buffer = new byte[BUFFER_SIZE];
                    int bytesRead = sourceStream.Read(buffer, 0, BUFFER_SIZE);

                    do
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                        bytesRead = sourceStream.Read(buffer, 0, BUFFER_SIZE);

                    } while (bytesRead > 0);

                    sourceStream.Close();
                    requestStream.Close();

                    response = (FtpWebResponse)request.GetResponse();
                    processResultToolStripStatusLabel.Text = string.Format("Upload Complete, Status Code: {0}", response.StatusDescription);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.GetType().Name + ": \n" + ex.Message, "Exception!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    request = null;

                    sourceStream.Close();
                    sourceStream = null;

                    requestStream.Close();
                    requestStream = null;
                }
            }
        }
    }

reza,sadeghi
Why encoded UTF-8?
This example is great with text files, but try it with excel or many other file types and it fails. With a small change it will work for most any file.

USE:

byte[] fileContents = file.ReadAllBytes("testfile.txt");

NOT:

StreamReader sourceStream = new StreamReader("testfile.txt");
byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());

I have had more luck with this method

mist83
*PLEASE* give code that compiles
There's an extra bracket at the end of the code that you need to remove to compile it (there are currently 4, and there should only be 3).
I realize that this request may seem nitpicky in this specific situation, but it indicates that this *exact* code snippet was never even tested by Microsoft.


PattyDD
FTP Passive
If your FTP server is setup to be passive, make sure you set UsePassive to TRUE, else you will get a very unhelpful generic error.

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.UsePassive = true;

Thomas Lee
PowerShell Sample
<#
.SYNOPSIS
This script Uploads a text file to an FTP Server using PowerShell.
.DESCRIPTION
This script first creates an FTP 'web' request to upload a file. Then the
source file is read from disk and written up to the FTP Server. A response
is then displayed. This is a rewrite of an MSDN Sample.
.NOTES
File Name : Copy-FileToFtp.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell Version 2.0
.LINK
This script posted to:
http://www.pshscripts.blogspot.com
MSDN sample posted tot:
http://
.EXAMPLE
PSH [C:\foo]: .Copy-FileToFtp.ps1
Upload File Complete, status 226-Maximum disk quota limited to 100000 Kbytes
Used disk quota 78237 Kbytes, available 21762 Kbytes
226 Transfer complete.
#>

# Get the object used to communicate with the server.
$Request = [System.Net.FtpWebRequest]::Create("ftp://www.reskit.net/powershell/Greetings.Txt")
$Request.Method = $Request.Method = [System.Net.WebRequestMethods+ftp]::UploadFile

# This example assumes the FTP site uses anonymous logon.
$Request.Credentials = New-Object System.Net.NetworkCredential "anonymous","tfl@psp.co.uk"

# Copy the contents of the file to the request stream.
$SourceStream = New-Object System.IO.StreamReader "c:\foo\ftpgreetings.txt"
$FileContents = [System.Text.Encoding]::UTF8.Getbytes($sourceStream.ReadToEnd())
$SourceStream.Close();
$Request.ContentLength = $fileContents.Length;

$RequestStream = $request.GetRequestStream()
$RequestStream.Write($FileContents, 0, $FileContents.Length);
$RequestStream.Close();
$Response = $Request.GetResponse()
"Upload File Complete, status {0}" -f $Response.StatusDescription
$Response.Close();