Code Examples
  Home arrow Code Examples arrow Building a Basic FTP Client with VS.Net by...
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
CODE EXAMPLES

Building a Basic FTP Client with VS.Net by Lance R.
By: aspfree
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 12
    2002-03-06

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    This users guide will go through some of the basic steps that one might take in order to create an FTP client application in VS.Net. The full source code for this client is available for download with any of the IPWorks! Editions.

     In this guide, we will make use of the FTP component included in the IP*Works! .Net Edition. If you do not have this toolkit, or would like to download it for free, please visit our download site and do so. For the purposes of this document, we will assume that IP*Works! .Net Edition has already been installed on the readers computer. The .Net Edition includes sample code for both VB.Net and C#, but here we will be coding in VB.Net.   If you would like code samples in a particular language, please contact support@nsoftware.com, or look through the demos available in the free fully functional trial versions of IP*Works! which is downloadable at http://www.nsoftware.com/download.asp. IP*Works! is available for many different languages and platforms.

    Getting Connected

    Begin by placing the FTP component on the form IP*Works! will provide you with the option of creating an IP*Works! toolbar in your VS.Net toolbox when you install Simply select the component from there The first thing we want to do is have the ability to logon to an FTP server, right? We'll put a Connect button, and textboxes for user input in order to get the name of the FTP server, the user name, and the password for that user.

    Once we have gathered this information “we can connect to the server. Simply assign the RemoteHost, User, and Password properties and call the Logon method.

     

    FTP1.RemoteHost = txtServer.Text

    FTP1.User = txtUser.Text

    FTP1.Password = txtPassword.Text

    FTP1.Logon()  

    What About Connection Errors?

    If the server is not reachable or if the connection is refused by the server, the component will generate an exception. This error would be a standard exception, caught with traditional error catching routines (ie in VB.Net, an On Error statement). As for slow connections, or established connections that experience problems later, you can set an optional timeout value using the Timeout property if you like. The Timeout will fire an error if the method (in this case the logon method) does not return in Timeout seconds.

    Now that we are connected what are we to do? The first thing we'll want to do obviously in an FTP client application is display a listing of files on the client and the server. In order to display the client side files, you'd want to use some file object library. You can use the VS.Net System.IO classes for this. The remote file listing can be obtained by using the ListDirectory or ListDirectoryLong methods of the FTP component. The difference is that the ListDirectory method will only return the filenames of the remote directory. The ListDirectoryLong method returns the filename, size, modification date, etc. The results from the methods will be returned in the DirList event. You'll need to overwrite this event in order to retrieve the results.

     

    We’ll use a listbox and combo box for both the client and server side to hold the file listings and the working directory. The RemotePath and RemoteFile properties are very important to the ListDirectory method (and any other FTP method that handles files). The directory listing will be performed on the remote path that is contained in the RemotePath property, and with the filemask contained in RemoteFile. If RemoteFile is empty, all files will be returned.

     

     

    After the Logon method, the RemotePath will automatically be updated with the home directory of the user, ie generally “/home/username”. But you must be very careful to keep up with what the RemotePath is during your connection.

     

           FTP1.RemotePath = “/home/username”

           FTP1.RemoteFile = “”

           FTP1.ListDirectory()

     

    These three simple lines will retrieve a directory listing of all files in the remote path /home/username. We’ll grab this data from the DirList event and insert it into the remote file listbox called lstRemote. The DirList event will fire one time for each file on the server that matches the filemask for the directory list request.

     

    Private Sub Ftp1_OnDirList(ByVal sender As System.Object, ByVal e As nsoftware.IPWorks.FtpDirListEventArgs) Handles Ftp1.OnDirList

     

    If e.IsDir Then

       lstRemote.Items.Add( "<Dir> " & e.FileName)

    Else

       lstRemote.Items.Add(e.FileName)

    End If

    End Sub

     

    Here, the parameter DirEntry contains the exact directory entry response from the server, exactly as the server sent it, ie:

     

    -rw-r--r--  1 group  username      4557 Aug 29 2001 .Xdefaults

     

    FileName is a string parameter containing the name of the file itself, ie .Xdefaults.

    IsDir is a Boolean value. IsDir will be true if this particular DirEntry is a directory.

    FileSize is a long containing the size of the file on the remote server.

    FileTime is a string containing the last modified date of the file on the server.

     

     

    File Transfers: Upload and Download

     

    Now we’ll add Upload and Download capabilities. To do this, we’ll need to set the RemotePath, RemoteFile, LocalPath, and LocalFile properties before attempting a transfer. We’ll use our two listboxes and comboboxes to determine that information.

     

    The value in our client combobox cbClient is “C:/. The selected item in our client listbox lstClient is “test.txt”. So we’ll set:

     

            FTP1.LocalPath = cbClient.Items(cbClient.SelectedIndex)

            FTP1.LocalFile = lstClient.Items(lstClient.Selectedindex)

     

    This will point the FTP component to the local file we want to upload. Now we’ll name the file the same thing on the client side, and we’ll keep track of the remote path in the server combobox, cbServer, ie:

     

            FTP1.RemotePath = cbServer.Items(cbServer.SelectedIndex)

            FTP1.RemoteFile = lstClient.Items(lstClient.SelectedIndex)

     

            And now perform the upload:

            FTP1.Upload()

    Other Methods

     

    For other miscellaneous functions of the FTP component, there are many useful methods:

    Append, much like Upload, except if the remote file already exists, the file is appended to rather than overwritten. DeleteFile, attempts to delete the remote file from the server. Logoff, log off the server. MakeDirectory, create the directory specified by RemoteFile on the server. RemoveDirectory, remove the directory specified by RemoteFile on the server. This will not remove files within the directory automatically, that would have to be done using DeleteFile before removing the directory. RenameFile, renames the file specified in RemoteFile to the value specified in the AltValue property. StoreUnique - much like Upload, except that the remote server decides the remote file name itself such that the file name is a unique one. The file name that the server writes to will be sent to the client. You can determine that filename by examining the LastReply property, which always contains the last reply from the server.

     

    Percent Transferred

     

    OK, so now we are transferring files. How do I know the status of the file transfer? First of all, when the transfer is first begun, a StartTransfer event will fire. During the transfer, a Transfer event will fire, and after the transfer is finished, an EndTransfer event will fire. You can use the BytesTransferred property that is available in the Transfer event of the FTP component to keep track of how many bytes have been transferred so far in the current transfer. This information will allow you to create a progress bar. In order to do the math, you will of course need to know the file size. If you are uploading a file to the server, you already know the file size since its local (Use a File system object). If you are downloading a remote file from the server, you’ll need to ask the server how large the file is before initiating the download, by setting the RemoteFile property to the appropriate file and issuing a ListDirectoryLong. Then the DirList event will be fired once for the file you have specified and you can get the filesize parameter of the DirList event.

     

     

    Debugging

     

    The most powerful debugging tool of the FTP component is the PITrail event. The PITrail event shows you all of the communication that is happening between the client and the server.

     

    Private Sub Ftp1_OnPITrail(ByVal sender As System.Object, ByVal e As nsoftware.IPWorks.FtpPITrailEventArgs) Handles Ftp1.OnPITrail

     

        txtPITrail.AppendText(e.Direction & ": " & e.Message & VbCrLf)

    End Sub

     

    The Direction parameter of the event tells you in what direction the message is traveling, from the client to the server or server to the client. If the value of Direction is 0, the Message is being sent by the client. If the value of Direction is 1, the Message is being sent by the server.

     

    For the full source of this fully implemented FTP Client, download an IP*Works! trial Edition from www.nsoftware.com/download.asp.

     

    More Information

     

    For more information about IP*Works! or the FTP component, please visit www.nsoftware.com. There you will find access to our online Knowledge Base, access to free email technical support, and much more valuable information. Included in each edition of IP*Works! are many demo applications that show the power and flexibility of the toolkit. If you need more specific guidance, please feel free to email our technical support department via the online support form at www.nsoftware.com/support/request.asp.

     

     


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Code Examples Articles
    More By aspfree

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Accelerating Software Innovation on i on Power Systems

    Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, for an overview of Rational’s new software offerings and resources to help modernize and accelerate software innovation on i on Power Systems – while ensuring past application investments are protected and continue to grow. Learn how these solutions are helping customers extend their core i5/OS solutions toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time.
    FREE! Go There Now!


    NEW! Download DB2 Express-C 9.5

    Visit IBM developerWorks to download IBM DB2 Express-C 9.5, a no-charge version of DB2 Express 9 database server. DB2 Express-C offers the same core data server base features as other DB2 Express editions and provides a solid base to build and deploy applications developed using C/C++, Java, .NET, PHP, and other programming languages.
    FREE! Go There Now!


    NEW! Evaluate IBM Lotus Sametime Standard V8.0

    Visit IBM developerWorks to download a free trial of the latest release of IBM Lotus Sametime Standard V8.0. Lotus Sametime Standard V8.0 is a platform for unified communications and collaboration that combines security features with an extensible, open solution including integrated Voice over IP, geographic location awareness, mobile clients, and a robust Business Partner community offering telephony and video integration.
    FREE! Go There Now!


    NEW! Evaluate WebSphere Extended Deployment Compute Grid V6.1

    Visit IBM developerWorks to download a free trial version of WebSphere Extended Deployment Compute Grid, which lets you schedule, execute, and monitor batch jobs. Because online transaction processing and batch jobs execute simultaneously on the same server resources, you can avoid costly duplication of resources. Compute Grid supports job types of Java transactional batch, compute-intensive and a new type called "native execution", which enables non-Java workloads to run on distributed end points.
    FREE! Go There Now!


    NEW! Hacking 101

    Join us for this web seminar to learn how you can defend your web applications from attack. Learn about the 3 most common web application attacks, including how they occur and what can be done to prevent them. We’ll also discuss manual versus automated approaches for scanning and identifying web application vulnerabilities and how IBM Rational AppScan, an automated vulnerability scanner, can help you automate more of what you are doing manually today.
    FREE! Go There Now!


    NEW! Hello World: Learn how to install and use the Rational Asset Manager Eclipse client

    In this tutorial, you can learn how to install and configure the IBM Rational Asset Manager Eclipse client, explore the different views in the Asset Management perspective, learn various search techniques, work with existing assets, and submit a new asset.
    FREE! Go There Now!


    NEW! IBM Enterprise Modernization Sandbox for System z: Architecture

    Analysts, architects, and developers who have existing COBOL or PL/I skills and want to extend those skills to deploy new workloads on the mainframe can use the IBM Enterprise Modernization Sandbox for System z to find hands-on walkthroughs of common real world scenarios. The scenarios provide examples of how to rapidly design, create, assemble, test, and deploy high-quality Web, Web services, portal, and SOA applications for IBM CICS, IBM IMS, and IBM WebSphere Application Server.
    FREE! Go There Now!


    NEW! Project and Portfolio Management Executive Resource Kit

    Portfolio Management is about effectively managing portfolio value by aligning portfolio investments with business goals. This complimentary e-kit provides a collection of materials that can help you understand how IBM Rational enables and automates best practices for improved governance and clear visibility into portfolio and project performance across the entire IT project lifecycle.
    FREE! Go There Now!


    NEW! Understanding Web application security challenges

    As businesses grow increasingly dependent upon Web applications, these complex entities grow more difficult to secure. Most companies equip their Web sites with firewalls, Secure Sockets Layer (SSL), and network and host security, but the majority of attacks are on applications themselves – and these technologies cannot prevent them. This paper explains what you can do to help protect your organization, and it discusses an approach for improving your organization’s Web application security.
    FREE! Go There Now!


    NEW! Webcast: Application security testing and Web compliance

    Join the IBM Watchfire team for an informative discussion on techniques and best practices to proactively manage Web application security and how to effectively build application security testing into the software development lifecycle (SDLC). In this Software Delivery Platform webcast you will learn: How to better understand potential web application security vulnerabilities, best practices and how to effectively integrate application security testing into the software development lifecycle, the importance of detecting and removing software vulnerabilities during application development.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    CODE EXAMPLES ARTICLES

    - Bipartite Graphs
    - Connectivity in Graphs
    - The Ford-Fulkerson Algorithm
    - Critical Paths
    - The Bellman-Ford and Roy-Floyd Algorithms
    - Shortest Path Algorithms in Graphs
    - Minimum Spanning Tree
    - Articulation Edges and Vertexes
    - Circles and Connectivity in Graphs
    - Depth-First Search in Graphs
    - Breadth-First Search in Graphs
    - The Prufer Code and the Floyd-Warshall Algor...
    - An Insight into Graphs
    - Coding a Custom Object with WSC
    - Creating a Custom Object with WSC





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek