News
  • Favorite
  • Facebook
  • Twitter
  • LinkedIn

Microsoft Press Pearson Education (InformIT)
Skip Navigation Links
Pearson Education (InformIT)
How to: Upload files to FTP directory using C#

Sometimes your application wants to upload files or reports to an FTP directory on a web server to be viewed by your customers. You can open Explorer and type your FTP directory location, type FTP user name and password and copy files from your machine to that FTP directory. But if you want to automate the process of generating reports from your application and upload it to the FTP directory on the web server. This article will help you solve this problem.

Using the Code:

To automate the process of generating reports from your application and upload it to the FTP directory follow the following steps:

1.      Create a new windows application using Visual Studio 2005/2008/2010.

2.      Rename Form1 to FtpForm.

3.      Add a Label to the FtpFormand rename it to FtpDirectoryLabel and set its Text property toFTP Directory.

4.      Add another Label to the FtpFormand rename it to UserNameLabel and set its Text property to User Name.

5.      Add another Label to the FtpFormand rename it to PasswordLabel and set its Text property to Password.

6.      Add a TextBox to the FtpFormand rename it to FtpDirectoryTextBox.

7.      Add another TextBox to the FtpFormand rename it to UserNameTextBox.

8.      Add another TextBox to the FtpFormand rename it to PasswordTextBox and set its PasswordCharproperty to *.

9.      Add a RichTextBox to the FtpFormand rename it to ResultTextBox.

10.  Add an ErrorProvider component to the FtpForm and name it errorProvider. The Error Provider  provides a user interface for indication that a control on the form has an error associated with it.

11.  Add a button to the FtpFormand rename it to UploadFtpButton and set its Text Property to Upload FTP.

12.  Import the System.Net and System.IO namespaces using the following statement:

using System.Net;

using System.IO;

13.  The System.Net namespace provides a simple programming interface for many of the protocols used on networks today.

14.  The System.IO namespace contains types that allow reading and writing to files and data streams and types that provide basic file and directory support.

15.  Double click theUploadFtpButton to create the Click Event Handler.

16.  Add the following code to the UploadFtpButton Click Event Handler:

private void UploadFtpToolStripButton_Click(object sender, EventArgs e)

{

    try

    {

        errorProvider.Clear();

        if (string.IsNullOrEmpty(FtpDirectoryTextBox.Text))

        {

            errorProvider.SetError(FtpDirectoryTextBox, "Required");

            return;

        }

 

        if (string.IsNullOrEmpty(UserNameTextBox.Text))

        {

            errorProvider.SetError(UserNameTextBox, "Required");

            return;

        }

 

        if (string.IsNullOrEmpty(PasswordTextBox.Text))

        {

            errorProvider.SetError(PasswordTextBox, "Required");

            return;

        }

 

        OpenFileDialog openFileDialog = new OpenFileDialog();

        DialogResult openResult = openFileDialog.ShowDialog();

 

        if (openResult == DialogResult.OK)

        {

            FileInfo uploadFile = new FileInfo(openFileDialog.FileName);

            string ftpLink = FtpDirectoryTextBox.Text + "/" + uploadFile.Name;

 

            FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create(ftpLink);

            ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;

            ftpWebRequest.Credentials = new NetworkCredential(UserNameTextBox.Text, PasswordTextBox.Text);

            ftpWebRequest.KeepAlive = true;

 

            FileStream fileStream = new FileStream(openFileDialog.FileName, FileMode.Open);

            byte[] fileData = new byte[fileStream.Length];

            fileStream.Read(fileData, 0, (int)fileStream.Length);

            fileStream.Close();

 

            ftpWebRequest.ContentLength = fileData.Length;

            Stream requestStream = ftpWebRequest.GetRequestStream();

            requestStream.Write(fileData, 0, fileData.Length);

            requestStream.Close();

 

            FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();

 

            ResultTextBox.Text += string.Format("\n{0} {1} {2}", uploadFile.Name

, ftpWebResponse.StatusDescription, ftpWebResponse.StatusCode.ToString());

 

            ftpWebResponse.Close();

        }

    }

    catch (IOException ex)

    {

        MessageBox.Show(ex.Message, ex.GetType().ToString(),

               MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    catch (WebException ex)

    {

        MessageBox.Show(ex.Message, ex.GetType().ToString(),

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

}

 

a.      First of all we clear any error in the errorProvider component by calling the Clear method of the errorProvider.

b.     We check that the user enters a value in the FtpDirectoryTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text.

c.      We then check that the user enters a value in the UserNameTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text.

d.     We then check that the user enters a value in the PasswordTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text.

e.     We create an object of the OpenFileDialog class that will prompt the user to open a file.

f.       We create an object of the Dialogresult class that will hold the result of opening the OpenFileDialog to determine if the user clicks open or cancel.

g.      If the user selects to upload the files we create a FileInfo object that will have all the details about the selected file to upload.

h.     Create a string object and set it to the FTP upload directory concatenated by the file to upload.

i.        We create an FtpWebRequestobject named ftpWebRequest that implements a File Transfer Protocol (FTP) client.

j.       We use the WebRequestclass (that makes a request to a Uniform Resource Identifier (URI)) to create the request and cast it to FtpWebRequest.

k.      We then set the ftpWebRequestMethod property to WebRequestMethods.Ftp.UploadFile to make the request uploads the file.

l.        Then we set the ftpWebRequestCredentials using the NetworkCredential class and passing to it the user name and password that we will use to authenticate the FTP request.

m.   Creat a FileStreamobject and name it fileStream to open the file to be uploaded.

n.     Create a byte array and name it fileData that will be used to store the file data and set its initial capacity to the file stream length.

o.     Read the data of the file from the fileStream object and place it in the fileData byte array.

p.     Close the fileStream to free memory resourse we don’t need this stream again.

q.     We set the ftpWebRequestcontent length to the length of the fileData byte array.

r.       We create a Stream object and name it requestStream this will get its data from the ftpWebRequest.GetRequestStream()method. We will use this stream to write the fileData to the FTP Directory.

s.      Close the requestStreamobject to free memory resources.

t.       Create an object of type FtpWebResponseclass that encapsulates a File Transfer Protocol (FTP) server's response to a request.

u.     Use the ftpWebRequestto get the response to the upload operation using the GetResponsemethod.

v.      Now we have the response to the upload operation we will display the response status code and Status Description in the ResultTextBox.

w.    Close the ftpWebResponseobject to free memory and resources.

x.      We then catch any IO Exceptions and Web Exceptions.

Now you have an application that can be used to upload files to an FTP directory.

Further Improvements:

1.      You can collect data from the application user and save it in a file and upload it directly.

2.      You can select more than one file from the OpenFileDialog and upload them.

(72) Comments

Blog Message http://studio-5.financialcontent.com/mi.macon/news/read/37949241

This blog is no doubt educating as well as informative. I have picked helluva helpful things out of this source. I ad love to return again and again. Thanks a bunch!


Blog Message https://startupshop.jouwweb.nl/

Only wanna input that you may have a very nice internet site, I enjoy the design and style it actually stands out.


Blog Message http://cutleryratings.net/__media__/js/netsoltrademark.php?d=cqa.aaua.edu.ng%2Findex.php%3Fqa%3Duser%26qa_1%3Dnutbell9

This is very interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your wonderful post. Also, I have shared your site in my social networks!


Blog Message http://vinochok-dnz17.in.ua/user/LamTauttBlilt450/

Wow, great blog.Much thanks again. Want more.


Blog Message http://hornsteiner.saarland/index.php/Need_To_Have_To_Purchase_A_Car_Look_At_This_Very_First..._Advice_No._1_From_411

My spouse and I stumbled over here from a different page and thought I might as well check things out. I like what I see so i am just following you. Look forward to going over your web page again.


Blog Message http://www.iamsport.org/pg/bookmarks/jutesupply3/read/43107391/how-to-grow-your-internet-marketing

Wow! Thank you! I continuously needed to write on my blog something like that. Can I take a part of your post to my site?


Blog Message http://www.lhasa.ru/board/tools.php?event=profile&pname=ErrorieElipse802

Thanks a lot for the article post.Much thanks again. Awesome.


Blog Message http://sla6.com/moon/profile.php?lookup=285428

The best and clear News and why it means a great deal.


Blog Message http://prodonetsk.com/users/SottomFautt554

My brother recommended I might like this web site. He was entirely right. This post truly made my day. You can not imagine simply how much time I had spent for this information! Thanks!


Blog Message http://bihardetails.com/user/profile/25746

Im grateful for the blog post.Thanks Again. Awesome.


Blog Message http://coastestate.website/story.php?id=11453

Really appreciate you sharing this blog post.Much thanks again. Cool.


Blog Message http://b3.zcubes.com/v.aspx?mid=647305

Im no professional, but I imagine you just made an excellent point. You definitely comprehend what youre talking about, and I can truly get behind that. Thanks for being so upfront and so genuine.


Blog Message http://avplus.ru/bitrix/rk.php?goto=https://zzb.bz/w2H28

Thanks for the blog article.Much thanks again. Really Cool.


Blog Message http://www.24x7buddy.com/index.php?qa=user&qa_1=juicegirl36

very nice put up, i certainly love this web site, keep on it


Blog Message https://vue-forums.uit.tufts.edu/user/profile/779782.page

I think other site proprietors should take this web site as an model, very clean and wonderful user genial style and design, as well as the content. You are an expert in this topic!

First Previous 1 2 3 4 5 Next Last 
Rating
Name
Email
Comment