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.

(25) Comments

Blog Message Parajumpers

Ultra Developers - How to: Upload files to FTP directory using C# Parajumpers http://www.inntre.no/admin/jakke.asp


Blog Message cheap red bottom shoes

Ultra Developers - How to: Upload files to FTP directory using C# cheap red bottom shoes http://www.christianlouboutins-outlet.com


Blog Message louis vuitton neverfull gm damier

iCoat Notebook is really a not long ago released OZAKI iPad two leather protection circumstance. This protective shell with a high fashion leather goods in Italy and France manufactured Saffiano and Epi leather materials, which has a variety of colors, in leather components decorated with retro vogue in 2011, to create elegant extravagance knows no borders, and together with the top equate leather. louis vuitton neverfull gm damier http://pksuccess.com/louis-vuitton-neverfull-gm-damier.html


Blog Message

Graduation dresses for juniors ought to become selected cautiously. The bulk from the juniors are not able of make great options relating to the choice of graduation dresses. Consequently, moms and dads should pay out suitable attention on obtaining the appealing outfit for his or her member of the family. I have to confess that contemporary and fashionable graduation dresses are particularly beneficial to acquire a regal existence. I counsel you to realize with regards to the graduation bash principles to be sure that you may possibly come up with a good move to pick out proper types of apparel. Lots of youthful women of all ages have great particulars with regard to the gown code additionally they could choose the right social gathering put on. A couple of in the faculties manage semi-formal and formal graduation events inside of the popularity of eighth grade students. This kind of an case in point instructional facilities are incredibly strict with regards to their rules and guidelines. http://lakemacquariewebdesign.com.au


Blog Message

Yet again, whenever you request yourself the best way to move forward as he withdraws, the perfect factor to perform is to step absent far too. Let him to have his inner thoughts under handle and assess which he wishes. If he demands a prolonged whilst to return then so no matter whether it is. Only he is capable to determine what he wants and you should never ever thrust him to talk or maybe be coupled with you if he doesn show up to wish to accomplish each one. http://france.nicktour.spb.ru/index.php?subaction=userinfo&user=kopetpdmsp


Blog Message discount prada gaufre fabric tote

For those who are logging in for the 1st time, you can make an account so as to shop more quickly and a lot easier. You will get the newest updates on your own order as well as the position. Supply is prompt and prospects are suggested to help keep track of the orders beforehand created. discount prada gaufre fabric tote http://goseela.com/discount-prada-gaufre-fabric-tote.html


Blog Message louis vuitton sale

23 year-old Dental Technician Harlan Bonacci from Masson, loves to spend some time aeromodeling, nike free and polo. Plans to retire and take the family to many of the noteworthy heritage listed locales on the globe for example Medina of Tunis. louis vuitton sale http://www.budget-hotels-jaipur.com#


Blog Message authentique Nike air max 90 hommes

Regardless of what relative will be searching for footwear it is a wise substitute for look for the actual Geox shoes for sale.There exists by no means a spat from the youngsters while planning to find some Geox footwear on sale. Children value the comfort of the sneakers and also much like the trendy styles too. authentique Nike air max 90 hommes http://www.airmaxpascherfemme.com/views/homme-nike-air-max-90-hyp-prm-vert-fluorescence-357.html/


Blog Message

Nevertheless, following some persuasion, I did generate a straightforward web-site for this match, which was tentatively named Ovasinax (an abbreviation of ovanp sin axlar, which happens to be subsequently dependant on the Swedish phrase that means - "on top of his shoulders"). The title had to be just a little odd but exclusive, so as to fit the game; the sport itself is without a doubt exclusive, while it does borrow a few elements from your excessive activity of Tandem-Surfing as well as the quirky (but increasing) match of Wife-Carrying, which was even highlighted on an episode from the "Live with Kelly and Michael" Tv set present, recently. Ovasinax basically is actually a tandem level of competition in which (i) the onus is placed on the two associates in a crew to screen distinguished skills, and (ii) an try is designed to strike a contented medium among "sport" and "game show" (because sporting activities generally start/grow slowly and gradually but do stand the check of your time, even though the reverse is commonly true for Television recreation demonstrates). In almost any case, male strength and velocity are essential in the course of an Ovasinax race, though female balance/coordination capabilities are equally required; you'll find also aspects of romance and chivalry throughout the match because of the lady currently being to the man's shoulders (that's pertinent since romance and chivalry show up for being getting to be significantly less common, as time passes... regrettably!). http://thisgamesux.net/vb/showthread.php?p=546108#post546108


Blog Message lunette de soleil ray ban pas cher

Hello, several person known as Blumenthal has recently removed your current infographic and submitted the idea in the site! I actually need ideas in the event he obtained agreement not really, therefore merely transferring that down. Below is their hyperlink: lunette de soleil ray ban pas cher http://www.setetmatch.com/Images/raybanenligne/


Blog Message jordan shoes for sale

Also i including browsing on on thesixtyone. com excellent beautiful artwork enviroment, nice music by breakin by means of musicians along with a nice social network. jordan shoes for sale http://locascompras.com/wp-content/languages/postbox.php


Blog Message michael kors outlet online

Television Journalist Magnuson from Vankleek Hill, enjoys to spend some time volleyball, nike free and bee keeping. Always loves going to destinations including Schokland and Surroundings. michael kors outlet online http://www.marshallpta.net#


Blog Message christian louboutin

Otorhinolaryngologist Emerson Piker from Roxboro, has hobbies and interests for example sculpting, nike free and drawing. Felt especially encouraged after visiting New Zealand Sub-Antarctic Islands. christian louboutin http://www.22solution.com#


Blog Message

ISIL has vowed to accept the struggle to cities and Baghdad even farther southern property revered Shiite shrines. http://www.cheahagolfcarts.com/page1.php


Blog Message michael kors outlet

34 yrs old Careers Counsellor Rusty Budzinski from La Loche, has interests which include sculpting, nike free and post cards. In the last year has completed a visit to . michael kors outlet http://www.descargarebooksgratis.net#

First Previous 1 2 Next Last 
Rating
Name
Email
Comment