PowerTCP FTP for .NET

Welcome to PowerTCP FTP for .NET, the most comprehensive and powerful FTP client development tool available on the market today. Working closely with Microsoft throughout the development process at the Microsoft DevLab, the design decisions incorporated into the product reflect the most effective techniques for developing a user-friendly, but powerful component in the Microsoft .NET Framework. These techniques not only reflect the actual code, but also extend to documentation, incorporating the Microsoft Help 2.0 engine that includes integrated dynamic Help within the development environment. The SSL implementation in the PowerTCP FTP for .NET has been tested against the most popular Secure FTP servers and is flexible enough to let you configure the security settings for any type of Secure FTP server.

In PowerTCP FTP for .NET.

Getting Started
Provides an overview of PowerTCP FTP for .NET and discusses such topics as distribution, licensing, and support.
Using the Ftp Component
Provides step-by-step instructions for those that are new to .NET or using components. It provides step-by-step instructions on creating an application using the Ftp component.
Storing Files Overview
Discusses how to store files to the server using the Ftp component.
Retrieving Files Overview
Discusses how to retrieve files from the server using the Ftp component.
Transferring Streams Overview
Discusses storing streams as files, and retrieving files as streams.
Accessing The Data Ftp.Connection
Discusses how to access the data connection for subsequent reading/writing.
Sending Commands Overview
Discusses how commands can be sent using the Ftp component.
Retrieving Listings Overview
Discusses how to retrieve listings using the Ftp component.
Using Secure Ftp
Discusses how to transfer files over SSL.
Using Events In PowerTcp
Dicusses how to use events with the Ftp component, both using Visual Studio .NET and in other environments.
Session Management Overview
Discusses how sessions are maintained using the Ftp component.
Using The Interactive Tools
Demonstrates how to use the included interactive tools to help make debugging and testing quicker and easier.
Accessing TCP Level Information
Demonstrates how to obtain data about the TCP connection used for the FTP communication.
Proxy Support Overview
Discusses special server implementations, including proxy servers.
Reference
Provides a language/syntax reference for FTP for .NET.
Ftp Component Samples
Describes the samples that are installed with the Ftp component.

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Getting Started With The Ftp Component

PowerTCP FTP for .NET is a complete suite of objects which enable the integration of FTP capabilty into any .NET application. This topic, and related subtopics, address issues such as licensing, distribution, and support. For tutorials and walkthroughs pertaining to usage of the Ftp component, see the topic Using The Ftp Component Overview. For a programmer's reference of the classes used by PowerTCP FTP for .NET, see the "Reference" topic.

In This Section

Overview
Provides an overview to the product.
Documentation Map
Provides a good navigational aid to quickly find the topic you want.
Requirements
Discusses the requirements needed to use PowerTCP FTP for .NET.
License Registration
Provides step-by-step instructions on installing a license.
Trial Operation
Provides an overview on using PowerTCP FTP for .NET in trial mode.
Deployment in ASP.NET
Discusses the extra steps which are required to distribute an application in ASP.NET.
Support
Provides an overview of the support options that are available for this product.
FTP Protocol Overview
Provides a brief introduction to the FTP protocol.

Related Sections

Using the Ftp Component
Provides links to walkthroughs pertaining to the Ftp component.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Overview

PowerTCP FTP for .NET Overview

Welcome to PowerTCP FTP for .NET, the most comprehensive and powerful FTP client development tool available on the market today. The combined software development experience of 62 years was applied to the creation of the product, including the lessons and knowledge garnered from multiple revisions of FTP client development tools ranging from C++ to multiple Visual Basic versions. Working closely with Microsoft throughout the development process at the Microsoft DevLab, the design decisions incorporated into the product reflect the most effective techniques for developing a user-friendly, but powerful component in the Microsoft .NET Framework. These techniques not only reflect the actual code design, but also extend to documentation, incorporating the Microsoft Help 2.0 engine that includes integrated dynamic Help within the development environment.

PowerTCP FTP for .NET is designed both for the beginner Microsoft .NET developer migrating from Visual Basic and the more experienced object-oriented developer moving from C++ to C#. Since not everyone is experienced with the FTP protocol, we have included a WYSIWYG code generator and connectivity-testing environment that is available from the Properties window called the Editor. This design-time testing environment works like an interactive FTP client, enabling a live connection to an FTP Server. Any information used in this environment is then saved as code to the form. Because PowerTCP FTP for .NET includes an Ftp component, usability is as simple as dragging and dropping onto a form, enabling all the events to be automatically wired into the application and all the properties exposed in the Properties window. Of course, those that wish to reference the component manually and create their own delegates are easily able to do so. Another ease-of-use addition to this product is the transparent login technology used throughout the FTP product. This technique removes the burden of session management from FTP communications by monitoring login-related properties for changes and automatically re-establishing communications if a login value has changed. For those in need of login-related control when using custom FTP proxy servers, a RawConnect method is available for low-level control.

The components included with PowerTCP FTP for .NET are architected for both synchronous and asynchronous functionality using multi-threading within the class. This elegant approach gives a programmer the flexibility of triggering an action and moving on to the next line of code before that action is completed, enabling a time-consuming activity to occur on a separate thread. All multi-threaded operation is synchronized internally so all asynchronous activity will be completely thread safe. Another architectural feature is the ability to conduct communications with an FTP server on multiple programmatic levels. Higher level functions wrap FTP commands for most required activities, and should be sufficient for most applications, but if sending proprietary or rarely used commands to the FTP server is a requirement, a configurable Invoke method is available for custom communications. Finally, if the level of communications required involves interaction with the underlying TCP protocol, the TCP connection is exposed using the ProgressBar property.

The core purpose of any FTP product is to send and retrieve files. The FTP objects enable this functionality both synchronously and asynchronously (with auto restart), using overloaded functions that enable sending and retrieving not only a file or a group of files, but files based on wildcards, streams, and direct access to the data connection. What this means is that all the simple functionality is available for sending and retrieving files, but for more complex needs like requiring data to be spooled to memory, streams are fully supported, and for the most low-level need, access to on-the-fly reading and writing to the data connection is available.

Debugging is a crucial aspect of software development and no developer can ever have enough debugging support in a product. The components included in PowerTCP FTP for .NET include both a powerful Trace event and an interactive debugger class, the TraceForm, which visually displays data as it is sent and received. The Trace event enables a software developer to create a log file to capture all low-level data as it is sent or received, or just use it for monitoring. To view the debugging process interactively, the TraceForm class can be used with any Tcp instance (ProgressBar) by simply passing an instance of the Tcp instance into the constructor.

Finally, and just as important as the actual software, is the documentation. PowerTCP FTP for .NET includes the most comprehensive documentation available for an FTP product, regardless of development environment. Besides complete integration using the Microsoft Help 2.0 engine (making all of the reference pages available in Visual Studio .NET and dynamic help with F1 support that includes high-level tutorials), the documentation consists of hundreds of pages of reference topics with code examples written in both VB.NET and C#. In addition, over 3-dozen tutorials are included covering topics for beginners and advanced users alike. Sample applications are also included in both VB.NET and C#.

Thank you for choosing PowerTCP. We hope you will agree that this product is a perfect complement to the .NET Framework, bringing you the quality and value you have learned to expect from Dart Communications.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Documentation Map

PowerTCP FTP for .NET Documentation Map

The following topics were designed to get you quickly developing using PowerTCP FTP for .NET

To | See
Learn how to add an Ftp component to a form | Using The Ftp Component In Visual Studio .NET
Learn how to add an Ftp component to a project as a reference. | Adding The Ftp Component As A Reference In Visual Studio .NET
Learn how to store a single file. | Storing Files Overview
Learn how to store multiple files. | Storing Files Overview
Learn how to retrieve a single file. | Retrieving Files Overview
Learn how to store a stream as a file. | Transferring Streams Overview
Learn how to retrieve a file as a stream. | Transferring Streams Overview
Learn how to read directly from the data connection. | Reading/Writing To The Data Connection Overview
Learn how to write directly to the data connection. | Reading/Writing To The Data Connection Overview
Learn how to send commands to the server. | Sending Commands Overview
Learn how to retrieve listings from the server. | Retrieving Listings Overview
Learn how to use events with PowerTCP.NET components in .NET. | Using Events In PowerTcp
Learn how sessions are managed using the Ftp component | Session Management Overview
Learn how to get information about the TCP connection. | Accessing The TCP Ftp.Connection
Learn how to connect to proxy servers and other FTP servers operating out of the FTP spec. | Proxy Support Overview
Learn how to use the included interactive tools to help make debugging and testing quicker and easier. | Using Interactive Tools
Get syntax descriptions for properties, methods, and events of PowerTCP FTP for .NET components. | Reference Overview
Get descriptions of samples installed with PowerTCP FTP For .NET | FTP for .NET Samples Overview
Learn how to communicate with secure servers using FTP. | Using Secure Ftp

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Requirements

To use PowerTCP for .NET you must have the following environment installed:

  • Microsoft Visual Studio .NET (recommended)
  • .NET Framework version 1, 1.1 or 2.

Related Sections

Using the Ftp Component
Provides links to walkthroughs pertaining to the Ftp component.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


License Registration

Your PowerTCP License Agreement provides you with a single-seat development license and the right to distribute PowerTCP classes with NO ROYALTIES of any kind. Some PowerTCP classes are marked as licensed. This topic covers:
  • Trial Installation
  • Installing a Fully Licensed PowerTCP Product
  • Re-installing a PowerTCP Product
  • License Details
  • Troubleshooting Licensing

Trial Installation

Installing a PowerTCP product as a fully–functional trial involves running the trial setup program (available from www.dart.com). The trial will operate for 30 days after installation. Proceed to step 2 of Installing a Fully Licensed PowerTCP Product when you are ready to license the product.

See Trial Operation for more information.

Installing a Fully Licensed PowerTCP Product

Once you have downloaded the latest version, complete the following steps to register your PowerTCP product.

If you have Internet Access on your development machine, please follow these instructions:

  1. From the Start menu, select Programs, select PowerTCP, select the PowerTCP product you downloaded, and then click License Registration.
  2. In the Dart License Registration dialog box, click Install.
  3. Click the Online Registration button.
  4. Enter required information, including Serial Number, First Name, Last Name, and Organization.
  5. Click Next.
  6. Enter your Email Address, Purchased From, and Purchase Date information.
  7. Click Next.
  8. Verify that the information is correct, and then click Next.
  9. When the registration process is complete, click Exit. (Note: Clicking Done at this step displays your currently registered PowerTCP product. Click Exit to complete the registration process and close the dialog box.)

If you do not have Internet Access on your development machine, please follow these instructions:
  1. From the Start menu, select Programs, select PowerTCP, select the PowerTCP product you downloaded, and then click License Registration.
  2. In the Dart License Registration dialog box, click Install.
  3. Under Option 2, enter your serial number in the Serial # field.
  4. Write down the number in the Key field.
  5. On a machine that has Internet access, log on to the Dart registration page (http://www.dart.com/register/).
  6. Enter all required information. The Key is the number written down in Step 4.
  7. Click Submit. A seven-digit registration code should appear.
  8. Back on the development machine (the machine on which Steps 1-4 were completed), enter the seven-digit registration number obtained in Step 7.
  9. Click Add.
  10. Click Exit.

After either of the two registration procedures are complete, your PowerTCP product appears in the Registered Tools field at the top of the registration form. Make sure you recompile your application after you register the PowerTCP product.

Re-installing a PowerTCP Product

The Key provided by the Registration Program is derived from a system number that is changed when the C: drive is reformatted. If you reformat your hard disk and need to re-install your PowerTCP product, follow the steps in Installing a Fully Licensed PowerTCP Product. A new Registration Number will be generated.

License Details

When you insert a PowerTCP component into a project, most development environments verify that the class is licensed for development. The component will work if you correctly entered the PowerTCP product Serial Number. See Installing a Fully Licensed PowerTCP Product for more information. When you compile your application, the development environment requests this Serial Number and embeds it in the application. When users run your application, the application submits this Serial Number to the class and the Serial Number is checked for validity. If the Serial Number is correct, then the application runs. This verification process occurs automatically.

Troubleshooting Licensing

For help troubleshooting licensing issues, see www.dart.com/support/lictrouble.asp.

If you have any problems registering your license, please contact Dart at 315-339-8040.

Related Sections

Using the Ftp Component
Provides links to walkthroughs pertaining to the Ftp component.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Trial Operation

PowerTCP Trials are now separate installs that do not interfere with already installed licensed products. PowerTCP Trial dlls contain ".Trial" in their filenames. For example, the trial version of "Dart.PowerTCP.Ftp.dll" is "Dart.PowerTCP.Ftp.Trial.dll". For questions concerning trial operation, contact the Sales Department at sales@dart.com.

Trial Notification in Development Mode

A trial notification screen will appear when the component is added to a form, or when a Project using the component is first opened. It will then re-appear once every hour or so.

Trial Notification During Run-Time

Trial components are fully-functional components. Applications compiled with trial components have a seven day lifespan. For the first three days, applications execute as if the trial component is licensed. In the remaining four days, applications show a trial reminder when started. After these four days (seven days since compilation), a trial expired message appears and applications no longer run.

ASP.NET applications running under IIS will not show the trial screen, but will cease to function after the seven day trial period.

The developer may Rebuild his Project at any time to reset the trial countdown.

The separate PowerTCP trial install will allow coexistence of licensed versions and trial versions of PowerTCP products. It is no longer necessary to uninstall a licensed product to test a newer trial version.

Once a licensed version is purchased, existing applications developed with trial dlls must be Rebuilt. Prior to Rebuilding, the trial dll should be replaced in References, and trial component(s) should be replaced on forms.

See License Installation for more information on product registration.

Related Sections

Using the Ftp Component
Provides links to walkthroughs pertaining to the Ftp component.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Deployment In ASP.NET

The FTP component can be deployed in an ASP.NET application.

To deploy a licensed ASP.NET Web Application or Web Service, follow these steps.

  1. Compile the ASP.NET application on a licensed development machine.
  2. If you are instantiating the component dynamically, be sure to include a licenses.licx file (see the "Creating The Licenses.licx File" topic for more information.
  3. Copy the contents of the bin folder and the ASP.NET source files (such as .aspx files) to the server that will be hosting the application.
  4. Create a virtual directory pointing to the folder containing the Web Application or Web Service.

Note: It is not necessary for the deployment server to be licensed or to contain a copy of a license in its registry.

Related Sections

Using the Ftp Component
Provides links to walkthroughs pertaining to the Ftp component.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Support Options

Our mission at Dart is to deliver high quality Internet connectivity solutions to Internet application developers. Our goal is to supplement these solutions with timely support resources that can help at many different levels.

Related Links (you have an active connection to the Internet to view these links).

Paid Support Options
Discusses the paid support options available.
Free Support Options
Provides access to free materials to help your development, including FAQS, online help files, tutorials, code snippets, online asp samples, and a free support forum.
Support Forum
Provides access to our support forum, monitored by our own development staff as time permits.
Dart Solutions
Discusses the custom development support offered by Dart Solutions.

Related Sections

Using the Ftp Component
Provides links to walkthroughs pertaining to the Ftp component.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


FTP Protocol Overview

This topic is intended to give a brief overview of the FTP protocol. More a more in-depth description, see RFC 959.

This topic covers:

  • Protocol Overview
  • Control Connection
  • Data Connection
  • Data Representation
  • Common Commands

Protocol Overview

The File Transfer Protocol (FTP) provides a standard method for transferring files between computers. You can get directory listings, retrieve files, upload files, and more. A client accesses files stored on a server. A server responds to clients, providing directory and file data. FTP uses both TCP and Telnet, differing from other protocols by using the following two connections:

  • Control connection using Telnet
  • Data connection using TCP

Control Connection

A control connection is formed to initiate a session. It is used for login, sending commands, and receiving information. The control connection utilizes the Telnet protocol and usually uses the FTP default port 21.

A control connection is generally made between a client and server. However, a client can control file transfers between two servers. See RFC 959 for detailed information about this and other advanced features.

During login, a user name and password must be sent. Many FTP servers support anonymous FTP where the user name is "anonymous" and the password is the user's email address.

After authentication, commands can be sent over the control connection. Typical commands are RETR (retrieve a file), STOR (upload a file), and QUIT (log off). For more information, refer to the RFC.

A server responds to commands with three-digit codes and descriptions across the control connection. Each digit has a different meaning, shown in the following tables (the code descriptions are taken directly from the RFC):

First-Digit Codes

Code | Description
1yz | Positive preliminary reply. The requested action is being initiated; expect another reply before proceeding with a new command. (The user-process of sending another command before the completion reply would be in violation of protocol; but server-FTP processes should queue any commands that arrive while a preceding command is in progress.) This type of reply can be used to indicate that the command was accepted and the user-process may now pay attention to the data connection, for implementations where simultaneous monitoring is difficult. The server-FTP process may send at most, one 1yz reply per command.
2yz | Positive completion reply. The requested action has been successfully completed. A new request may be initiated.
3yz | Positive intermediate reply. The command has been accepted, but the requested action is being held, pending receipt of further information. The user should send another command specifying this information. This reply is used in command sequence groups.
4yz | Transient negative completion reply. The command was not accepted and the requested action did not take place, but the error condition is temporary and the action may be requested again. The user should return to the beginning of the command sequence, if any. It is difficult to assign a meaning to transient, particularly when two distinct sites (Server- and User-processes) have to agree on the interpretation. Each reply in the 4yz category might have a slightly different time value, but the intent is that the user-process is encouraged to try again. A rule of thumb in determining if a reply fits into the 4yz or 5yz (Permanent Negative) category is that replies are 4yz if the commands can be repeated without any change in command form or in properties of the User or Server. For example, if the command is spelled the same with the same arguments used and the user does not change his file access or user name; then the server does not put up a new implementation.)
5yz | Permanent negative completion reply. The command was not accepted and the requested action did not take place. The User-process is discouraged from repeating the exact request (in the same sequence). Even some permanent error conditions can be corrected, so the human user may want to direct his User-process to reinitiate the command sequence by direct action at some point in the future (for example, after the spelling has been changed, or the user has altered his directory status).

Second-Digit Codes

Code | Description
x0z | Syntax. These replies refer to syntax errors, syntactically correct commands that don't fit any functional category, unimplemented or superfluous commands.
x1z | Information. These are replies to requests for information, such as status or help.
x2z | Connections. Replies referring to the control and data connections.
x3z | Authentication and accounting. Replies for the login process and accounting procedures.
x4z | Not Defined
x45z | File system. These replies indicate the status of the Server file system in relation to the requested transfer or other file system action.

Third-Digit Codes

The third-digit codes are more detailed. Refer to the RFC for these. Normally, a response consists of the code followed by an English description, as shown below:

200 PORT command successful.
150 Opening ASCII mode data connection for /bin/ls.
226 Transfer complete.
221 Goodbye.

Data Connection

A data connection is used when a:

  • Client sends a file to the server.
  • Server sends a file to the client.
  • Server sends a directory listing to the client.

    • Once a data connection has transferred its data, the connection is closed—it is dynamic and only one exists at a time. Data connection consists of the following steps:

    1. Client chooses an unused port number on which to accept the connection.
    2. Client waits for a connection on that port.
    3. Client uses the PORT command to send the port number to the server over the control connection.
    4. Client sends a transfer command (for example, STOR, RETR, or LIST).
    5. Server connects to the correct port using its local port 20.

    After the data connection is created, the file transfer or directory listing occurs and the connection closes.

    Data Representation

    Data can be transferred in different modes. File type, format control, structure, and transmission mode can all be controlled. However, only file type is commonly used; the other features are generally not changed.

    Of the following four options for file type, only ASCII and Image are commonly used:

    • ASCII. This is the default mode. Different computer systems implement new-line characters differently. Many UNIX systems use the ASCII character 13 (CR). Microsoft Windows uses ASCII character 13 followed by 10 (CR-LF). When ASCII mode is enabled, proper conversions are made between the server and the client. Note Use this mode only for text files. Using this mode on binary files cause corruption.
    • Image (binary). This sends an exact replica of the file across the connection. Use this for all binary files, which includes all executable programs and many document files.
    • EBCDIC. Not commonly used. It is an alternative way of transferring files between two EBCDIC systems.
    • Local file type. Not commonly used. It is a method of transferring data between two computers with different byte sizes.

    Common Commands

    The table below lists some common commands:

    Command | Description
ABOR | Cancel the previous command issued, and halt any data transfer in progress.
LIST filelist | List all files and directories in the directory.
PASS password | Send the user's password to the server during login.
PORT n1,n2,n3,n4,n5,n6 | Send the client's IP address in the first four arguments and the port in the fifth and sixth arguments.
QUIT | Log off the server.
RETR filename | Retrieve a file from the server.
STOR filename | Place a file on the server.
TYPE type | Specify the file type.
USER username | Send the user's name to the server.

    See Also

    Ftp Component Usage | Reference

    Send comments on this topic.

    © 2002 Dart Communications. All rights reserved.


Using The Ftp Component Overview

PowerTCP FTP for .NET is a complete suite of objects which enable the integration of FTP capability into any .NET application. Single file, multiple file, and stream transfers are fully supported, as is reading from and writing to the data connection. Asynchronous and synchronous methods are fully supported.

In This Section

Ftp Component Usage Overview
Discusses the basic theory and design decisions behind the Ftp component and associated objects.
Creating An Instance Of The Ftp Component Within Visual Studio .NET
Demonstrates how to create and use a component using Visual Studio .NET.
Adding The Ftp Component As A Reference
Demonstrates how to add the Ftp component as a reference using Visual Studio .NET.
Creating The Licenses.licx File
Demonstrates how to create the licenses.licx file. This in only necessary when adding the component as a reference.
Synchronous Vs Asynchronous Use
Discusses the benefits and uses for synchronous and asynchronous methods.

Related Sections

Storing Files Overview
Discusses how to store files to the server using the Ftp component.
Retrieving Files Overview
Discusses how to retrieve files from the server using the Ftp component.
Transferring Streams Overview
Discusses storing streams as files, and retrieving files as streams.
Accessing The Data Ftp.Connection
Discusses how to access the data connection for subsequent reading/writing.
Sending Commands Overview
Discusses how commands can be sent using the Ftp component.
Retrieving Listings Overview
Discusses how to retrieve listings using the Ftp component.
Using Secure Ftp
Discusses how to transfer files over SSL.
Using Events In PowerTcp
Discusses how to use events with the Ftp component, both using Visual Studio .NET and in other environments.
Session Management Overview
Discusses how sessions are maintained using the Ftp component.
Proxy Support Overview
Discusses special server implementations including proxy servers.
Using The Interactive Tools
Demonstrates how to use the included interactive tools to help make debugging and testing quicker and easier.
Reference
Provides a language/syntax reference for PowerTCP FTP for .NET.
Ftp Component Samples
Describes the samples that are installed with the Ftp component.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Ftp Component Usage Overview

PowerTCP FTP for .NET is designed to be an extremely flexible and powerful component-level implementation of the FTP protocol. High-level properties and methods provide quick code creation and ease-of use while access to lower-level properties and methods provide power and control.

The following discusses some of the characteristics of the Ftp component.

Automated Login: The Ftp component removes any login/logout complexity in your code by handling the login. Simply specify the FTP server and port, and the username and password for the server (if required) and any login resulting from any method call that requires communication with the server will occur transparently. If any properties change (for example, perhaps the port changes), login will occur transparently. The Ftp component will remain logged into the FTP server until the connection is explicitly closed by the user, or the Ftp component is destroyed.

Flexible File Transfer: The Ftp component enables the sending and receiving of a single file or multiple files with a single method call. Synchronous and asynchronous use is fully supported.

Flexible Stream Transfer: The Ftp component enables the transfer of streams as well. With a single method call, you can store a stream into a remote file or retrieve a remote file as a stream to use within your application. Again, synchronous and asynchronous use is fully supported.

Ability To Access The Data Connection: With the Ftp component, you have full control over the data connection. You can read from the data connection and you can write to the data connection. Synchronous and asynchronous use is fully supported.

Send Commands: Send any command with the Ftp component, including user-defined. Higher-level methods encapsulate the most common commands, while lower-level methods enable the sending of any custom command. Synchronous and asynchronous use is fully supported.

Proxy Support: The Ftp component has full proxy support built-in with the FtpProxy object. Set the properties of this object and proxy use is handled transparently. Also, if your FTP server expects a custom login sequence before use, the Ftp component allows connection with the FTP server after which you can send the required commands to login.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Creating An Instance Of The Ftp Component Using Visual Studio .NET

Although the Ftp component can be used in your preferred environment on any machine that has the .NET Framework installed, the recommended method is to use the Ftp component within the Visual Studio .NET environment.

To create an Ftp component within Visual Studio .NET, use the following steps:

  1. Start Visual Studio .NET.
  2. From the File menu, choose New, then choose Project.
  3. From the resulting dialog box, choose either Visual C# Projects or Visual Basic Projects then choose Windows Application. Specify a name and a location for the project, then click OK.
  4. Now add the Ftp component to the form. To do this, right-click on the ToolBox and choose Customize ToolBox (see the screen shot below). If the ToolBox is not visible, navigate to the View menu and choose ToolBox.

  5. From the resulting dialog box, choose the .NET Framework Components tab, then scroll until you find the Ftp component (see the screen shot below). Check the checkbox next to it and select OK.

  6. Now click the Ftp component icon on the ToolBox, and "drag" an instance of it onto the form. The Visual Studio .NET environment will automatically create and instantiate an instance of the Ftp component.
  7. Now make a quick application to test. Drag a button onto the form.
  8. Add the following code to the button "on-click" event handler.
    [C#]
ftp1.Server = "MyFtpServer"; // Substitute your server here.
ftp1.Username = "blah"; // Substitute your username here.
ftp1.Password = "mypass"; // Substitute your password here.

// Now execute a simple method. In this case we use GetDirectory to return the
// working directory. As long as Server, Username, and Password are set, login will
// occur transparently.
string dir;
try
{
   dir = ftp1.GetDirectory();
}
catch
{
   MessageBox.Show("Error");
   return;
}
MessageBox.Show(dir);
[Visual Basic]
Ftp1.Server = "MyFtpServer" ' Substitute your server here.
Ftp1.Username = "blah" ' Substitute your username here.
Ftp1.Password = "mypass" ' Substitute your password here.

' Now execute a simple method. In this case we use GetDirectory to return the
' working directory. As long as Server, Username, and Password are set, login will
' occur transparently.
Dim dir as string

Try
   dir = ftp1.GetDirectory()
Catch
   MessageBox.Show("Error");
   Exit Sub
End Try

MessageBox.Show(dir)
  9. Navigate to the Debug menu and choose Start. The app will compile and execute. Click the button and you should see your FTP server's default working directory in the MessageBox.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Adding The Ftp Component As A Reference Within Visual Studio .NET

When using Visual Studio .NET, the Ftp component can either be used as a component (see the topic Using The Ftp Component Within Visual Studio .NET for more information) or added as a reference. If you are using the Ftp component as a reference, there are a few extra steps you must take, namely:

  • You must instantiate your own event handlers.
  • You must create and add a licenses.licx file to the project.
The following steps illustrate how to add the Ftp component as a reference within Visual Studio .NET

To add the Ftp component as a reference within Visual Studio .NET, use the following steps:

  1. Start Visual Studio .NET.
  2. From the File menu, choose New, then choose Project.
  3. From the resulting dialog box, choose either Visual C# Projects or Visual Basic Projects then choose Windows Application. Specify a name and a location for the project, then click OK.
  4. The Ftp component must be added as a reference. To do this right-click the References folder in the Solution Explorer and choose Add Reference (see the screen shot below). If the Solution Explorer is not visible, navigate to the View menu and choose Solution Explorer.

  5. Now add the Ftp and component as a reference.
  6. Now you must add a licenses.licx file to the project. (See the topic Creating A Licenses.licx File for more information).
  7. Now make a quick application to test. Drag a button onto the form.
  8. Create an instance of the Ftp component within the button "on-click" event handler.
    [C#]
Dart.PowerTCP.Ftp.Ftp ftp1 = new Dart.PowerTCP.Ftp.Ftp();
[Visual Basic]
Dim Ftp1 as New Dart.PowerTCP.Ftp.Ftp();
  9. Add the following code to the button "on-click" event handler after the code to create the Ftp component.
    [C#]
ftp1.Server = "MyFtpServer"; // Substitute your server here.
ftp1.Username = "blah"; // Substitute your username here.
ftp1.Password = "mypass"; // Substitute your password here.

// Now execute a simple method. In this case we use GetDirectory to return the
// working directory. As long as Server, Username, and Password are set, login will
// occur transparently.
string dir;
try
{
   dir = ftp1.GetDirectory();
}
catch
{
   MessageBox.Show("Error");
   return;
}
MessageBox.Show(dir);
[Visual Basic]
Ftp1.Server = "MyFtpServer" ' Substitute your server here.
Ftp1.Username = "blah" ' Substitute your username here.
Ftp1.Password = "mypass" ' Substitute your password here.

' Now execute a simple method. In this case we use GetDirectory to return the
' working directory. As long as Server, Username, and Password are set, login will
' occur transparently.
Dim dir as string

Try
   dir = ftp1.GetDirectory()
Catch
   MessageBox.Show("Error");
   Exit Sub
End Try

MessageBox.Show(dir)
  10. Navigate to the Debug menu and choose Start. The application will compile and execute. Click the button and you should see your FTP server's default working directory in the MessageBox.
  11. Note: This example shows usage without events. If you use the Ftp component as a reference you will have to create your own event handlers. To do this, see the "Using Events When Using The Ftp Component As A Reference" topic.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Creating The Licenses.licx File

Note: If you are creating a component by dragging it from the toolbox, you do not need to create a licenses.licx file, as one will be created by the environment. These steps apply only if you are using a component as a reference, or from a non-Visual Studio .NET environment.

To create a licenses.licx file, use the following steps (This example demonstrates using the Ftp component).

  1. Start a new application in Visual Studio .NET and add the Ftp component as a reference.
  2. In the Solution Explorer, right-click the project name, choose Add, then Add New Item.
  3. From the resulting dialog box, choose Text File and name the file "licenses.licx". Click Open.
  4. Type the following in the licenses.licx file
    Dart.PowerTCP.Ftp.Ftp, Dart.PowerTCP.Ftp

    and save the file. You should now be able to compile and run a project that uses the Ftp component as a reference.

Note! Do not change the "Build Action" property of the licenses.licx file from its default value of "Embedded Resource."

Please Note: Any time changes are made to the license, the Project (not the Solution) must be rebuilt or license changes will not take effect.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Using A Component Outside of Visual Studio .NET

Compiling a project without using VS.NET takes a few extra steps. Use the following steps if you are compiling a project using a PowerTCP component outside of VS.NET (note, these steps demonstrate using the csc compiler).

To compile a project outside of VS.NET, use the following steps.

  1. First, create the licenses.licx file as described in Creating The Licenses.licx File.
  2. Compile this into a resource as follows:
    lc /target:mytest.exe /complist:licenses.licx /i:Dart.PowerTCP.Ftp.Dll
  3. Now compile the app using csc:
    csc mytest.cs /r:Dart.PowerTCP.Ftp.dll /res:mytest.p.exe.licenses

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Synchronous Versus Asynchronous Methods

The decision to use synchronous or asynchronous methods can be crucial and have an impact on the complexity of your code and the user experience.

The following lists discuss some of the characteristics of synchronous and asynchronous methods in PowerTCP.

Synchronous Methods

  • Are easier to implement and use than asynchronous.
  • Do not require an event to implement.
  • Results are returned directly from the method call.
  • Error handling occurs during the method call.

Asynchronous Methods

  • Occur on a new thread.
  • Are slightly more difficult to implement and use than synchronous.
  • Must have an event to handle the response.
  • Results are returned to the event handler.
  • Error handling occurs during the associated event.

Most applications written with the Ftp component will be synchronous. The reasons for this are not purely due to the ease-of-use of synchronous methods. Synchronous methods are ideal for automated processes that can execute a blocking method for a long period of time. In addition, synchronous methods can work well for interactive applications. The DoEvents property controls the processing of user interface messages while a synchronous method is executing. This means that while a synchronous method is executing, other portions of the application will be able to respond to events (for example, button or menu clicks).

Asynchronous methods, on the other hand, provide a great deal of power. When an asynchronous method is called, the method will execute on a thread separate from the calling thread. Such operation is useful when an action is time consuming and other code needs to execute without waiting for the intial operation to complete. In addition, the user interface will be most responsive when asynchronous methods are used.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Storing Files Overview

PowerTCP FTP for .NET provide a flexible implementation for storing files on a server. Whether you wish to store a single file, many files, or a stream, PowerTCP FTP for .NET makes integrating FTP file storage into your application easy. Synchronous and asynchronous use is fully supported, as is control over writing to the data stream.

In This Section

Storing Files Synchronously
Provides an overview for storing files synchronously. This is the easiest way to implement file storage in an application and is recommended for beginners.
Storing Files Asynchronously (Advanced Users)
Provides an overview for storing files asynchronously. This topic involves event usage, so it is recommended for more advanced users.

Related Sections

Retrieving Files
Describes how to retrieve files using PowerTCP FTP for .NET.
Stream Functionality Overview
Describes how to store and retrieve streams and read/write the data connection using PowerTCP FTP for .NET.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Storing Files Synchronously Overview

Synchronous file storage is the easiest way to store a file to an FTP server. Synchronous operation is simple because it is not necessary to implement events. The thread that calls the synchronous method will simply block until the file is stored to the server. If the DoEvents property is set to true, the UI will process events while the file is transferred.

In This Section

Storing A Single File Synchronously
Provides step-by-step instructions on storing a single file on the server.
Storing Multiple Files Synchronously
Provides step-by-step instructions on storing multiple files to the server.

Related Sections

Storing Files Asynchronously (Advanced Users)
Provides an overview for storing files asynchronously. This topic involves event usage, so it is recommended for more advanced users.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Storing A Single File Synchronously

Storing A File Synchronously

Using the Put method to store a single file demonstrates the simplest usage for storing files. Before using this method ,or any method of the Ftp component, the Server, Username, and Password properties must first be set. This provides for a transparent server login. After setting these properties the Put method can be called. This method returns an FtpFile object, which encapsulates information about the file transfer.

To use the Put method to store a single file on the server, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 1.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Create an FtpFile variable to encapsulate information about the file transfer.(optional)

    [Visual Basic, C#] The following code demonstrates creating an FtpFile object. Place this code directly after the code from step 3.

    [C#]
Dart.PowerTCP.Ftp.FtpFile file;
[Visual Basic]
Dim file As Dart.PowerTCP.Ftp.FtpFile
  5. Use the Ftp.Put method to store the file on the server. Login will transparently take place. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed. The Ftp.Put method returns an FtpFile object, which can be used to access data about the file transfer.

    [Visual Basic, C#] The following code demonstrates using Put to store a single file. The first parameter (localFileName) specifies the local file name and path of the file to be stored. The second parameter (remoteFileName) specifies the name and path of the file to be created on the server. This code will cause the Ftp component to attempt to store the file "C:\myfile.gif" on the server at "/home/myfile.gif". Place this code directly after the code from step 4.

    [C#]
file = ftp1.Put("C:\myfile.gif", "home/myfile.gif");
[Visual Basic]
file = Ftp1.Put("C:\myfile.gif", "home/myfile.gif")
  6. Access information about the transfer using the FtpFile object returned from the Ftp.Put method. (optional)

    [Visual Basic, C#] The following code demonstrates retrieving information from the FtpFile object returned from the Ftp.Put method. Place this code directly after the code from step 5.

    [C#]
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Data transferred " + file.Count);
[Visual Basic]
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Data transferred " + file.Count)
  7. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Storing Multiple Files Synchronously

Using the Put method to store multiple files demonstrates the simplest method for storing multiple files with a single method call. Before using this method, or any method of the Ftp component, the Server, Username, and Password properties must first be set. This provides for transparent server login during any method. After setting these properties, the Put method can then be called. Three parameters of this method, localRoot, searchPattern, and subDirectories give control over which files are uploaded. This method returns an array of FtpFile objects which encapsulate transfer information about the files.

To use the Put method to store multiple files on the server, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 1.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Create an FtpFile[] variable which will encapsulate information about the file transfers.(optional)

    [Visual Basic, C#] The following code demonstrates creating a variable for an array of FtpFile objects. Place this code directly after the code from step 3.

    [C#]
Dart.PowerTCP.Ftp.FtpFile[] files;
[Visual Basic]
Dim files() As Dart.PowerTCP.Ftp.FtpFile
  5. Use the Ftp.Put method to store the files on the server. Login will occur transparently. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed. The Ftp.Put method will return an array of FtpFile objects describing each file transfer.

    [Visual Basic, C#] The following code demonstrates using Ftp.Put to store multiple files. The first parameter (localRoot) specifies the directory on the client from which files will be copied. The second parameter (searchPattern ) specifies the search pattern (using wildcards) used to define which files are stored. The third parameter (remoteRoot) specifies the root on the server to which files will be stored. The fourth parameter (subDirectories) specifies whether directories under the directory specified will be included in the store. In this example, all files located in "C:\Files" will be uploaded to the directory "/home" of the FTP server. If there are any subdirectories under "C:\Files", they will not be included, as the subDirectories parameter is false. Place this code directly after the code from step 4.

    [C#]
files =  ftp1.Put("C:\\files", "*", "/home", false);
[Visual Basic]
files = Ftp1.Put("C:\files", "*", "/home", False)
    Note: Other options for the searchPattern parameter include "*.txt" to store only text files, or "file.*" to upload all files that are named "file".
  6. Access information about the transfer using the FtpFile objects returned from the Ftp.Put method. (optional)

    [Visual Basic, C#] The following code demonstrates retrieving info from the FtpFile objects returned from the Ftp.Put method. Place this code directly after the code from step 5.

    [C#]
foreach(Dart.PowerTCP.Ftp.FtpFile file in files)
       if (file.Exception ==   null)
   Debug.WriteLine(file.LocalFileName + " successfully stored");
[Visual Basic]
Dim file as Dart.PowerTCP.Ftp.FtpFile
For Each file In files
     if (file.Exception == Nothing)
   Debug.WriteLine(file.LocalFileName + " successfully stored.")
Next
  7. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Storing Files Asynchronously Overview (Advanced Users)

Asynchronous file storage is useful because communication and data transfer can occur without waiting for the action to complete before executing the next line of code. Such operation is useful when an operation is time consuming and other code needs to execute without waiting for the operation to complete. This is possible because when an asynchronous method is called execution occurs on a unique thread. When the asynchronous method is complete, an event is raised notifying the main thread of completion. Asynchronous methods are slightly more difficult to use than synchronous methods because it is necessary to implement events to handle completion notification.

In This Section

Storing A Single File Asynchronously (Advanced Users)
Provides step-by-step instructions on asynchronously storing a single file on the server.
Storing Multiple Files Asynchronously (Advanced Users)
Provides step-by-step instructions on asynchronously storing multiple files on the server.

Related Sections

Storing Files Synchronously
Provides an overview for storing files synchronously. Describes the easiest way to store a file.
Using Events In PowerTcp
Provides an overview for implementing events in PowerTCP. In order to use any asynchronous method, you should implement the appropriate event.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Storing A Single File Asynchronously

To store a single file asynchronously use the BeginPut method. This method stores a single file asynchronously with execution occurring on a new thread, thus allowing the next line of code to execute immediately. When the store is complete, the EndPut event will be raised, making accessible the FileEventArgs object encapsulating information about the transfer. Before you can call BeginPut (or any method of the Ftp component) the Server, Username, and Password properties must first be set. This provides for a transparent server login.

To use the BeginPut method to store a single file on the server asynchronously, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 2.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Add the code for the Ftp.BeginPut method which, when called, will begin execution on a new thread. Execution on the main thread will immediately continue. Login will occur transparently. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed.

    [Visual Basic, C#] The following code demonstrates calling an asynchronous Ftp.BeginPut. The first parameter (localFile) specifies the path and name of the local file to be stored. The second parameter (remoteFileName)specifies the path and name of the file to be created on the server. The third parameter (state) allows the passing of any object that you would like accessible in the Ftp.EndPut event. Place this code directly after the code from step 3.

    [C#]
ftp1.BeginPut("C:\myfile.gif", "myfile.gif", null);
[Visual Basic]
Ftp1.BeginPut("C:\myfile.gif", "myfile.gif", Nothing)
  5. Upon completion of the file store, the Ftp.EndPut event will be raised. In order to access this event, you must have a method "signed up" as the event handler. For more information about how to do this, see the topic Using Events In PowerTcp. Once you have the Ftp.EndPut event properly "signed up" to handle the response from the Ftp.BeginPut method, add the code to the event handler. When the event is raised, access information contained in the FileEventArgs object.

    [Visual Basic, C#] The following code demonstrates an event handler, including code to access the FileEventArgs object for information about the transfer. If any error occurred during the asynchronous operation, it would be returned in the FileEventArgs.Exception property. Check this first to find out the success/failure of the operation.

    [C#]
private void ftp1_EndPut(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
   if(e.Exception == null)
   {
      Debug.WriteLine("Successfully stored file " + e.File.LocalFileName);
      Debug.WriteLine("File now on server as " + e.File.RemoteFileName);
      Debug.WriteLine("Data transferred " + e.File.Count);
   }
   else
      Debug.WriteLine("Error: " + e.Exception.Message);
}
[Visual Basic]
Private Sub Ftp1_EndPut(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndPut

    If e.Exception Is Nothing then
       Debug.WriteLine("Successfully stored file " + e.File.LocalFileName)
       Debug.WriteLine("File now on server as " + e.File.RemoteFileName)
       Debug.WriteLine("Data transferred " + e.File.Count)
    Else
        Debug.WriteLine("Error: " + e.Exception.Message);
    End If

End Sub
  6. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Storing Multiple Files Asynchronously

To store multiple files asynchronously, use the BeginPut method. This method stores multiple files asynchronously with execution occurring on a new thread, thus allowing the next line of code to execute immediately. When the store is complete the EndPut event will be raised, making accessible the FileEventArgs object encapsulating information about the transferred files. Before using this method (or any method of the Ftp component) the Server, Username, and Password properties must first be set. This provides for transparent server login during any method.

To use the BeginPut method to store multiple files on the server asynchronously, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 2.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Add the code for the Ftp.BeginPut method which, when called will begin execution on a new thread. Execution on the main thread will immediately continue. Login will occur transparently. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed.

    [Visual Basic, C#] The following code demonstrates using Ftp.BeginPut to store multiple files. The first parameter specifies the directory on the client from which files will be stored. The second parameter specifies a search pattern (using wildcards) that defines which files are stored. The third parameter specifies the root on the server to which files will be stored. The fourth parameter specifies whether directories under the directory specified will be included in the store. The fifth parameter allows the passing of any object that you would like accessible in the Ftp.EndPut event. In this example, all files located in "C:\Files" will be uploaded to the directory "/home" of the FTP server. If there are any subdirectories under "C:\Files" they will not be included, as the fourth parameter is false. Place this code directly after the code from step 3.

    [C#]
ftp1.BeginPut("C:\\Files", "*", "/home", false, null);
[Visual Basic]
Ftp1.BeginPut("C:\Files", "*", "/home", False, Nothing)
  5. Upon completion of the store, the Ftp.EndPut event will be raised. In order to access this event, you must have a method "signed up" as the event handler. For more information about how to do this, see the topic Using Events In PowerTcp. Once you have the Ftp.EndPut event properly "signed up" to handle the response from the Ftp.BeginPut method, add the code to the event handler. When the event is raised, access information contained in the FileEventArgs object.

    [Visual Basic, C#] The following code demonstrates an event handler, including code to access the FileEventArgs object for information about the transfer. If any error occurred during the asynchronous operation, it would be returned in the FileEventArgs.Exception property. Check this first to find out the success/failure of the operation.

    [C#]
private void ftp1_EndPut(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
   if (e.Exception == null)
   {<

    BR >

       // Iterate through files collection and display info.
       foreach(Dart.PowerTCP.Ftp.FtpFile file in e.Files)
          Debug.WriteLine("Successfully put " + file.LocalFileName);
    }
    else
        Debug.WriteLine("Error " + e.Exception.Message);
}
[Visual Basic]
Private Sub Ftp1_EndPut(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndPut

   If e.Exception Is Nothing Then
      Dim file As Dart.PowerTCP.Ftp.FtpFile

      ' Iterate through files collection and display info.
      For Each file In e.Files
         Debug.WriteLine("Successfully Put " + file.LocalFileName)
      Next

   Else
      Debug.WriteLine("Error " + e.Exception.Message);
   End If

End Sub
  6. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Retrieving Files Overview

PowerTCP FTP for .NET provide a flexible implementation for getting files from a server. Whether you wish to retrieve a single file, many files, or a file as a stream, PowerTCP FTP for .NET makes integrating FTP file transfer capability into your application easy. Synchronous and asynchronous use is fully supported, as is control over reading from the data stream.

In This Section

Retrieving Files Synchronously
Provides an overview for retrieving files synchronously. This is the easiest way to implement file retrieval in an application and is recommended for beginners.
Retrieving Files Asynchronously (Advanced Users)
Provides an overview for retrieving files asynchronously. This topic involves event usage, so it is recommended for more advanced users.

Related Sections

Storing Files
Describes how to retrieve files using PowerTCP FTP for .NET.
Stream Functionality Overview
Describes how to store and retrieve streams and read/write the data connection using PowerTCP FTP for .NET.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Retrieving Files Synchronously Overview

Synchronous file retrieval is the easiest way to get a file from an FTP server. Synchronous operation is simple because it is not necessary to implement events. The thread that calls the synchronous method will simply block until the file is retrieved from the server. If the DoEvents property is set to true, the UI will process events while the file is transferred.

In This Section

Retrieving A Single File Synchronously
Provides step-by-step instructions on getting a single file from the server.
Retrieving Multiple Files Synchronously
Provides step-by-step instructions on getting multiple files from the server.

Related Sections

Retrieving Files Asynchronously (Advanced Users)
Provides an overview for getting files asynchronously. This topic involves event usage, so it is recommended for more advanced users.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Retrieving A Single File Synchronously

Using the Get method to retrieve a single file is the simplest usage of FTP file retrieval. Before using this method, or any method of the Ftp component, the Server, Username, and Password properties must first be set. This provides for transparent server login. After setting these properties, the Get method can then be called. This method returns an FtpFile object which encapsulates transfer information.

To use the Get method to retrieve a single file from the server, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 1.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Create an FtpFile variable which will encapsulate information about the file transfer. This variable will be initialized by any method that transfers files.(optional)

    [Visual Basic, C#] The following code demonstrates creating an FtpFile variable. Place this code directly after the code from step 3.

    [C#]
Dart.PowerTCP.Ftp.FtpFile file;
[Visual Basic]
Dim file As Dart.PowerTCP.Ftp.FtpFile
  5. Use the Ftp.Get method to get the file from the server. Login will occur transparently. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed. The Ftp.Get method returns an FtpFile object, which can be used to access data about the file transfer.

    [Visual Basic, C#] The following code demonstrates using Ftp.Get to a retrieve a single file. The first parameter (remoteFileName) specifies the remote file name and path of the file to be retrieved. The second parameter (localFileName) specifies the local name and path of the file to be created. This code will cause the Ftp component to attempt to get the file "/home/file1.txt" from the server and store it locally at "c:\files\file1.txt". Place this code directly after the code from step 4.

    [C#]
file = ftp1.Get("/home/file1.txt", "C:\\files\\file1.txt");
[Visual Basic]
file = Ftp1.Get("/home/file1.txt", "C:\files\file1.txt")
  6. Access information about the transfer using the FtpFile object returned from the Ftp.Get method. (optional)

    [Visual Basic, C#] The following code demonstrates retrieving info from the FtpFile object returned from the Ftp.Get method. Place this code directly after the code from step 5.

    [C#]
Debug.WriteLine("Successfully retrieved file " + file.RemoteFileName);
Debug.WriteLine("File now on local machine as " + file.LocalFileName);
Debug.WriteLine("Data transferred " + file.Count);
[Visual Basic]
Debug.WriteLine("Successfully retrieved file " + file.RemoteFileName)
Debug.WriteLine("File now on local machine as " + file.LocalFileName)
Debug.WriteLine("Data transferred " + file.Count)
  7. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Retrieving Multiple Files Synchronously

Using the Get method to get multiple files demonstrates the simplest method for retrieving multiple files with a single method call. Before using this method, or any method of the Ftp component, the Server, Username, and Password properties must first be set. This provides for transparent server login during any method. After setting these properties, the Get method can then be called. Three parameters of this method, remoteRoot, searchPattern, and subDirectories give control over which files are uploaded. This method returns an array of FtpFile objects which encapsulates transfer information about the files.

To use the Get method to retrieve multiple files from the server, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties, so login can transparently take place. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 1.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Create an FtpFile[] variable which will encapsulate information about the file transfers.(optional)

    [Visual Basic, C#] The following code demonstrates creating a variable for an array of FtpFile objects. Place this code directly after the code from step 3.

    [C#]
Dart.PowerTCP.Ftp.FtpFile[] files;
[Visual Basic]
Dim files() As Dart.PowerTCP.Ftp.FtpFile
  5. Use the Ftp.Get method to retrieve the files from the server. Login will occur transparently. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed. The Ftp.Get method will return an array of FtpFile objects describing each file transfer.

    [Visual Basic, C#] The following code demonstrates using Get to retrieve multiple files. The first parameter (remoteRoot) specifies the directory on the server from which files will be retrieved. The second parameter (searchPattern ) specifies the search pattern (using wildcards) used to define which files are retrieved. The third parameter (localRoot ) specifies the directory on the client to which files will be copied. The fourth parameter (subDirectories) specifies whether directories under the directory specified will be included. In this example, all files located in "/home/directory1/" will be downloaded to the directory "C:\Files". If there are any subdirectories under "/home/directory1" they will not be included, as the subDirectories parameter is false. Place this code directly after the code from step 4.

    [C#]
files = ftp1.Get("/home/directory1", "*", "C:\\Files", false);
[Visual Basic]
files = Ftp1.Get("/home/directory1", "*", "C:\Files", False)
    Note Other options for the searchPattern parameter include "*.txt" to retrieve only text files, or "file.*" to download all files that are named "file".
  6. Access information about the transfer using the FtpFile objects returned from the Ftp.Get method. (optional)

    [Visual Basic, C#] The following code demonstrates retrieving info from the FtpFile objects returned from the Get method. Place this code directly after the code from step 5.

    [C#]
foreach(Dart.PowerTCP.Ftp.FtpFile file in files)
       if (file.Exception == null)
      Debug.WriteLine(file.RemoteFileName + " successfully retrieved");
[Visual Basic]
Dim file as Dart.PowerTCP.Ftp.FtpFile
For Each file In files
       if (file.Exception == Nothing)
      Debug.WriteLine(file.RemoteFileName + " successfully retrieved.")
Next
  7. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Retrieving Files Asynchronously Overview (Advanced Users)

Asynchronous file storage is useful because communication and data transfer can occur with an FTP server without waiting for the action to complete before executing the next line of code. Such operation is useful when an operation is time consuming and other code needs to execute without waiting for the operation to complete. This is possible because when an asynchronous method is called, execution occurs on a unique thread. When the asynchronous method is complete, an event is raised, notifying the main thread of completion. Asynchronous methods are slightly more difficult to use than synchronous methods because it is necessary to implement events to handle completion notification.

In This Section

Retrieving A Single File Asynchronously (Advanced Users)
Provides step-by-step instructions on asynchronously getting a single file from the server.
Retrieving Multiple Files Asynchronously (Advanced Users)
Provides step-by-step instructions on asynchronously getting multiple files from the server.

Related Sections

Retrieving Files Synchronously
Provides an overview for retrieving files synchronously. Describes the easiest way to get a file.
Using Events In PowerTcp
Provides an overview for implementing events in PowerTCP. In order to use any asynchronous method, you should implement the appropriate event.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Retrieving A Single File Asynchronously

To retrieve a single file asynchronously, use the BeginGet method. This method retrieves a single file asynchronously with execution occurring on a new thread, thereby allowing your next line of code to execute immediately. When the file retrieval is complete, the EndGet event will be raised, making accessible the FileEventArgs object encapsulating information about the transfer. Before you can call BeginGet (or any method of the Ftp component) the Ftp.Ftp.Server, Username, and Password properties must first be set. This provides for transparent server login.

To use the BeginGet method to retrieve a single file from the server asynchronously, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 2.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Add the code for the Ftp.BeginGet method, which, when called, will begin execution on a new thread. Execution on the main thread will immediately continue. Login will occur transparently. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed.

    [Visual Basic, C#] The following code demonstrates calling an asynchronous Ftp.BeginGet. The first parameter (remoteFileName) specifies the path and name of the file to be retrieved. The second parameter (localFileName ) specifies the path and name of the file to be created, and the third parameter (state) allows the passing of any object that you would like accessible in the Ftp.EndGet event. Place this code directly after the code from step 3.

    [C#]
ftp1.BeginGet("myfile.gif", "C:\\Files\\myfile.gif", null);
[Visual Basic]
Ftp1.BeginGet("myfile.gif", "C:\Files\myfile.gif", Nothing)
  5. Upon completion of the file retrieval, the Ftp.EndGet event will be raised. In order to access this event, you must have a method "signed up" as the event handler. For more information about how to do this, see the topic Using Events In PowerTcp. Once you have the Ftp.EndGet event properly "signed up" to handle the response from the Ftp.BeginGet method, add the code to the event handler. When the event is raised, access information contained in the FileEventArgs object.

    [Visual Basic, C#] The following code demonstrates an event handler, including code to access the FileEventArgs object for information about the transfer. If any error occurred during the asynchronous operation, it would be returned in the FileEventArgs.Exception property. Check this first to find out the success/failure of the operation.

    [C#]
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
   if(e.Exception == null)
   {
      Debug.WriteLine("Successfully retrieved file " + e.File.RemoteFileName);
      Debug.WriteLine("File now on local machine as " + e.File.LocalFileName);
      Debug.WriteLine("Data transferred " + e.File.Count);
   }
   else
      Debug.WriteLine("Error: " + e.Exception.Message);
}
[Visual Basic]
Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

    If e.Exception Is Nothing then
       Debug.WriteLine("Successfully retrieved file " + e.File.RemoteFileName)
       Debug.WriteLine("File now on local machine as " + e.File.LocalFileName)
       Debug.WriteLine("Data transferred " + e.File.Count)
    Else
        Debug.WriteLine("Error: " + e.Exception.Message);
    End If

End Sub
  6. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Retrieving Multiple Files Asynchronously

To retrieve multiple files asynchronously, use the BeginGet method. This method retrieves multiple files asynchronously, with execution occurring on a new thread, allowing the next line of code to execute immediately. When the retrieval is complete, the EndGet event will be raised, making accessible the FileEventArgs object encapsulating information about the transferred files. Before using this method, or any method of the Ftp component, the Server, Username, and Password properties must first be set. This provides for transparent server login during any method.

To use the BeginGet method to store multiple files on the server asynchronously, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 2.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Add the code for the Ftp.BeginGet method which, when called, will begin execution on a new thread. Execution on the main thread will immediately continue. Login will occur transparently. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed.

    [Visual Basic, C#] The following code demonstrates using Ftp.BeginGet to retrieve multiple files. The first parameter (remoteRoot) specifies the directory on the server from which files will be retrieved. The second parameter (searchPattern ) specifies a search pattern (using wildcards) that defines which files are retrieved. The third parameter (localRoot ) specifies the directory on the client to which files will be downloaded. The fourth parameter (subDirectories) specifies whether directories under the directory specified will be included in the file retrieval. The fifth parameter (state) allows the passing of any objects that you would like accessible in the Ftp.EndGet event. In this example, all files located in "/home/directory1" will be downloaded to the directory "C:\Files". If there are any subdirectories under "C:\Files" they will not be included, as the subDirectories parameter is false. Place this code directly after the code from step 3.

    [C#]
ftp1.BeginGet("/home/directory1", "*", "C:\\Files\\", false, null);
[Visual Basic]
Ftp1.BeginGet("/home/directory1", "*", "C:\Files\", False, Nothing)
  5. Upon completion of the file retrieval, the Ftp.EndGet event will be raised. In order to access this event, you must have a method "signed up" as the event handler. For more information about how to do this, see the topic Using Events In PowerTcp. Once you have the Ftp.EndGet event properly "signed up" to handle the response from the Ftp.BeginGet method, add the code to the event handler. When the event is raised, access information contained in the FileEventArgs object.

    [Visual Basic, C#] The following code demonstrates an event handler, including code to access the FileEventArgs object for information about the transfer. If any error occurred during the asynchronous operation, it would be returned in the FileEventArgs.Exception property. Check this first to find out the success/failure of the operation.

    [C#]
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
    if(e.Exception == null)
    {
       // Iterate through files collection and display info.
       foreach(Dart.PowerTCP.Ftp.FtpFile file in e.Files)
          Debug.WriteLine("Successfully got " + file.LocalFileName);
    }
    else
        Debug.WriteLine("Error " + e.Exception.Message);
}
[Visual Basic]
Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

   If e.Exception Is Nothing Then
      Dim file As Dart.PowerTCP.Ftp.FtpFile

      ' Iterate through files collection and display info.
      For Each file In e.Files
         Debug.WriteLine("Successfully got " + file.LocalFileName)
      Next

   Else
      Debug.WriteLine("Error " + e.Exception.Message);
   End If

End Sub
  6. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Stream Functionality Overview

FTP for .NET provide a number of options for using streams instead of simple disk to disk transfers. Using the Ftp component you can store/retrieve streams or open data streams for reading/writing directly to/from the server.

There is a distinction between transferring streams and reading/writing to the data connection. For example, take the case of retrieving a file as a stream versus reading the same file over the data connection. Although the Get and BeginGet methods are both overloaded to handle both stream transfer and reading from the data connection, this is where the similarity ends. To illustrate this point, examine the following table, which shows the differences between retrieving a file as a stream and reading from the data connection, (for simplicity only the synchronous versions are shown here):

 | Retrieving A Stream | Reading The Data Connection
Method Used (Synchronous) | Get method | Get method
Values Passed Into The Method | A string representing the file to retrieve and a stream object to be filled with the file data. | A string representing the file to retrieve and a long representing the offset to begin reading this file.
Values Returned From The Method | An FtpFile object describing the file transfer. | A SegmentedStream object to use to read the data connection.
Status Of The Data Connection After The Method Completes | Closed, and the stream object contains the transferred file. | Connected, and the stream object needs to be read to get the transferred file (this is the most efficient way to download a file directly into your memory buffer).
Handling The Returned Data | Access the FtpFile object to get such information as bytes transferred. Access the file itself by using the Stream object. | Use the SegmentedStream object to read the data from the data connection. Close the SegmentedStream after reading the data you need by using the AbortTransfer method and closing the stream (this aborts the file transfer before it is complete), or let the Ftp component close the stream when 0 bytes are returned from reading the stream.

In This Section

Storing Files
Describes how to store files using PowerTCP FTP for .NET.
Retrieving Files
Describes how to retrieve files using PowerTCP FTP for .NET.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Transferring Streams Overview

PowerTCP FTP for .NET have a great deal of functionality for handling streams. Using PowerTCP FTP for .NET, you can store a MemoryStream as a file on the server and retrieve a file from the server as a MemoryStream, thus eliminating the need for temporary files. It is also possible to read/write directly to the data connection. This topic, and related subtopics, discuss retrieving files as streams and storing streams as files.

In This Section

Transferring Streams Synchronously
Provides an overview for transferring streams synchronously. This is the easiest way to implement stream transfer and is recommended for beginners.
Transferring Streams Asynchronously (Advanced Users)
Provides an overview for transferring streams asynchronously. This topic involves event usage, so it is recommended for more advanced users.

Related Sections

Storing Files
Describes how to store files using PowerTCP FTP for .NET.
Retrieving Files
Describes how to retrieve files using PowerTCP FTP for .NET.
Reading/Writing To The Data Ftp.Connection
Describes how to directly read from and write to the data connection using PowerTCP FTP for .NET.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Transferring Streams Synchronously Overview

Synchronous stream transfers are the easiest way to store or retrieve streams in an application. Synchronous operation is simple because it is not necessary to implement events. The thread that calls the synchronous method will simply block until the file data is received from the server. If the DoEvents property is set to true, the UI will process events while the file is transferred.

In This Section

Storing A Stream Synchronously
Provides step-by-step instructions on storing a stream as a file on the server.
Retrieving A File As A Stream Synchronously
Provides step-by-step instructions on retrieving a file as a stream within your application.

Related Sections

Transferring Streams Asynchronously (Advanced Users)
Provides an overview for transferring streams asynchronously. This topic involves event usage, so it is recommended for more advanced users.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Storing A Stream As A File Synchronously

Using the Put method to store a stream demonstrates the simplest usage for storing streams. The intended usage is to create a stream and fill it with data within your application, then call the Put method. The stream will be uploaded as a file to your FTP server.

Before using this method, or any method of the Ftp component, the Server, Username, and Password properties must first be set. This provides for transparent server login. After setting these properties, the Put method can be called. This method returns an FtpFile object, which encapsulates information about the file transfer.

To use the Put method to store a stream on the server, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties, so login can transparently take place. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 1.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Create an FtpFile variable which will encapsulate information about the file transfer. This variable will be initialized by any method that transfers files. (optional)

    [Visual Basic, C#] The following code demonstrates creating an FtpFile object. Place this code directly after the code from step 3.

    [C#]
Dart.PowerTCP.Ftp.FtpFile file;
[Visual Basic]
Dim file As Dart.PowerTCP.Ftp.FtpFile
  5. Create a stream to store. A good stream for this example is a MemoryStream (contained in the System.IO namespace) because it is intended to encapsulate data stored in memory, reducing the need for temporary files in an application.

    [Visual Basic, C#] The following code demonstrates creating a MemoryStream object. Place this code directly after the code from step 4.

    [C#]
System.IO.MemoryStream stream1 = new System.IO.MemoryStream();
[Visual Basic]
Dim stream1 As New System.IO.MemoryStream()
  6. Now add some data to the stream. First create a byte array which will hold data, then write this data to the stream.

    [Visual Basic, C#] The following code demonstrates creating a byte array, adding data to this array, then writing this to the stream created in step 5. The data is encoded from a string to a byte array using System.Text.Encoding.ASCII.GetBytes(). Place this code directly after the code from step 5.

    [C#]
byte[] data = System.Text.Encoding.ASCII.GetBytes("Some data");
stream1.Write(data, 0, data.Length);
[Visual Basic]
Dim data() As Byte
data = System.Text.Encoding.ASCII.GetBytes("Some data")
stream1.Write(data, 0, data.Length)
  7. Use the Ftp.Put method to store the stream to the server. Login will transparently take place. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed. The Ftp.Put method returns an FtpFile object which can be used to access data about the stream transfer.

    [Visual Basic, C#] The following code demonstrates using Ftp.Put to store a stream. The first parameter (localStream) specifies the stream object containing the data to be stored. The second parameter (remoteFileName) specifies the name and path of the file to be created on the server. This code will cause the Ftp component to attempt to store the stream stream1 on the server in the default working directory under the name "filefromstream.txt". Place this code directly after the code from step 6.

    [C#]
file = ftp1.Put(stream1, "filefromstream.txt");
[Visual Basic]
file = Ftp1.Put(stream1, "filefromstream.txt")
  8. Access information about the transfer using the FtpFile object returned from the Ftp.Put method. (optional)

    [Visual Basic, C#] The following code demonstrates retrieving info from the FtpFile object returned from the Ftp.Put method. In this case FtpFile.LocalFileName will be null because the data only existed in memory. FtpFile.RemoteFileName will contain the name of the file on the server. Place this code directly after the code from step 7.

    [C#]
Debug.WriteLine("Stream now on server as " + file.RemoteFileName);
Debug.WriteLine("Data transferred " + file.Count);
[Visual Basic]

Debug.WriteLine("Stream now on server as " + file.RemoteFileName)
Debug.WriteLine("Data transferred " + file.Count)
  9. Compile and run the application.
  10. Retrieve the file "filefromstream.txt" and open it. It should say:
    Some data

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Retrieving A File As A Stream Synchronously

Using the Get method is the easiest way to retrieve a file as a stream. The intended usage is to create a stream and pass it into the Get method. When the method returns the stream will contain the data from the file.

Before using this method, or any method of the Ftp component, the Server, Username, and Password properties must first be set. This provides for transparent server login. After setting these properties, the Get method can then be called. This method returns an FtpFile object which encapsulates file transfer information.

To use the Get method to retrieve a file from the server as a stream, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property as this property defaults to 21, the well-known port for FTP. Of course if your server is operating at a non-standard port, this property can be explicitly set.

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 2.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Create a stream to hold the data from the retrieved file. A good stream for this example is a MemoryStream because it is intended to encapsulate data stored in memory, reducing the need for temporary files in an application.

    [Visual Basic, C#] The following code demonstrates creating a MemoryStream object. Place this code directly after the code from step 4.

    [C#]
System.IO.MemoryStream stream1 = new System.IO.MemoryStream();
[Visual Basic]
Dim stream1 As New System.IO.MemoryStream()
  5. Create an FtpFile variable which will encapsulate information about the file transfer. This variable will be initialized by any method that transfers files. (optional)

    [Visual Basic, C#] The following code demonstrates creating an FtpFile variable. Place this code directly after the code from step 4.

    [C#]
Dart.PowerTCP.Ftp.FtpFile file;
[Visual Basic]
Dim file As Dart.PowerTCP.Ftp.FtpFile
  6. Use the Ftp.Get method to get the file from the server. Be sure to pass in the stream created in step 5. Login will occur transparently. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed. The Ftp.Get method returns an FtpFile object, which can be used to access data about the stream transfer.

    [Visual Basic, C#] The following code demonstrates using Ftp.Get to a retrieve a file as a stream. The first parameter (remoteFileName) specifies the remote file name and path of the file to be retrieved. The second parameter (localStream ) specifies the stream object which will contain the file data retrieved. This code will cause the Ftp component to attempt to get the file "file1.txt" from the server and store it in the stream stream1. Place this code directly after the code from step 5.

    [C#]
file = ftp1.Get("file1.txt", stream1);
[Visual Basic]
file = ftp1.Get("file1.txt", stream1)
  7. Access information about the transfer using the FtpFile object returned from the Ftp.Get method. (optional)

    [Visual Basic, C#] The following code demonstrates retrieving info from the FtpFile object returned from the Ftp.Get method. Place this code directly after the code from step 5.

    [C#]
Debug.WriteLine("Successfully retrieved file " + file.RemoteFileName);
Debug.WriteLine("Data transferred " + file.Count);
[Visual Basic]
Debug.WriteLine("Successfully retrieved file " + file.RemoteFileName)
Debug.WriteLine("Data transferred " + file.Count)
  8. Add code to display the file data.

    [Visual Basic, C#] The following code displays the data contained within the stream returned from the Ftp.Get method. First, create a byte array the size of the stream length. Reset the stream position, then read the data into the byte array. Finally, display the data from the file.

    [C#]
byte[] data = new byte[stream1.Length];
stream1.Position = 0;
stream1.Read(data, 0, (int)stream1.Length);
Debug.WriteLine("File data: " + System.Text.Encoding.ASCII.GetString(data));
[Visual Basic]
Dim data(stream1.Length) As Byte
stream1.Position = 0
stream1.Read(data, 0, stream1.Length)
Debug.WriteLine("File data: " + System.Text.Encoding.ASCII.GetString(data))
    Note: For best display, choose a small ASCII file for this walkthrough.
  9. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Transferring Streams Asynchronously Overview (Advanced Users)

Asynchronous stream transfer is useful because communication and data transfer occur with without waiting for the action to complete before executing the next line of code. Such operation is useful when an operation is time consuming and other code needs to execute without waiting for the operation to complete. This is possible because when an asynchronous method is called execution occurs on a unique thread. When the asynchronous method is complete an event is raised, notifying the main thread of completion. Asynchronous methods are slightly more difficult to use than synchronous methods because it is necessary to implement events to handle completion notification.

In This Section

Storing A Stream As A File Asynchronously (Advanced Users)
Provides step-by-step instructions on asynchronously storing a stream as a file on the server.
Retrieving A File As A Stream Asynchronously (Advanced Users)
Provides step-by-step instructions on asynchronously retrieving a file as a stream.

Related Sections

Transferring Streams Synchronously
Provides an overview for transferring streams asynchronously. This topic describes the easiest way to store a stream.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Storing A Stream As A File Asynchronously

To store a stream as a file asynchronously, use the BeginPut method. This method allows storing of a stream asynchronously (created as a file on the server), with execution occurring on a new thread, allowing the next line of code to execute immediately. When the store is completed, the EndPut event will be raised, making accessible the FileEventArgs object encapsulating information about the transfer. The intended usage is for you to create a stream and fill it with data within your application, then pass it to the BeginPut method. The stream will be asynchronously uploaded to your FTP server as a file.

Before you can call BeginPut (or any method of the Ftp component) the Server, Username, and Password properties must first be set. This provides for transparent server login.

To use the BeginPut method to store a stream on the server as a file asynchronously, use the following steps.

  1. To use the BeginPut method to store a stream on the server as a file asynchronously, use the following steps.

    1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
    2. Add a button to the form.
    3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties, so login can transparently take place. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

      [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 2.

      [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
    4. Create a stream to store. A good stream for this example is a MemoryStream (contained in the System.IO namespace) because it is intended to use memory only as a backing store.

      [Visual Basic, C#] The following code demonstrates creating a MemoryStream object. Place this code directly after the code from step 4.

      [C#]
System.IO.MemoryStream stream1 = new System.IO.MemoryStream();
[Visual Basic]
Dim stream1 As New System.IO.MemoryStream()
    5. Now add some data to the stream. First create a byte array which will hold data, then write this data to the stream.

      [Visual Basic, C#] The following code demonstrates creating a byte array, adding data to this array, then writing this to the stream created in step 5. The data is encoded from a string to a byte array using System.Text.Encoding.ASCII.GetBytes(). Place this code directly after the code from step 5.

      [C#]
byte[] data = System.Text.Encoding.ASCII.GetBytes("Some data");
stream1.Write(data, 0, data.Length);
[Visual Basic]
Dim data() As Byte
data = System.Text.Encoding.ASCII.GetBytes("Some data")
stream1.Write(data, 0, data.Length)
    6. Add the code for the Ftp.BeginPut method, which, when called, will begin execution on a new thread. Execution on the main thread will immediately continue. Login will occur transparently. The Ftp component will stay logged in to the server until either the Ftp.Close or Abort method is called, or until the Ftp component is destroyed.

      [Visual Basic, C#] The following code demonstrates calling an asynchronous Ftp.BeginPut. The first parameter (localStream) specifies the stream object filled with data to be stored, the second parameter (remoteFileName) specifies the path and name of the file to be created on the server, and the third parameter (state) allows the passing of any object that you would like accessible in the Ftp.EndPut event. Place this code directly after the code from step 6.

      [C#]
ftp1.BeginPut(stream1, "myfile.txt", null);
[Visual Basic]
Ftp1.BeginPut(stream1, "myfile.txt", Nothing)
    7. Upon completion of the store, the Ftp.EndPut event will be raised. In order to access this event, you must have a method "signed up" as the event handler. For more information about how to do this, see the topic Using Events In PowerTcp. Once you have the Ftp.EndPut event properly "signed up" to handle the response from the Ftp.BeginPut method, add the code to the event handler. When the event is raised, access information contained in the FileEventArgs object.

      [Visual Basic, C#] The following code demonstrates an event handler, including code to access the FileEventArgs object for information about the stream transfer. If any error occurred during the asynchronous operation, it would be returned in the FileEventArgs.Exception property. Check this first to find out the success/failure of the operation.

      [C#]
private void ftp1_EndPut(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
   if(e.Exception == null)
   {
      Debug.WriteLine(e.File.RemoteFileName + " created on server.");
      Debug.WriteLine(e.File.Count + " bytes transferred.");
   }
   else
      Debug.WriteLine("Error: " + e.Exception.Message;
}
[Visual Basic]
Private Sub Ftp1_EndPut(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndPut

    If e.Exception Is Nothing Then
       Debug.WriteLine(e.File.RemoteFileName + "created on server.")
       Debug.WriteLine(e.File.Count + " bytes transferred.")
    Else
        Debug.WriteLine("Error: " + e.Exception.Message);
    End If

End Sub
    8. Compile and run the application.

    See Also

    Ftp Component Usage | Reference

    Send comments on this topic.

    © 2002 Dart Communications. All rights reserved.


Retrieving A File As A Stream Asynchronously

To retrieve a file as a stream asynchronously, use the BeginGet method. This method retrieves a file as a stream asynchronously, with execution occurring on a new thread, allowing your next line of code to execute immediately. When the file retrieval is completed, the EndGet event will be raised, making accessible the FileEventArgs object encapsulating information about the transfer. The intended usage is to create an empty stream, and pass it into the BeginGet method. When the operation completes, the stream will contain the data from the file.

Before you can call BeginGet (or any method of the Ftp component) the Server, Username, and Password properties must first be set. This provides for transparent server login.

To use the BeginGet method to retrieve a single file from the server asynchronously, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties, so login can transparently take place. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 2.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Create a stream to hold the data from the retrieved file. A good stream for this example is a MemoryStream because it is intended to use memory only as a backing store.

    [Visual Basic, C#] The following code demonstrates creating a MemoryStream object. Place this code directly after the code from step 4.

    [C#]
System.IO.MemoryStream stream1 = new System.IO.MemoryStream();
[Visual Basic]
Dim stream1 As New System.IO.MemoryStream()
  5. Add the code for the Ftp.BeginGet method, which, when called, will begin execution on a new thread. Execution on the main thread will immediately continue. Login will occur transparently. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed.

    [Visual Basic, C#] The following code demonstrates calling an asynchronous Ftp.BeginGet. The first parameter (remoteFileName) specifies the path and name of the file to be retrieved. The second parameter (localStream ) specifies the stream object which will be filled with file data, and the third parameter (state) allows the passing of any object that you would like accessible in the Ftp.EndGet event. Place this code directly after the code from step 3.

    [C#]
ftp1.BeginGet("myfile.txt", stream1, null);
[Visual Basic]
Ftp1.BeginPut("myfile.txt", stream1, Nothing)
  6. Upon completion of the file retrieval, the Ftp.EndGet event will be raised. In order to access this event, you must have a method "signed up" as the event handler. For more information about how to do this, see the topic Using Events In PowerTcp. Once you have the Ftp.EndGet event properly "signed up" to handle the response from the Ftp.BeginGet method, add the code to the event handler. When the event is raised, access information contained in the FileEventArgs object.

    [Visual Basic, C#] The following code demonstrates an event handler, including code to access the FileEventArgs object for information about the transfer. If any error occurred during the asynchronous operation, it would be returned in the FileEventArgs.Exception property. Check this first to find out the success/failure of the operation. If all went well, display the data from the stream. Do this by creating a byte array, resetting the stream position, and reading the data into the byte array.

    [C#]
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
   if(e.Exception == null)
   {
     byte[] data = new byte[stream1.Length];
    stream1.Position = 0;
    stream1.Read(data, 0, (int)stream1.Length);
    Debug.WriteLine("File data: " + System.Text.Encoding.ASCII.GetString(data));
   }
   else
      Debug.WriteLine("Error: " + e.Exception.Message);
}
[Visual Basic]
Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

    If e.Exception Is Nothing then
       Dim data(stream1.Length) As Byte
       stream1.Position = 0
       stream1.Read(data, 0, stream1.Length)
       Debug.WriteLine("File data: " + System.Text.Encoding.ASCII.GetString(data))
    Else
        Debug.WriteLine("Error: " + e.Exception.Message);
    End If

End Sub
  7. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Reading/Writing To The Data Connection Overview

Accessing The Data Connection Overview

PowerTCP FTP for .NET have a great deal of functionality for handling streams. Using the Ftp component, you can read directly from and write directly to the data connection. You can also store a stream to a file on the server and retrieve a file from the server as a stream, eliminating the need for temporary files. This topic (and related subtopics) discuss reading from and writing to the data connection.

In This Section

Synchronous Access To The Data Ftp.Connection
Provides an overview for synchronously accessing the data connection. This is the easiest way to access the data connection for reading/writing and is recommended for beginners.
Asynchronous Access To The Data Connection (Advanced Users)
Provides an overview for asynchronously accessing the data connection. This topic involves event usage, so it is recommended for more advanced users.

Related Sections

Storing Files
Describes how to store files using PowerTCP FTP for .NET.
Retrieving Files
Describes how to retrieve files using PowerTCP FTP for .NET.
Transferring Streams
Describes how to store and retrieve streams using PowerTCP FTP for .NET.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Reading/Writing The Data Connection Synchronously

Accessing The Data Connection Synchronously

The easiest way to access the data connection is synchronously. Synchronous operation is simple because it is not necessary to implement events. The thread that calls the synchronous method will simply block until the data connection is established. If the DoEvents property is set to true, the UI will process events while the file is transferred.

In This Section

Accessing The Data Connection Synchronously For Writing
Provides step-by-step instructions on accessing the data connection for writing.
Accessing The Data Connection Synchronously For Reading
Provides step-by-step instructions on accessing the data connection for reading.

Related Sections

Accessing The Data Connection Asynchronously (Advanced Usage)
Provides an overview for accessing the data connection asynchronously. This topic involves event usage, so it is recommended for more advanced users.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Reading From The Data Connection Synchronously

Accessing The Data Connection Synchronously For Reading

Use the Get method to establish a data connection for reading. The Get method returns a SegmentedStream object that is used to read from the data connection. When you are finished reading the file, the Ftp component will close the connection. If you do not wish to read the entire fire, you must call the AbortTransfer and Close methods to close the connection.

Before using this method (or any method of the Ftp component) the Server, Username, and Password properties must first be set. This provides for transparent server login. After setting these properties, the Get method can then be called.

To use the Get method to read from the data connection, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 2.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Create a SegmentedStream variable to hold the return value from the Ftp.Get method which will be used to read from the data connection.

    [Visual Basic, C#] The following code demonstrates creating a SegmentedStream object. Place this code directly after the code from step 3.

    [C#]
Dart.PowerTCP.Ftp.SegmentedStream sstream;
[Visual Basic]
Dim sstream As Dart.PowerTCP.Ftp.SegmentedStream
  5. Call the Ftp.Get method, passing in the name of the remote file and the offset to begin reading from this file.

    [Visual Basic, C#] The following code demonstrates using the Ftp.Get method to open a stream to read from the data connection. The first parameter, remoteFileName, specifies the file on the server to which a data connection will be established. The second parameter, restartMarker, specifies the location in this file to begin reading. Place this code directly after the code from step 4.

    [C#]
sstream = ftp1.Get("myfile.txt", 0);
[Visual Basic]
sstream = ftp1.Get("myfile.txt", 0)
  6. Now use the SegmentedStream object to synchronously read some data (asynchronous methods are also available). There are many options here. For example, the entire file can be read and used, or only a portion. For the sake of simplicity, this walkthrough will demonstrate a non-real world example of simply reading a few bytes from the stream. This may be useful if you want to determine file type (maybe by looking at tags or headers encoded within the file).

    [Visual Basic, C#] The following code will read up to 128 bytes from the stream. Place it after the code from step 5.

    [C#]
// Create a buffer to read data into
byte[] buffer = new byte[128];
// Read up to 128 bytes into the buffer.
sstream.Read(buffer,0, 128);
[Visual Basic]
' Create a buffer to read data into
byte() buffer = new byte(128)
' Read up to 128 bytes into the buffer.
sstream.Read(buffer,0, 128)
  7. When you are done reading from the file, close the data connection by using the Ftp.AbortTransfer and SegmentedStream.Close methods.

    [Visual Basic, C#] The following code demonstrates closing the data connection when you are done reading. Place this code directly after the code from step 7.

    [C#]
ftp1.AbortTransfer();
    sstream.Close();
[Visual Basic]
Ftp1.AbortTransfer()
    sstream.Close()
  8. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Writing To The Data Connection Synchronously

Accessing The Data Connection Synchronously For Writing

Use the Put method to establish a data connection for writing. The Put method returns a SegmentedStream object that is used to write to the data connection. When you are finished writing the file, use the Close method to close the connection.

Before using this method (or any method of the Ftp component) the Server, Username, and Password properties must first be set. This provides for transparent server login. After setting these properties the Put method can be called.

To use the Put method to write to the data connection, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 2.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Create a SegmentedStream variable for storing the return value from the Ftp.Put method.

    [Visual Basic, C#] The following code demonstrates creating a SegmentedStream variable. Place this code directly after the code from step 3.

    [C#]
Dart.PowerTCP.Ftp.SegmentedStream sstream;
[Visual Basic]
Dim sstream As Dart.PowerTCP.Ftp.SegmentedStream
  5. Call the Ftp.Put method, passing in the name of the remote file and the offset to begin writing to this file. If the file does not exist, it will be created on the server.

    [Visual Basic, C#] The following code demonstrates using the Ftp.Put method to open a stream to write to the data connection. The first parameter, remoteFileName, specifies the name of the file to be written to on the server. The second parameter, restartMarker, specifies the location in this file to begin writing. The file "mynewfile.txt" will be created on the server. Place this code directly after the code from step 4.

    [C#]
sstream = ftp1.Put("mynewfile.txt", 0);
[Visual Basic]
sstream = ftp1.Put("mynewfile.txt", 0)
  6. Now use the SegmentedStream object to write some data to the file (asynchronous methods are also available) . The SegmentedStream object supports writing both byte arrays and strings to the stream. For simplicity, this walkthrough will demonstrate writing a string.

    [Visual Basic, C#] The following code demonstrates writing a string to the newly created file on the server. After this method executes, the file on the server will contain the text "Some data. ". Place this code directly after the code from step 5.

    [C#]
sstream.Write("Some data. ");
[Visual Basic]
sstream.Write("Some data. ")
  7. Write a couple of more times to the file on the server. The data connection is maintained until you close it.

    [Visual Basic, C#] The following code demonstrates writing more data to the file on the server. Place this code directly after the code from step 6.

    [C#]
sstream.Write("Some more data. ");
sstream.Write("This is all of the data. ");
[Visual Basic]
sstream.Write("Some more data. ")
sstream.Write("This is all of the data. ")
  8. When you are done writing to the file, close the SegmentedStream object. The file "mynewfile.txt" will exist complete on the server.

    [Visual Basic, C#] The following code demonstrates closing the data connection when you are dome writing. Place this code directly after the code from step 7.

    [C#]
sstream1.Close();
[Visual Basic]
sstream1.Close()
  9. Compile and run the application.
  10. Retrieve the file "mynewfile.txt" and open it. It should say:
    Some data. Some more data. This is all of the data.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Reading/Writing To The Data Connection Asynchronously

Accessing The Data Connection Asynchronously

Asynchronous establishment of the data connection is useful because it allows for communication and data transfer to occur with an FTP server without waiting for the action to complete before executing the next line of code. Such operation is useful if other code needs to execute while the operation completes. This is possible because when an asynchronous method is called, execution occurs on a unique thread. When the asynchronous method is complete, an event is raised, notifying the main thread of completion. Asynchronous methods are slightly more difficult to implement than synchronous methods because it is necessary to implement events to handle the response.

In This Section

Accessing the Data Connection Asynchronously For Writing (Advanced Users)
Provides step-by-step instructions on asynchronously establishing a data stream for storing a file to the server.
Accessing the Data Connection Asynchronously for Reading (Advanced Users)
Provides step-by-step instructions on asynchronously establishing a data stream for storing a file to the server.

Related Sections

Transferring Streams Synchronously
Provides an overview for transferring streams synchronously. This topic shows the easiest way to store or retrieve a file using a stream interface.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Reading From The Data Connection Asynchronously

Accessing The Data Connection Asynchronously For Reading

To establish the data connection asynchronously (for reading), use the BeginGet method. This method opens a data connection to the server asynchronously, meaning that execution will occur on a new thread, allowing the next line of code to execute immediately. When the stream is opened, the EndGet event will be raised. Within the EndGet event, a SegmentedStream object will be accessible. Use this object to read from the data connection. When you are finished reading the file, the Ftp component will close the connection. If you do not wish to read the entire file, you must call the AbortTransfer and Close methods to close the connection.

Before using this method (or any method of the Ftp component) the Server, Username, and Password properties must first be set. This provides for transparent server login. After setting these properties, the Get method can then be called.

To use the BeginGet method to read from the data connection, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 2.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Call the Ftp.BeginGet method, passing in the name of the remote file and the offset specifying where to begin reading from the remote file.

    [Visual Basic, C#] The following code demonstrates using the Ftp.BeginGet method to open a stream to read from the data connection. The first parameter, remoteFileName, specifies the file on the server to which a data connection will be established. The second parameter, restartMarker, specifies the location in this file to begin reading. The third parameter, state, allows the calling method to make accessible any object in the handling event. Place this code directly after the code from step 3.

    [C#]
ftp1.BeginGet("myfile.txt", 0, null);
[Visual Basic]
Ftp1.BeginGet("myfile.txt", 0, Nothing)
  5. After this method executes and the data connection has been opened and is ready for reading, the Ftp.EndGet event will be raised. To access this event, you must have a method "signed up" as the event handler. For more information about how to do this, see the topic "Using Events In PowerTcp".

    [Visual Basic, C#] The following code demonstrates an empty event handler. Your event handler should look similiar.

    [C#]
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
}
[Visual Basic]
Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

End Sub
  6. Several objects will be accessible in the Ftp.EndGet event's FileEventArgs class, one of which will be a SegmentedStream object. Use this object to read data from the file on the server (synchronous and asynchronous methods are available). There are many options here. For example, the entire file can be read and used, or only a portion. For the sake of simplicity, this walkthrough will demonstrate a non-real world example of simply reading a few bytes from the stream. This may be useful if you want to determine file type (maybe by looking at tags or headers encoded within the file).

    [Visual Basic, C#] The following code will read up to 128 bytes from the stream.

    [C#]
// First create a SegmentedStream and set it equal to the Stream returned in the event
Dart.PowerTCP.Ftp.SegmentedStream sstream = (Dart.PowerTCP.Ftp.SegmentedStream)e.Stream;

// Create a byte array to read data into.
byte[] buffer = new  byte[128];

// Read into the byte array synchronously
sstream.Read(buffer, 0, 128);
[Visual Basic]
' First create a SegmentedStream and set it equal to the Stream returned in the event
Dim sstream As Dart.PowerTCP.Ftp.SegmentedStream sstream= e.Stream

'Create a byte array to read data into.
byte() buffer = new byte(128)

'Read into the byte array synchronously
sstream.Read(buffer, 0, 128)
  7. When you are done reading from the file, close the data connection by using the Ftp.AbortTransfer method.

    [Visual Basic, C#] The following code demonstrates closing the data connection when you are done reading. Place this code directly after the code from step 7.

    [C#]
ftp1.AbortTransfer();
[Visual Basic]
Ftp1.AbortTransfer()
  8. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Writing To The Data Connection Asynchronously

Accessing The Data Connection Asynchronously For Writing

To establish the data connection asynchronously (for writing), use the BeginPut method. This method open a data connection to the server asynchronously, meaning that execution will occur on a new thread, allowing the next line of code to execute immediately. When the stream is opened, the EndPut event will be raised. Within the EndPut event, a SegmentedStream object will be accessible. Use this object to write to the data connection, and close the Stream object when you are done writing.

Before using this method (or any method of the Ftp component) the Server, ServerPort, Username, and Password properties must first be set. This allows for server login to take place "behind the scenes" during any method. After setting these properties, the Put method can then be called.

To use the BeginPut method to write to the data connection, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties, so login can transparently take place. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 2.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Call the Ftp.BeginPut method, passing in the name of the remote file and the offset specifying where to begin writing to the remote file. If the file does not exist, it will be created on the server.

    [Visual Basic, C#] The following code demonstrates using the Ftp.BeginPut method to open a stream to write to the data connection. The first parameter, remoteFileName, specifies the name of the file to be written to on the server. The second parameter, restartMarker, specifies the location on this file to begin writing. The third parameter, state, allows the calling method to make accessible any object in the handling event.The file "mynewfile.txt" will be created on the server. Place this code directly after the code from step 3.

    [C#]
ftp1.BeginPut("mynewfile.txt", 0, null);
[Visual Basic]
ftp1.BeginPut("mynewfile.txt", 0, Nothing)
  5. After this method executes and the data connection has been opened and ready for writing, the Ftp.EndPut event will be raised. In order to access this event, you must have a method "signed up" as the event handler. For more information about how to do this, see the topic Using Events In PowerTcp.

    [Visual Basic, C#] The following code demonstrates an empty event handler. Your event handler should look similiar.

    [C#]
private void ftp1_EndPut(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
}
[Visual Basic]
Private Sub Ftp1_EndPut(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndPut

End Sub
  6. Several objects will be accessible in the Ftp.EndPut event's FileEventArgs class, one of which will be a Stream object. Use this object to write some data onto the file on the server.

    [Visual Basic, C#] The following code demonstrates writing a string to the newly created file on the server. After this method executes, the file on the server will contain the text "Some data. ". Place this code within your Ftp.EndGet event handler.

    [C#]
// First create a SegmentedStream and set it equal to the Stream returned in the event
// SegmentedStream allows for shortcut methods like writing a string that aren't available in
// Stream object.
Dart.PowerTCP.Ftp.SegmentedStream sstream = (Dart.PowerTCP.Ftp.SegmentedStream)e.Stream;

// Write to the file synchronously
sstream.Write("Some data. ");
[Visual Basic]
' First create a SegmentedStream and set it equal to the Stream returned in the event
' SegmentedStream allows for shortcut methods like writing a string that aren't available in
' Stream object.
Dim sstream As Dart.PowerTCP.Ftp.SegmentedStream sstream = e.Stream

'Write to the file synchronously
sstream.Write("Some data. ")
  7. Write a couple of more times to the file on the server. Since the data connection is maintained you can keep writing to it.

    [Visual Basic, C#] The following code demonstrates writing more data to the file on the server. Place this code directly after the code from step 6.

    [C#]
sstream.Write("Some more data. ");
sstream.Write("This is all of the data. ");
[Visual Basic]
sstream.Write("Some more data. ")
sstream.Write("This is all of the data. ")
  8. When you are done writing to the file, close the SegmentedStream object. The file "mynewfile.txt" will exist complete on the server.

    [Visual Basic, C#] The following code demonstrates closing the data connection when you are done writing. Place this code directly after the code from step 7.

    [C#]
sstream1.Close();
[Visual Basic]
sstream1.Close()
  9. Compile and run the application.
  10. Retrieve the file "mynewfile.txt" and open it. It should say:
    Some data. Some more data. This is all of the data.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Sending Commands Overview

The FTP protocol is built upon a request/response model, meaning that the client will send a request, to which the server will send at least one reply. This will continue, lock-step, until communication is complete. It goes without saying then, that the ability to send commands is the basic element of an FTP component.

The Ftp component provides a good balance between high-level ease-of-use and low-level flexibility in sending commands. Commonly used commands are encapsulated by high-level methods and properties while other commands (including user-defined) can be sent using lower-level methods.

In This Section

Sending Commands Described
Describes how commands are issued using the Ftp component.
Sending Commands Synchronously
Provides step-by-step instructions on sending commands synchronously using the Invoke method. This is the simplest method for explicitly sending commands.
Sending Commands Asynchronously
Provides step-by-step instructions on sending commands asynchronously using the BeginInvoke method. This topic involves event usage, so it is recommended for more advanced users.
Sending User-Defined Commands
Provides step-by-step instructions on sending commands that are proprietary to a specific FTP server implementation.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Sending Commands Described

PowerTCP FTP for .NET have a flexible implementation for sending commands to the server. Commands are sent two ways using the Ftp component:

  1. Sent explicitly using the Invoke or BeginInvoke methods.
  2. Sent transparently using a higher-level method or property.

Commands Sent Explicitly:
Commands can be sent explicitly using the Invoke or BeginInvoke methods. To do this simply call either of these two methods, passing in the appropriate FtpCommand (an enumeration describing which commands can be sent) and modifier for the command (if necessary). For example, to send a change working directory request synchronously, you would simply call the Invoke method as follows:

[C#]
ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.ChangeDir, "/mydir/");
[Visual Basic]
Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.ChangeDir, "/mydir/")
The above code causes "CWD /mydir/" to be sent to the server. If you wish to send your own command, simply specify FtpCommand.Null as the first parameter and specify your entire command as the second parameter.

Commands Sent Transparently:
Most commands sent with the Ftp component will occur transparently resulting from the use of a high-level property or method. A good example of this can be seen with the Ftp component auto-login feature. Simply set the necessary properties of the Ftp component (usually only the Ftp.Server, Ftp.Username, and Ftp.Password properties, then call a method of the Ftp component. In this example, a simple NoOp command will be sent to the server:

[C#]
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Send NoOp
ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.NoOp);

[Visual Basic]
Ftp1.Server = "MyFtpServer";
Ftp1.Username = "blah";
Ftp1.Password = "mypass";

' Send NoOp
Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.NoOp);
The above code causes the following commands to be sent:

<connection made to the server "MyFtpServer" and greeting received>
USER blah
<Response received>
PASS mypass
<Response received>
NOOP
<Response received>
If any errors occurred during these operations, a ProtocolException would be thrown.

Commands are transparently issued other ways using the Ftp component. For example, the Rename method causes both RNFR and RNTO commands to be sent, which the following code demonstrates.

[C#]
ftp1.Rename("oldfilename.txt", "newfilename.txt");
[Visual Basic]
Ftp1.Rename("oldfilename.txt", "newfilename.txt")

The above code causes the following commands to be sent:

RNFR oldfilename.txt
<Response received>
RNTO newfilename.txt
<Response received>

If any errors occurred during these operations, a ProtocolException would be thrown. Generally, commands are encapsulated by higher level methods like Rename when they are commonly used (for example, the Close method). or when doing so would be a benefit in code development (for example, the GetDirectory method returns a parsed response, where Invoke (PrintDir) returns an unparsed response).

Related Sections

Sending Commands Synchronously
Provides an overview on sending commands to the server synchronously.
Sending Commands Asynchronously
Provides an overview on sending commands to the server asynchronously.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Sending Commands Synchronously

Using the Invoke method to send a command to the server demonstrates the simplest usage for sending commands. Before using this method (or any method of the Ftp component) the Server, Username, and Password properties must first be set. This provides for transparent server login. After setting these properties, the Invoke method can then be called. This method returns an Invoke object, which encapsulates information about the command sent to the server and the reply received from the server.

To use the Invoke method to send a command to the server, use the following steps. (In this example the "SYST" command will be sent to retrieve system information about the server).

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 1.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Create an Invoke variable which will store information about the command sent and the reply received. (optional)

    [Visual Basic, C#] The following code demonstrates creating an Invoke object. Place this code directly after the code from step 3.

    [C#]
Dart.PowerTCP.Ftp.Invoke invoke;
[Visual Basic]
Dim Ftp.Invoke Dart.PowerTCP.Ftp.Invoke
  5. Use the Ftp.Invoke method to send the "SYST" command to the server. Login will occur transparently. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed. The Ftp.Invoke method returns an Invoke object, which can be used to access data about the request sent to the server and the response received from the server.

    [Visual Basic, C#] The following code demonstrates using Ftp.Invoke to send a "SYST" command. Place this code directly after the code from step 4.

    [C#]
invoke = ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.System);
[Visual Basic]
invoke = Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.System)
  6. Access information about the transfer using the Ftp.Invoke object returned from the Ftp.Invoke method. (optional)

    [Visual Basic, C#] The following code demonstrates retrieving info from the Invoke object returned from the Ftp.Invoke method. Place this code directly after the code from step 5.

    [C#]
Debug.WriteLine(invoke.ToString());
[Visual Basic]
Debug.WriteLine(invoke.ToString())
  7. Compile and run the application. The following (or something similiar) should be written to the debugger window.
    FTP Request: SYST
FTP Response: 215 UNIX Type: L8

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Sending Commands Asynchronously

To send a command to the server asynchronously, use the BeginInvoke method. This method sends a command asynchronously, with execution occurring on a new thread, allowing the next line of code to execute immediately. When the command has been successfully sent and the response received, the EndInvoke event will be raised, making accessible the InvokeEventArgs object encapsulating information about the command sent and the response received. Before you can call BeginInvoke (or any method of the Ftp component) the Server, Username, and Password properties must first be set. This provides for a transparent server login.

To use the BeginInvoke method send a command to the server asynchronously, use the following steps (In this example, the "SYST" command will be sent to retrieve system information about the server).

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 2.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Add the code for the BeginInvoke method, which, when called, will begin execution on a new thread. Execution on the main thread will immediately continue. Login will occur transparently. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed.

    [Visual Basic, C#] The following code demonstrates calling an asynchronous BeginInvoke method. The first parameter (command) specifies the FtpCommand to send to the server. The second parameter (modifier) specifies a parameter to be used along with the command parameter (for example, if the command was Delete, the modifier would specify which file to delete. Of course, no modifier is required for a "SYST" command, so this will simply be null. The third parameter (state) allows the passing of any object that you would like accessible in the Ftp.EndGet event. Place this code directly after the code from step 3.

    [C#]
ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.System, null, null);
[Visual Basic]
Ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.System, null, null);
  5. After the command has been sent and the reply received, the Ftp.EndInvoke event will be raised. In order to access this event, you must have a method "signed up" as the event handler. For more information about how to do this, see the topic Using Events In PowerTcp. Once you have the Ftp.EndInvoke event properly "signed up" to handle the response from the Ftp.BeginInvoke method, add the code to the event handler. When the event is raised, access information contained in the InvokeEventArgs object.

    [Visual Basic, C#] The following code demonstrates an event handler, including code to access the InvokeEventArgs object to retrieve information about the request sent and the response received. If any error occurred during the asynchronous operation, it would be returned in the InvokeEventArgs.Exception property. Check this first to find out the success/failure of the operation.

    [C#]
private void ftp1_EndInvoke(object sender, Dart.PowerTCP.Ftp.InvokeEventArgs e)
{
   if(e.Exception == null)
   {
      Debug.WriteLine("Request: " + e.Request);
      Debug.WriteLine("Response: " + e.Response.ToString());
   }
   else
   {
      Debug.WriteLine("Error: " + e.Exception.ToString());
   }
}
[Visual Basic]
Private Sub Ftp1_EndInvoke(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.InvokeEventArgs) Handles Ftp1.EndInvoke

    If e.Exception Is Nothing then
      Debug.WriteLine("Request: " + e.Request)
      Debug.WriteLine("Response: " + e.Response.ToString())
    Else
        Debug.WriteLine("Error: " + e.Exception.ToString())
    End If

End Sub
  6. Compile and run the application. The following (or something similiar) should be written to the debugger window.
    FTP Request: SYST
FTP Response: 215 UNIX Type: L8

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Sending User-Defined Commands

Although all commonly used FTP commands are encapsulated by either higher-level methods and properties or the FtpCommand enumeration, it is impossible to account all possible commands that could conceivably be sent to an FTP server. For this reason, the Invoke and BeginInvoke methods both have the capability to send any command to the server. This topic addresses sending a user-defined command using the Invoke method, although the BeginInvoke method works similarly if you wish to send an asynchronous user-defined command.

Before using this method (or any method of the Ftp component) the Server, ServerPort, Username, and Password properties must first be set. This allows for server login to transparently take place during any method. After setting these properties, the Invoke method can then be called. This method returns an Invoke object, which encapsulates information about the command sent to the server and the reply received from the server.

For the purposes of this walkthrough, an invented command will be used. For example, perhaps the FTP server supports a "Change Password" command called CHPASS, which would be followed by the new password. This command can be used after successful login.

To use the Invoke method to send a user-defined command to the server, use the following steps .

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties, so login can transparently take place. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 1.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Create an Invoke object which encapsulates information about the command sent and the reply received. (optional)

    [Visual Basic, C#] The following code demonstrates creating an Invoke object. Place this code directly after the code from step 3.

    [C#]
Dart.PowerTCP.Invoke invoke;
[Visual Basic]
Dart.PowerTCP.Invoke invoke
  5. Use the Ftp.Invoke method to send the "CHPASS" command to the server. To send a user-defined command like "CHPASS" you MUST use FtpCommand.Null as the first parameter and your ENTIRE command as the second parameter. Login will transparently take place. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed. The Invoke method returns an Invoke object, which can be used to access data about the request sent to the server and the response received from the server.

    [Visual Basic, C#] The following code demonstrates using Invoke to send the user-defined "CHPASS" command. In this example, the password will be changed to "mynewpass". Place this code directly after the code from step 4.

    [C#]
invoke = ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "CHPASS mynewpass");
[Visual Basic]
invoke = Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "CHPASS mynewpass")
  6. Access information about the transfer using the Ftp.Invoke object returned from the Ftp.Invoke method. (optional)

    [Visual Basic, C#] The following code demonstrates retrieving info from the Invoke object returned from the Ftp.Invoke method. Place this code directly after the code from step 5.

    [C#]
Debug.WriteLine(invoke.ToString());
[Visual Basic]
Debug.WriteLine(invoke.ToString())
  7. Compile and run the application. If the FTP server supportes this command, the password should be changed, if not a ProtocolException will be thrown.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Retrieving Listings Overview

Use the Ftp component to retrieve listings from the server using the List or BeginList method. These methods return a Listing object which encapsulates an FTP listing. If the listing returned is either a DOS or UNIX listing, the fields will automatically be parsed and will be available as properties of the ListEntry object. If the listing type is unknown, you will have to use the Text property to obtain the raw text, and parse it yourself.

In This Section

Retrieving Listings Synchronously
Provides step-by-step instructions on retrieving FTP listings from the server synchronously. This is the simplest method of retrieving listings from the server.
Retrieving Listings Asynchronously
Provides step-by-step instructions on retrieving FTP listings from the server asynchronously. This topic involves event usage, so it is recommended for more advanced users.
Parsing An Unknown Listing
Provides instructions for parsing a non-DOS and non-UNIX listing.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Retrieving Listings Synchronously

Use the List method to easily retrieve FTP listings. The Ftp component will attempt to automatically detect the type of listing (UNIX, DOS, or Unknown). Before using this method (or any method of the Ftp component) the Server, Username, and Password properties must first be set. This provides for a transparent server login. After setting these properties, the List method can then be called. This method returns a Listing object, which encapsulates the returned listing.

To use the List method to retrieve an FTP listing from the server, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties, so login can transparently take place. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 1.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Create a Listing variable to store the listing returned from the server.

    [Visual Basic, C#] The following code demonstrates creating a Listing object. Place this code directly after the code from step 3.

    [C#]
Dart.PowerTCP.Ftp.Listing listing;
[Visual Basic]
Dim listing As Dart.PowerTCP.Ftp.Listing
  5. Use the Ftp.List method to retrieve a listing from the server. Login will transparently occur. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed. The Ftp.List method returns a Listing object, which encapsulates an FTP listing. Each entry in the FTP listing (directory, file, or link) will be included in the Listing object as a ListEntry object.

    [Visual Basic, C#] The following code demonstrates using list to retrieve an FTP listing. The first parameter, searchPattern, specifies, using a wildcard, which files to retrieve in the listing. For example, if "*.txt" is specified as the wildcard, only text files will be retrieved. In this example, "*" is used, so all files will be retrieved. The second parameter, full , specifies whether to retrieve a full listing or a named list. In this example the parameter is true so a full listing will be retrieved. Place the following code directly after the code from step 4.

    [C#]
listing = ftp1.List("*", true);
[Visual Basic]
listing = Ftp1.List("*", true)
  6. Iterate through the ListEntry objects contained within the Listing object and display some fields. Normally an object such as a ListView would be used for displaying lists but, in the interest of code simplicity, the fields are simply written to the debug window in this walkthrough.

    [Visual Basic, C#] The following code demonstrates iterating through the ListEntry objects contained within the Listing. Place this code directly after the code from step 5.

    [C#]
    // Check to see if it is a format recognized by the Ftp component
if(listing.Format != Dart.PowerTCP.Ftp.ListingFormat.Unknown)
{
   // Iterate through each ListEntry
   foreach(Dart.PowerTCP.Ftp.ListEntry le in listing)
   {
      /*
      Display generic fields (fields that are available whether the
      listing returned is UNIX or DOS)
      */

      // Display file path and name
      Debug.WriteLine(le.Path + le.Name);

      // Display size
      Debug.WriteLine(le.Size);

      // Display timestap
      Debug.WriteLine(le.TimeStamp);

    }
}
else // Format not recognized
{
   Debug.WriteLine("Listing format is unknown. You must parse it yourself.");
}
[Visual Basic]
' Check to see if it is a format recognized by the Ftp component
If listing.Format <> Dart.PowerTCP.Ftp.ListingFormat.Unknown Then

   ' Iterate through each ListEntry
   Dim le As Dart.PowerTCP.Ftp.ListEntry
   For Each le In listing

      ' Display generic fields (fields that are available whether the
      ' listing returned is UNIX or DOS)

      ' Display file path and name
      Debug.WriteLine(le.Path + le.Name)

      ' Display size
      Debug.WriteLine(le.Size)

      ' Display timestamp
      Debug.WriteLine(le.TimeStamp)
   Next

Else ' Format not recognized
   Debug.WriteLine("Listing format is unknown. You must parse it yourself.");
End If
  7. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Retrieving Listings Asynchronously

To retrieve a listing from an FTP server asynchronously, use the BeginList method. This method enables the retrieval of a listing asynchronously, with execution occurring on a new thread, allowing the next line of code to execute immediately. When the listing has been received the EndList event is raised, providing the ListEventArgs object encapsulating the listing. Before you can call BeginList (or any method of the Ftp component) the Server, Username, and Password properties must first be set. This provides for a transparent server login.

To use the BeginList method to retrieve a listing asynchronously, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 2.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Add the code for the Ftp.BeginList method, which, when called, will begin execution on a new thread. Execution on the main thread will immediately continue. Login will transparently occur. The Ftp component will stay logged in to the server until either the Ftp.Close or Ftp.Abort method is called, or until the Ftp component is destroyed.

    [Visual Basic, C#] The following code demonstrates calling an asynchronous Ftp.BeginList method. The first parameter, searchPattern , specifies, using a wildcard, which files to retrieve in the listing. For example, if "*.txt" is specified as the wildcard, only text files will be retrieved. In this example, "*" is used, so all files will be retrieved. The second parameter, full, specifies whether to retrieve a full listing, or a named list. In this example, this parameter is true so a full listing will be retrieved. The third parameter, state, allows the passing of any object that you would like accessible in the Ftp.EndGet event. Place this code directly after the code from step 3.

    [C#]
ftp1.BeginList("*", true, null);
[Visual Basic]
Ftp1.BeginList("*", true, Nothing)
  5. After the listing has been received, the Ftp.EndList event will be raised. In order to access this event, you must have a method "signed up" as the event handler. For more information about how to do this, see the topic Using Events In PowerTcp. Once you have the Ftp.EndList event properly "signed up" to handle the response from the Ftp.BeginList method, add the code to the event handler. When the event is raised, iterate through the Listing object passed in as part of the ListEventArgs object and display some fields. Normally an object such as a ListView would be used for displaying lists but, in the interest of code simplicity, the fields are simply written to the debug window.

    [Visual Basic, C#] The following code demonstrates an event handler, including code to access the ListEventArgs object to retrieve the listing returned. If any error occurred during the asynchronous operation, it would be returned in the ListEventArgs.Exception property. Check this first to determine the success/failure of the operation.

    [C#]
private void ftp1_EndList(object sender, Dart.PowerTCP.Ftp.InvokeEventArgs e)
{
   // Check to see if it is a format recognized by the Ftp component
   if(e.Exception ==

               null &&
   e.Listing.Format != Dart.PowerTCP.Ftp.ListingFormat.Unknown)
   {
      // Iterate through each ListEntry
      foreach(Dart.PowerTCP.Ftp.ListEntry le in e.Listing)
      {
         /*
         Display generic fields (fields that are available whether the
         listing returned is UNIX or DOS)
         */

         // Display file path and name of the entry
         Debug.WriteLine(le.Path + le.Name);

         // Display size of the entry
         Debug.WriteLine(le.Size);

         // Display timestamp
         Debug.WriteLine(le.TimeStamp);
       }
   }
   else
   {
      Debug.WriteLine("Listing format is unknown. You must parse it yourself.");
   }
}
[Visual Basic]
Private Sub Ftp1_EndList(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.InvokeEventArgs) Handles Ftp1.EndList
   ' Check to see if it is a format recognized by the Ftp component
   If e.Listing.Format <> Dart.PowerTCP.Ftp.ListingFormat.Unknown Then

      ' Iterate through each ListEntry
      Dim le As Dart.PowerTCP.Ftp.ListEntry
      For Each le In Listing

         ' Display generic fields (fields that are available whether the
         ' listing returned is UNIX or DOS)

         ' Display file path and name
         Debug.WriteLine(le.Path + le.Name)

         ' Display size
         Debug.WriteLine(le.Size)

         ' Display timestamp
         Debug.WriteLine(le.TimeStamp)
      Next

   Else ' Format not recognized
      Debug.WriteLine("Listing format is unknown. You must parse it yourself.");
   End If

End Sub
  6. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Parsing An Unknown Listing Type

When retrieving a listing, the Ftp component will attempt to determine the type and parse it automatically. This will be the case when the listing returned from the server is either a UNIX listing or a DOS listing. In either of these two cases, the Format property will contain either DOS or UNIX, and the properties of the ListEntry object will contain the parsed fields of the listing. However, many servers return listings that are not DOS or UNIX formatted. In these cases the Format property will be Unknown and the properties of the ListEntry will be null. It is necessary to parse the listing in this case.

To parse a listing that is not recognized by the Ftp component, use the following steps.

Note: There are many ways to parse a listing. This example will use regular expressions. For the purposes of this walkthrough, the server is returning a listing like the following:

myfile.txt 158 01-11-02 11:55

This is a four-field listing, starting with the file name, then whitespace, then the file size, then whitespace, then the file date, then whitespace, then finally the file time stamp.

  1. Retrieve a listing as described in the "Retrieving Listings Synchronously" topic.
  2. Iterate through the ListEntry objects.
  3. Check to be sure the Format is unknown.
  4. Construct a regular expression pattern to match the above listing format.
    [C#]
string pattern;
pattern = @"(?<filename>\S+)\s+(?<filesize>\S+)\s+(?<filedate>\S+)\s+(?<filetime>\S+)";
[Visual Basic]
Dim pattern As String
pattern = "(?<filename>\S+)\s+(?<filesize>\S+)\s+(?<filedate>\S+)\s+(?<filetime>\S+)"
  5. Create a RegularExpression object, passing in the pattern created.
    [C#]
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern);
[Visual Basic]
Dim regex as new System.Text.RegularExpressions.Regex(pattern)
  6. Attempt to match the regular expression to the raw text for each ListEntry object.
    [C#]
System.Text.RegularExpressions.Match match = regex.Match(le.Text);
[Visual Basic]
Dim match As System.Text.RegularExpressions.Match
match = regex.Match(le.Text);
  7. Check for match success and retrieve fields.
    [C#]
if(match.Success)
{
   string filename = match.Groups["filename"].Value;
   string filesize = match.Groups["filesize"].Value;
   string filedate = match.Groups["filedate"].Value;
   string filetime = match.Groups["filetime"].Value;
   Debug.WriteLine(filename);
   Debug.WriteLine(filesize);
   Debug.WriteLine(filedate);
   Debug.WriteLine(filetime);
}
[Visual Basic]
If match.Success Then
   Dim filename As string = match.Groups("filename").Value
   Dim filesize As string = match.Groups("filesize").Value
   Dim filedate As string = match.Groups("filedate").Value
   Dim filetime As string = match.Groups("filetime").Value
   Debug.WriteLine(filename)
   Debug.WriteLine(filesize)
   Debug.WriteLine(filedate)
   Debug.WriteLine(filetime)
End If
  8. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Using Secure FTP

The Ftp component included in PowerTCP FTP for .NET fully supports SSL communication, including explicit and implicit use. Simple properties, methods, and events control SSL and certificate use, simplifying the task of secure communication.

The following topics discuss secure communications in general and how to communicate securely with PowerTCP FTP for .NET.

In This Section

Security Overview
Provides an overview of basic security concepts such as digital certificates and authentication.
Creating A Secure FTP Client
Provides a step-by-step set of instructions on how to create a secure FTP client using the Ftp component.
Handling Client Authentication.
Demonstrates how to use a certificate to authenticate the client to the server.
Explicit vs Implicit Security
Discusses the differences between using explicit and implicit SSL.
Using The CertificateListForm Object
Demonstrates how to use the CertificateListForm to assist users in selecting a certificate.
Using MMC To Manage SSL Certificates
Discusses how to use the Microsoft Management Console to manage SSL certificates.
Windows 95/98 Security Compatibility
Discusses compatibility issues with Windows 95 and 98.

See Also

Using FTP for .NET | FTP for .NET Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Security Overview

This topic covers:

  • What is a digital certificate?
  • Where do I get a certificate?
  • How does the authentication process work?
  • What is a certificate store?
  • What are the system store and the machine store?
  • What is the X500 naming convention?

What is a digital certificate?

Authentication is important for secure communications. Users must be able to prove their identity to the entities they are communicating with. In addition they must be able to verify the identity of the entity communicating with them. This is accomplished by presenting or verifying some form of trusted credentials.

A digital certificate is a common credential that provides authentication. A trusted organization, called a Certificate Authority (CA), assigns a certificate to a user or entity and the user or entity then uses the certificate to prove itself to the other side. You may configure your system to accept any number of Certificate Authorities. Completing the following steps to access the Certificates dialog box:

  1. In the Control Panel, double-click Internet Options.
  2. Select the Content tab, and then click Certificates.
Back to Top

Where do I get a certificate?

Certificates must come from a trusted CA. A user submits a certificate request to a CA and the CA returns a certificate for the user to use. Listed below are some Certificate Authorities:

  • Microsoft Certificate Server – used for internal corporate Certificate delegation
  • VeriSign – (www.verisign.com) provides certificates for Internet users and servers

You always need a digital certificate installed to operate as a server. You only need a digital certificate installed on a client if the server requests authentication.

Back to Top

How does the authentication process work?

  1. The client normally initiates the TCP connection. The Connect method makes this TCP connection, sends a "client hello" message, and automatically responds to authentication requests received from the server.
  2. The server accepts the connection initiated by the client, constructs its digital credentials from the digital certificate referred to by the Server.Certificate Property, and sends its credentials to the client.
  3. Optionally, the server may also send an authentication request to the client.
  4. The client receives the server's credentials, verifies it against the CAs it is configured to trust, and responds with its own credentials if an authentication request is received.
  5. If the client and server cannot negotiate a mutually acceptable security protocol, an error is generated and the connection is closed.
  6. If the client cannot validate the server's credentials, an error is generated and the client closes the connection.
  7. If the server cannot validate the client's credentials (if requested), an error is generated and the server closes the connection.
  8. Once protocol negotiation and authentication is successful, secure encryption/decryption is performed on all data passing over the connection.
  9. The session is terminated when one side closes the connection.
Back to Top

What is a certificate store?

A certificate store is a location on the system (memory, disk, registry, etc.) where certificates are stored for use. There are three major system stores and other minor stores. The three major stores are:

  • MY – personal certificates go here
  • ROOT – certificates for Trusted Root Certificate Authorities
  • CA – all other certificates

There are other certificate stores. For example, the store "SPC" containes software publisher's certificates. For more information see the CertificateStoreName enumeration.

Back to Top

What are the system store and the machine store?

The system store is the certificate store located in the HKEY_CURRENT_USER registry key. The machine store is the certificate store located in the HKEY_LOCAL_MACHINE registry key. Applications installed as a service should store their certificates in the machine store since there is no current user when running as a service.

Back to Top

What is the X500 naming convention?

This is a format for creating a distinguished name. The different parts of the name are described below:

  • C – country you are in (ex. US)
  • S – state you are in (ex. New York)
  • L – locality value or city (ex. Syracuse)
  • O – your organization (ex. Dart)
  • OU – organizational unit (ex. Development)
  • CN – common name; typically the name of the system or user (Ex. MyMachine)

Here are some examples of X500 names:

  • C=US, S=New York, L=Syracuse, O=Dart, OU=Development, CN=My Machine
  • C=US, S=Georgia, L=Atlanta, O=MyOrg, OU=Toy Department, CN=John Doe
Back to Top

See Also

Using FTP for .NET | FTP for .NET Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Creating a Secure FTP Client

Creating a secure FTP client is quite simple. All that needs to occur is the Security property must be set to the type of security/authentication desired. Then simply connect to your secure FTP server, and handle all certificate-related issues in the CertificateReceived or CertificateRequested events.

The Simplest Secure Example: Disabling All Security Checks.

This example demonstrates the simplest possible secure FTP example. In this example, the UseAuthentication property is set to false, "disabling" all security checks (NOTE: This does NOT disable security). This means that even if an invalid certificate is received from the server, it is accepted and SSL communication is established. This has obvious shortcomings, which will be addressed later in the topic.

[Visual Basic]
Private Sub SecureTest()
   ' Set the server & user info
   Ftp1.Server = "myftpserver"
   Ftp1.ServerPort = 21
   Ftp1.Username = "user"
   Ftp1.Password = "pass"

   ' "Disable" security checks
   Ftp1.UseAuthentication = False

   ' Set the desired security/authentication to explicit.
   Ftp1.Security = Dart.PowerTCP.Ftp.Security.Explicit

   ' Execute a command (this will cause an SSL connection to be made first
   ' and the data will be sent securely)
   Dim dir As String = Ftp1.GetDirectory()
   Debug.WriteLine("Current directory: " + dir)

   ' Close the connection.
   Ftp1.Close()
End Sub
[C#]
private void SecureTest()
{
   // Set the server & user info
   ftp1.Server = "myftpserver";
   ftp1.ServerPort = 21;
   ftp1.Username = "user";
   ftp1.Password = "pass";

   // "Disable" security checks
   ftp1.UseAuthentication = false;

   // Set the desired security/authentication to explicit.
   ftp1.Security = Dart.PowerTCP.Ftp.Security.Explicit;

   // Execute a command (this will cause an SSL connection to be made first
   // and the data will be sent securely)
   string dir = ftp1.GetDirectory();
   Debug.WriteLine("Current directory: " + dir);

   // Close the connection.
   ftp1.Close();
}

A More Advanced Secure Client: Validating certificates.

The example above demonstrates communicating securely but is flawed, mainly because all certificates are automatically accepted. To remedy this, set UseAuthentication = true and handle which certificates are accepted/rejected in the CertificateReceived event.

[Visual Basic]
Private Sub SecureTest()
   ' Set the server & user info
   Ftp1.Server = "myftpserver"
   Ftp1.ServerPort = 21
   Ftp1.Username = "user"
   Ftp1.Password = "pass"

   ' "Enable" certificate authentication (verify any certificate the server sends)
   Ftp1.UseAuthentication = True

   ' Set the desired security/authentication to explicit.
   Ftp1.Security = Dart.PowerTCP.Ftp.Security.Explicit

   ' Execute a command (this will cause an SSL connection to be made first
   ' and the data will be sent securely)
   Dim dir As String = Ftp1.GetDirectory()
   Debug.WriteLine("Current directory: " + dir)

   ' Close the connection.
   Ftp1.Close()
End Sub

Private Sub Ftp1_CertificateReceived(ByVal sender As Object, e As Dart.PowerTCP.Ftp.CertificateReceivedEventArgs) Handles Ftp1.CertificateReceived
   Dim msg As String = ""

   ' Check to see if the certificate is from a trusted root.
   If Not e.TrustedRoot Then
      msg += "This certificate is not from a trusted root" + vbCrLf
   End If

   ' Check to see if the certificate has a valid date.
   If Not e.ValidDate Then
      msg += "This certificate does not have a valid date" + vbCrLf
   End If

   ' Check to see if the certificate has a valid name.
   If Not e.ValidName Then
      msg += "This certificate does not have a valid name" + vbCrLf
   End If

   If msg <> "" Then
      msg += "Would you like to accept this certificate anyway?"
      If MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) = DialogResult.Yes Then
         ' User wants to accept the invalid cert. Accept it.
         e.Accept = True
      End If
   End If
End Sub
[C#]
private void SecureTest()
{
   // Set the server & user info
   ftp1.Server = "myftpserver";
   ftp1.ServerPort = 21;
   ftp1.Username = "user";
   ftp1.Password = "pass";

   // "Enable" certificate authentication (verify any certificate the server sends)
   ftp1.UseAuthentication = true;

   // Connect to a secure server using explicit SSL
   ftp1.Security = Dart.PowerTCP.Ftp.Security.Explicit;

   // Execute a command (this will cause an SSL connection to be made first
   // and the data will be sent securely)
   string dir = ftp1.GetDirectory();
   Debug.WriteLine("Current directory: " + dir);

   // Close the connection.
   ftp1.Close();
}

private void ftp1_CertificateReceived(object sender, Dart.PowerTCP.Ftp.CertificateReceivedEventArgs e)
{
   string msg = "";

   // Check to see if the certificate is from a trusted root.
   if(!e.TrustedRoot)
      msg+= "This certificate is not from a trusted root\n";

   // Check to see if the certificate has a valid date.
   if(!e.ValidDate)
      msg+= "This certificate does not have a valid date\n";

   // Check to see if the certificate has a valid name.
   if(!e.ValidName)
      msg+= "This certificate does not have a valid name\n";

   if(msg != "")
   {
      msg += "Would you like to accept this certificate anyway?";
      if(MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) == DialogResult.Yes)
      {
         // User wants to accept the invalid cert. Accept it.
         e.Accept = true;
      }
   }
}

See Also

Using FTP for .NET | FTP for .NET Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Handling Client Authentication

A secure FTP server may request a certificate from the client, forcing the client to prove it's identity to the server. This process is called client authentication. If the server does request a certificate from the FTP client, the CertificateRequested event will be raised, notifying the user.

Handling Client Authentication Interactively

When writing an interactive application in which a server requests client authentication it is often useful to notify the user and allow them to select the certificate they would like to use for client authentication. The CertificateListForm object is ideal for displaying available certificates to the user. See the topic Using The CertificateListForm Object for more information on using this object.

[Visual Basic]
Private Sub SecureTest()
   ' Set the server & user info
   Ftp1.Server = "myftpserver"
   Ftp1.ServerPort = 21
   Ftp1.Username = "user"
   Ftp1.Password = "pass"

   ' Set the desired security/authentication to explicit.
   Ftp1.Security = Dart.PowerTCP.Ftp.Security.Explicit

   ' Execute a command (this will cause an SSL connection to be made first
   ' and the data will be sent securely)
   Dim dir As String = Ftp1.GetDirectory()
   Debug.WriteLine("Current directory: " + dir)

   ' Close the connection.
   Ftp1.Close()
End Sub

Private Sub Ftp1_CertificateRequested(ByVal sender As Object, e As Dart.PowerTCP.Ftp.CertificateRequestedEventArgs) Handles Ftp1.CertificateRequested
   ' Create a new instance of CertificateListForm
   Dim certForm as new CertificateListForm(True, True)
   certForm.Text = "The Server Requested A Client Certificate"

   ' Show the CertificateListForm to the user and let them choose a certificate
   If certForm.ShowDialog() = DialogResult.OK Then
      ' Set the Certificate property to the certificate the user selected.
      Ftp1.Certificate = certForm.SelectedCertificate
   Else
      MessageBox.Show("You must select a cert. SSL communication will fail.")
   End If
End Sub
[C#]
private void SecureTest()
{
   // Set the server & user info
   ftp1.Server = "myftpserver";
   ftp1.ServerPort = 21;
   ftp1.Username = "user";
   ftp1.Password = "pass";

   // Connect to a secure server using explicit SSL
   ftp1.Security = Dart.PowerTCP.Ftp.Security.Explicit;

   // Execute a command (this will cause an SSL connection to be made first
   // and the data will be sent securely)
   string dir = ftp1.GetDirectory();
   Debug.WriteLine("Current directory: " + dir);

   // Close the connection.
   ftp1.Close();
}

private void ftp1_CertificateRequested(object sender, System.EventArgs e)
{
   // Create a new instance of CertificateListForm
   CertificateListForm certForm = new CertificateListForm(true, true);
   certForm.Text = "The Server Requested A Client Certificate";

   // Show the CertificateListForm to the user and let them choose a certificate
   if(certForm.ShowDialog() == DialogResult.OK)
   {
      // Set the Certificate property to the certificate the user selected.
      ftp1.Certificate = certForm.SelectedCertificate;
   }
   else
   {
      MessageBox.Show("You must select a cert. SSL communication will fail.");
   }
}

Handling Client Authentication When Writing A Scripting Application

If you are writing a scripting application which needs to execute without interactive user input it is often useful to set the Certificate property to a valid certificate before communication with the FTP server. For this purpose the CertificateStore object is ideal. NOTE, in this example the CertificateRequested event will still be raised (if an event handler is present) but it is NOT necessary to take action in this event because the Certificate property will already be properly set.

[Visual Basic]
Private Sub SecureTest()
   ' Set the server & user info
   Ftp1.Server = "myftpserver"
   Ftp1.ServerPort = 21
   Ftp1.Username = "user"
   Ftp1.Password = "pass"

   ' Disable security checks
   Ftp1.UseAuthentication = False

   ' Create a new certificate store object
   Dim store as new CertificateStore()

   ' Set the Certificate property to the first certificate found.
   Ftp1.Certificate = store(0)

   ' Connect to a secure server using explicit SSL
   Ftp1.Security = Dart.PowerTCP.Ftp.Security.Explicit

   ' Execute a command (this will cause an SSL connection to be made first)
   Dim dir as String = Ftp1.GetDirectory()
   Debug.WriteLine("Current directory: " + dir)

   ' Close the connection.
   Ftp1.Close()
End Sub
[C#]
private void SecureTest()
{
   // Set the server & user info
   ftp1.Server = "myftpserver";
   ftp1.ServerPort = 21;
   ftp1.Username = "user";
   ftp1.Password = "pass";

   // Disable security checks
   ftp1.UseAuthentication = false;

   // Create a new certificate store object
   CertificateStore store = new CertificateStore();

   // Set the Certificate property to the first certificate found.
   ftp1.Certificate = store[0];

   // Connect to a secure server using explicit SSL
   ftp1.Security = Dart.PowerTCP.Ftp.Security.Explicit;

   // Execute a command (this will cause an SSL connection to be made first)
   string dir = ftp1.GetDirectory();
   Debug.WriteLine("Current directory: " + dir);

   // Close the connection.
   ftp1.Close();
}

See Also

Using FTP for .NET | FTP for .NET Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Explicit vs Implicit Security

When using secure FTP, there are two choices to be made about how to initiate an SSL session:

  • Use implicit SSL
  • Use explicit SSL

Implicit Security

With implicit security, it is understood that both the client and the server will use SSL for the entire session. The client connects, the SSL handshake occurs, and (if successful) secure communication continues for the session. For this reason, implicit SSL typically must use a different port (the well-known port for FTP SSL of 990).Note: Implicit SSL, although common, is not formally adopted in an RFC.

Explicit Security

With explicit security, secure communication occurs only after some preliminary negotiation in the clear. The client connects normally to the FTP server at the well-known port of 21 and issues the AUTH command along with the security mechanism (such as SSL) that the client would like to use. If the server supports this mechanism and responds positively, secure communication continues for the rest of the session.

See Also

Using FTP for .NET | FTP for .NET Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Using The CertificateListForm Object

The CertificateListForm Object is a visual control which displays and allows selection of certificates available on the local machine. This form is particularly useful in making certificate selection easier when starting a secure server or when using a secure client and the server requests client authentication.

Standard usage of the CertificateListForm would be to create a new instance, passing in the parameters controlling which certificates are displayed to the user. Display the CertificateListForm to the user. When the user makes a selection, check CertificateListForm.SelectedCertificate to get an instance of the Certificate object representing the certificate the user selected

To use the CertificateListForm

  1. Add a reference in your project to Dart.PowerTCP.Ftp.Forms.
  2. Create the CertificateListForm and display it to the user.
    [Visual Basic]
' Create a new CertificateListForm, showing all locations and names.
Dim certform As New CertificateListForm(true, true)

' Display the CertificateListForm to the user.
If certform.ShowDialog() == DialogResult.OK Then
   ' User has selected a certificate. Set the Certificate property
   server1.Certificate = certform.SelectedCertificate
Else
   ' User did not choose a certificate.
   MessageBox.Show("Error. You must choose a certificate")
End If
[C#]
// Create a new CertificateListForm, showing all locations and names.
CertificateListForm certform  = new CertificateListForm(true, true);

// Display the CertificateListForm to the user.
if(certform.ShowDialog() == DialogResult.OK)
{
   // User has selected a certificate. Set the Certificate property
   server1.Certificate = certform.SelectedCertificate;
}
else
{
   // User did not choose a certificate.
   MessageBox.Show("Error. You must choose a certificate");
}

See Also

Using FTP for .NET | FTP for .NET Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Using MMC to Manage SSL Certificates

This document explains how to use the Microsoft Management Console (MMC) to import and export SSL Certificates. There are MANY more uses for the MMC. Please see the MMC Documentation for more info.

NOTE: This document assumes that the "existing certificate" is functional on the machine where the exporting is being done.

Starting the MMC

The Microsoft Management Console (MMC) is part of Windows 2000 and Windows XP. It does not exist in NT or 9x. You may be able to do similar functions using IE, but IE versions vary so we will not discuss that here.

To start the MMC:

  1. Start -> Run -> MMC
  2. Choose File | Add/Remove Snap-in ...
  3. Click Add
  4. Select Certificates from the list and click the Add button
  5. Choose Computer account
  6. Choose Local Computer
  7. Click Close
  8. Click OK
  9. Repeat steps 2-8, substituting 'My user account' in step 5 and skipping step 6
  10. Choose File | Save As ... and save the settings to an .MSC file

In the future you can skip these steps by double-clicking the MSC file or by choosing the MSC from the history under the File menu.

The Microsoft Management Console (MMC) is part of Windows 2000 and Windows XP. It does not exist in NT or 9x. You may be able to do similar functions using IE, but IE versions vary so we will not discuss that here.

Exporting an Existing Certificate

Follow these steps if you want to save a certificate to a file. The file can then be used to import the certificate to another machine.

To export an existing certificate:

  1. Start the MMC by following the steps above or by clicking the MSC file saved previously
  2. Locate the Certificate that you wish to export. Certificates are using installed under the Personal ("MY") store in either the Local Machine or Current User stores
  3. Right Click on the certificate and choose All Tasks | Export
  4. Click Next
  5. Check 'Yes, export the private key' (If it's grayed out, the certificate can't be moved to another machine)
  6. Click Next
  7. Leave the Default setting at "Enable Strong Protection"
  8. Click Next
  9. Choose a password and click next
  10. Save the PFX file using a filename
  11. Click Next and you should see the "Completing the Certificate Export Wizard" screen
  12. Click Finish and you are done

The file you just saved can now be moved to another machine.

Importing a Certificate

Follow these steps if you want to move a certificate from one machine to another.

To export an existing certificate:

  1. Start the MMC by following the steps above or by clicking the MSC file saved previously
  2. Choose the store that you want to import to (EXAMPLE: Local Computer -> Personal)
  3. Right Click on the store and choose All Tasks | Import
  4. Click Next
  5. Browse to the PFX file that was previously saved
  6. Click Next
  7. Enter the password. If you want to allow the certificate to be exported again, check 'Mark this key as exportable'
  8. Click Next
  9. Check 'Place all certificates in the following store'
  10. Click Browse
  11. Check 'Show physical stores'
  12. Choose 'Personal' to store to the Current User store or 'Personal -> Registry' to store to the Local Machine store
  13. Click OK
  14. Click Finish

The certificate is now usable, however unless the CA is already trusted ( which is the case for major Certificate providers ) your users will get notified that the certificate is not trusted. To avoid this go to the Website of the Certificate Authority that originally issued the certificate to obtain the CA.

Note about importing certificates Our implementation requires that a certificate be probably imported into a valid Microsoft Certificate Store. If you are importing a certificate that was created from a non-MS source (such as OpenSSL) , please assure that you export the certificate properly before attempting to import it into an MS Cert store. Check the docs for whatever SSL system you are using for this info.

See Also

Using FTP for .NET | FTP for .NET Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Windows 95/98 Security Compatibility

Until recently, the SSL/TLS Security Support Provider on the Windows 9x platforms was not fully implemented. Microsoft addressed this issue through a series of procedures we will explain below.

The following steps must be incorporated before installing any secure-dependent products.

  1. Make sure you have the latest Dart update from http://www.dart.com.
  2. Install Internet Explorer 5.01 or higher with 128-bit encryption.
  3. Install Directory Service Client software for Windows 9x. This program can be found on any Windows 2000 CD in the \Clients\Win9x folder. The name of this application is DSCLIENT.EXE. If you do not have a Windows 2000 CD, please contact Microsoft Developer Support.
  4. Enable the SChannel Security Support Provider in the registry.
    • Start Registry Editor (Regedit.exe).
    • Locate the following key in the registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders
    • On the Edit menu, click Modify, and then modify the following registry value:
      • Value Name: Security Providers
      • Data Type: REG_SZ
      • Value: Append ",schannel.dll" (with comma, no quotes) to previous string.

Note: Certificates for use with the SSL/TLS protocols on Windows 95, 98, Me, and Windows NT 4.0 must be marked exportable. Windows 2000 SSL/TLS protocols do not have this requirement.

See Also

Using FTP for .NET | FTP for .NET Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Using Events In PowerTCP

There are three kinds of events you may encounter when using the Ftp component:

  1. Process Completed Events
  2. Property Changed Events
  3. Reporting Events

Process Completed Events are used to notify the application that a process has completed. All of the EndXXX events (EndPut, EndGet, EndList, and EndInvoke) are completion events. For example, when transferring a file asynchronously using the BeginGet method, the EndGet event will be raised to notify the application that the transfer has completed, either successfully or unsuccessfully. A FileEventArgs object is made available to your event handler containing information about the operation.

Property Changed Events are used to notify the application that the value of a property has changed. The ConnectedChanged and BusyChanged events are property changed events. For example, every time the Connected property of the Ftp component changes, this event will be raised.

Reporting Events are used to report while an operation is occurring. The Progress and Trace events are both reporting events. For example, when a file transfer is in progress the Progress event will periodically be raised to notify the application of the current status of the file transfer. A FtpProgressEventArgs object will be made available to this event containing information about the operation.

This topic (and related subtopics) describe usage of these events.

In This Section

Using Events Within The Visual Studio .NET Environment
Describes how to use PowerTCP events within the Visual Studio .NET environment.
Using Events When The Ftp Component Is Used As A Reference
Describes the extra steps required to use events when using the Ftp component as a reference.
Using EndXXX Events
Describes how to use the EndXXX events (EndGet, EndPut, EndList, and EndInvoke) which are raised upon the completion of a method.
Using The Progress Event
Describes how to use the Progress event to monitor and display file transfer information.
Using The Trace Event
Describes how to use the Trace event to monitor data send and received over the control connection.
Using The ConnectedChanged Event
Describes how to use the ConnectedChanged event to monitor the connection status of the control connection.
Using The BusyChanged Event
Describes how to use the BusyChanged event to monitor if the Ftp component is busy performing an operation.
Using the CertificateRequested and CertificateRecieved Events
Describes how to use the CertificateRequested and CertificateReceived events to manage secure communications.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Using Events Within The Visual Studio .NET Environment

The Visual Studio .NET environment has built-in support for "wiring-up" and using component events, making their use simple.

To "wire-up" an event using the Visual Studio environment using VB.NET, use the following steps. (Steps for C# follow).

  1. Start a new VB.NET project and add the Ftp component to the form (see "Using The Ftp component Within Visual Studio .NET" for information of how to do this.
  2. Navigate to View then select Code to switch to code view.
  3. From the "drop-down" boxes at the top of the Code Window, select the instance of the Ftp component from the box on the left, then the name of the event you would like to "wire-up" from the box on the right (see screenshot below).

  4. After doing this, the Visual Studio .NET environment will transparently create the necessary code to "wire-up" the event. The code should look similiar to the following (using the EndInvoke event as an example).
    Private Sub Ftp1_EndInvoke(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.InvokeEventArgs) Handles Ftp1.EndInvoke
End Sub
  5. Now you can use the BeginInvoke method and handle the response in the EndInvoke event.

To "wire-up" an event using the Visual Studio environment using C#, use the following steps. (Steps for C# follow).

  1. Start a new VB.NET project and add the Ftp component to the form (see "Using The Ftp component Within Visual Studio .NET" for information of how to do this.
  2. Click the component icon which was created on the panel underneath the form.
  3. On the Properties Window click the "lightning bolt" icon to display all events for the Ftp component.
  4. Double-click the event you wish to "wire-up" (see screenshot below).

  5. After doing this, the Visual Studio .NET environment will automatically create the necessary code to "wire-up" the event. The code should look similiar to the following (using the EndInvoke event as an example).
    private void ftp1_EndInvoke(object sender, Dart.PowerTCP.Ftp.InvokeEventArgs e)
{
}
  6. Now you can use the BeginInvoke method and handle the response in the EndInvoke event.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Using Events When The Ftp Component Is Used As A Reference

Using Events When Using The Ftp Component As A Reference

If you are using the Ftp component as a class (instead of adding it to the project as a component), and would like to use events, you must "wire-up" the event yourself. This topic addresses how to do this using either VB.NET or C#. Note: You do NOT need to "wire-up" the events yourself if using Visual Studio .NET and you are dragging an instance of the Ftp component onto the form. In this case all event subscription will be handled by the environment.

To use events when using the Ftp component as a class and creating a VB.NET Windows Application, use the following steps (steps for C# below).

  1. Start a new VB.NET project and add the Ftp component as a reference (see "Adding The Ftp Component As A Reference Within Visual Studio .NET" for information of how to do this.
  2. Navigate to the View menu then select Code to switch to code view.
  3. Create an instance of the Ftp component. Be sure to use the WithEvents keyword such as:

    Private WithEvents Ftp1 As New Dart.PowerTCP.Ftp.Ftp()
  4. Now you must create a method that implements the appropriate delegate. The first step for doing this is to determine which event you would like to "wire-up". For the purposes of this walkthrough, the EndInvoke event will be used, although other events would work similarly.
  5. Navigate to the EndInvoke event in the Reference section.
  6. The syntax definition for the appropriate language specifies which delegate is implemented by the event, for example the VB.NET syntax for the EndInvoke event is:

    public Event Ftp.EndInvoke As InvokeEventHandler

    This means, to "wire-up" the EndInvoke event, you must first create a method that implements the InvokeEventHandler delegate.
  7. Navigate to the reference listing for the InvokeEventHandler delegate. This listing will tell you what your event-handler method should look like. According to the InvokeEventHandler delegate, your method must accept two arguments (an object and an InvokeEventArgs) and return nothing, so create a method that does this. This method should look similar to the following:

    Private Sub MyInvokeHandler(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.InvokeEventArgs)
End Sub
  8. Finally, the event handler must "subscribe" to the event. In VB.NET, this can simply be done by using the "Handles " keyword next to the event handler as such:

    Private Sub MyInvokeHandler(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.InvokeEventArgs) Handles ftp1.EndInvoke
End Sub
  9. Now the BeginInvoke method can be used, and the EndInvoke event will be raised upon completion.

To use events when using the Ftp component as a reference and creating a C# Windows Application, use the following steps.

  1. Start a new VB.NET project and add the Ftp component as a reference (see "Adding The Ftp Component As A Reference Within Visual Studio .NET" for information of how to do this.
  2. Navigate to the View menu then select Code to switch to code view.
  3. Create an instance of the Ftp component such as:

    private Dart.PowerTCP.Ftp.Ftp Ftp1 = new Dart.PowerTCP.Ftp.Ftp();
  4. Now you must create a method that implements the appropriate delegate. The first step for doing this is to determine which event you would like to "wire-up". For the purposes of this walkthrough, the EndInvoke event will be used, although other events would work similarly.
  5. Navigate to the EndInvoke event in the Reference section.
  6. The syntax definition for the appropriate language specifies which delegate is implemented by the event, for example the C# syntax for the EndInvoke event is:

    public event InvokeEventHandler EndInvoke;

    This means, to "wire-up" the EndInvoke event, you must first create a method that implements the InvokeEventHandler delegate.
  7. Navigate to the reference listing for the InvokeEventHandler delegate. This listing will tell you what your event-handler method should look like. According to the InvokeEventHandler delegate, your method must accept two arguments (an object and an InvokeEventArgs) and return void, so create a method that does this. This method should look similar to the following:

    private void MyInvoke(object sender, Dart.PowerTCP.Ftp.InvokeEventArgs e)
{
}
  8. Finally, the event handler must "subscribe" to the event, in C#, this can be done as such (put this code in your form initialization):
    ftp1.EndInvoke += new Dart.PowerTCP.Ftp.InvokeEventHandler(this.MyInvoke);
  9. Now the BeginInvoke method can be used, and the EndInvoke event will be raised upon completion.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


EndXXX Events

An EndXXX event is a generic term to describe any event used by the PowerTCP FTP for .NET that begins with the word "End". These events are reserved to notify the application of a process being completed. In addition, all EndXXX events are raised by the completion of a corresponding BeginXXX method. The EndXXX events used by the Ftp component are as follows:

Event | Raised By | Purpose
EndGet Event | Use of the BeginGet method | Notifies the application that a file, multiple files, or a stream has been retrieved.
EndPut Event | Use of the BeginPut method | Notifies the application that a file, or multiple files, has been stored, or the data connection is ready to be written to.
EndInvoke Event | Use of the BeginInvoke method | Notifies the application that a command has been sent to the server and the response has been received.
EndList Event | Use of the BeginList method | Notifies the application that a listing has been retrieved from the server.

Comparison With Other Techniques:

PowerTCP products provide a unique technique for handling asynchronous completion notification:

  1. Compared to the delegate technique, by using Events for completion notification, PowerTCP gives developers strong environment support for adding event handlers.
  2. Before raising the completion event, the component calls the (internal) delegate's EndInvoke method, capturing any Exceptions thrown during asynchronous execution. Using this technique, PowerTCP ensures all asynchronous calls are properly terminated, and consequently eliminates one programming step that would normally have to be accomplished by our users.
  3. When any BeginXXX method is used, PowerTCP checks for the appropriate event handler and throws an InvalidOperationException if none is found, ensuring proper usage.

We think this approach to asynchronous communications programming provides a superior value to our users, where asynchronous programming has become as easy as it can get.

Special Notes About EndXXX Events:

Be sure to check the e.Exception property for exceptions that occurred during the asynchronous method call. If the operation failed to complete, the presence of an Exception object may be your only indication that the operation failed.

It is a very good programming practice to surround your event code with a try/catch block. If you do not do so and generate an exception within your code, a default exception handler will display your exception to the user of your application using a MessageBox.

For A Step-By-Step Walkthrough Of Using An Asynchronous Method With The Corresponding EndXXX Event, See The Following Topics

Storing Files Asynchronously
Provides a step-by-step walkthrough of using the BeginPut method along with the EndPut event.
Retrieving Files Asynchronously
Provides a step-by-step walkthrough of using the BeginGet method along with the EndGet event.
Sending Commands Asynchronously
Provides a step-by-step walkthrough of using the BeginInvoke method along with the EndInvoke event.
Retrieving Listings Asynchronously
Provides a step-by-step walkthrough of using the BeginList method along with the EndList event.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Progress Event

The Progress event is a useful event for displaying to the user file transfer status, especially in cooperation with a ProgressBar object. The following walkthrough demonstrates using the Progress event with ProgressBar objects.

To use the Progress event to display file transfer status to the user, use the following steps.

  1. Create a Windows Application that transfers a file. For a quick walkthrough, see either of the topics Storing Files Overview or Retrieving Files Overview.
  2. Add a ProgressBar object to the application.
  3. Add the code necessary to "wire-up" the Progress event. For instructions on how to do this, see the topic Using Events Within The Visual Studio .NET Environment.
  4. Add the code to the Progress event to update the ProgressBar object with the current status of the file. ProgressBar.Minimum will equal 0, ProgressBar.Maximum will equal Length (which is the length of the currently transferring file), and ProgressBar.Value will equal Position (which is the marker within the file at which the transfer is occurring). When finished, the Progress event will look like the following:
    [C#]
private void ftp1_Progress(object sender, Dart.PowerTCP.Ftp.FtpProgressEventArgs e)
{
   progressBar1.Minimum = 0;
   progressBar1.Maximum = (int)e.Length;
   progressBar1.Value = (int)e.Position;
}
[Visual Basic]
Private Sub ftp1_Progress(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FtpProgressEventArgs) Handles ftp1.Progress
   progressBar1.Minimum = 0
   progressBar1.Maximum = e.Length
   progressBar1.Value = e.Position
End Sub
  5. Compile and run the application. When transferring a file, the ProgressBar object should reflect the current status of the transfer. Note: If transferring multiple files, you may want to have two ProgressBar objects, one to reflect the status of the current file transferring, and the second to reflect the transfer of all files. This second ProgressBar would use FtpProgressEventArg.TotalFiles for ProgressBar.Maximum and FtpProgressEventArg.CurrentFile for ProgressBar.Value.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Trace Event

The Trace event is useful if you need to log the commands sent and received by the Ftp component. This could be useful if you want to write a text file logging all commands, or if you wanted to display to the user commands send and received. This second usage is quite common in FTP applications, and will be demonstrated in this walkthrough.

To use the Trace event to display commands sent and received to the user, use the following steps.

  1. Create a Windows Application that transfers a file, or otherwise sends commands to the server. For a quick walkthrough, see either of the topics Storing Files Overview, Retrieving Files Overview, or Sending Commands Overview.
  2. Add a multiline TextBox to the application.
  3. Add the code necessary to "wire-up" the Trace event. For instructions on how to do this, see the topic Using Events Within The Visual Studio .NET Environment.
  4. Add the code to the Trace to update the TextBox with the data sent/received. When finished, the Trace event will look like the following:
    [C#]
private void ftp1_Trace(object sender, Dart.PowerTCP.Ftp.SegmentEventArgs e)
{
   textBox1.SelectionStart = 0xffff;
   textBox1.SelectedText = e.ToString();
}
[Visual Basic]
Private Sub Ftp1_Trace(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.SegmentEventArgs) Handles Ftp1.Trace
   textBox1.SelectionStart = 0xffff
   textBox1.SelectedText = e.ToString()
End Sub
  5. Compile and run the application. Every time communication occurs with the server it should be displayed in the TextBox.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


ConnectedChanged Event

The ConnectedChanged event is useful if you would like to display the connection status to the user, or take some action based on whether a connection was made or closed. The following walkthrough demonstrates writing the status of the connection to a TextBox to display to the user.

To use the ConnectedChanged event to display the current connection status, use the following steps.

  1. Create a Windows Application that transfers a file, or otherwise sends commands to the server. For a quick walkthrough, see either of the topics Storing Files Overview, Retrieving Files Overview, or Sending Commands Overview.
  2. Add a multiline TextBox to the application.
  3. Add the code necessary to "wire-up" the ConnectedChanged event. For instructions on how to do this, see the topic Using Events Within The Visual Studio .NET Environment.
  4. Add the code to the ConnectedChanged event to update the TextBox with the connection status when it changes When finished, the ConnectedChanged event should look like the following:
    [C#]
private void ftp1_ConnectedChanged(object sender, System.EventArgs e)
{
   string text;

   // Check the connection status
   if(ftp1.Connected)
      text = "Connection made to " + ftp1.Connection.RemoteEndPoint.ToString() + "\r\n";
   else
      text = "Connection closed\r\n";

   // Write the connection status to the text box
   textBox1.SelectionLength = text.Length;
   textBox1.SelectedText = text;
}
[Visual Basic]
Private Sub Ftp1_ConnectedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Ftp1.ConnectedChanged
   Dim text As string

   ' Check the connection status
   If Ftp1.Connected Then
      text = "Connection made to " + Ftp1.Connection.RemoteEndPoint.ToString() + VbCrLf
   Else
      text = "Connection closed" + VbCrLf

   ' Write the connection status to the text box
   textBox1.SelectionLength = text.Length
   textBox1.SelectedText = text
End Sub
  5. Compile and run the application. Every time a connection is made or closed, it should be displayed in the TextBox.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


BusyChanged Event

The BusyChanged event is useful if you would like to display when the Ftp component is available to process another request to the user, or take some action based on whether the Ftp component is busy or not busy. The Busy property reflects the current "busy-status" of the Ftp component. The Ftp component is considered to be busy when performing an operation which requires communication with the server. For example, if the Ftp component is being used to send a large file the Busy property would be true. If another store was attempted while the Busy property is true a BusyException would be thrown. This can be avoided by either checking the Busy property before calling a method that you believe may throw a BusyException, or by using the BusyChanged event to notify the application when the Ftp component is not busy, and take action at that point. The following walkthrough demonstrates writing the current "busy-status" to a TextBox.

To use the BusyChanged event to display the current "busy-status", use the following steps.

  1. Create a Windows Application that transfers a file, or otherwise sends commands to the server. For a quick walkthrough, see either of the topics Storing Files Overview, Retrieving Files Overview, or Sending Commands Overview.
  2. Add a multiline TextBox to the application.
  3. Add the code necessary to "wire-up" the BusyChanged event. For instructions on how to do this, see the topic Using Events Within The Visual Studio .NET Environment.
  4. Add the code to the BusyChanged event to update the TextBox with the "busy-status" when it changes. When finished, the BusyChanged event should look like the following:
    [C#]
private void ftp1_BusyChanged(object sender, System.EventArgs e)
{
   string text = "Busy Status = " + ftp1.Busy.ToString() + "\r\n";

   // Write the busy status to the text box
   textBox1.SelectionLength = text.Length;
   textBox1.SelectedText = text;
}
[Visual Basic]
Private Sub Ftp1_BusyChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Ftp1.BusyChanged
   Dim text As string
   text = "Busy Status = " + Ftp1.Busy.ToString() + "VbCrLf"

   ' Write the busy status to the text box
   textBox1.SelectionLength = text.Length
   textBox1.SelectedText = text
End Sub
  5. Compile and run the application. Every time the Ftp component becomes busy or not busy, it will be displayed in the text box. (This can also be used for some interesting effects, such as displaying a red "light" when busy and a green "light" when not busy).

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


CertificateRequested and CertificateReceived Events

For information on how to use the CertificateReceived event, see Creating a Secure FTP Client.

For information on how to use the CertificateRequested event, see Handling Client Authentication.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Session Management

The Ftp component provides an excellent compromise between the ease-of-use of automated session management and the control of defining your own sessions. It is designed to make session-management transparent to the user, as all FTP sessions are managed internally. However, if you would like to achieve a higher-level of control over sessions, this following subtopics address this issue.

In This Section

Session Management Overview
Provides an overview about how the Ftp component deals with session management.
Closing A Ftp.Connection
Provides instructions on how to end an FTP session explicitly.
Aborting A Data Transfer
Provides instructions on how to close a data connection while maintaining the control connection.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Session Management Overview

When using many products that provide FTP capability, there is a concept of an FTP session. Typically, when considering session management, there are a few issues that may come into mind. This topic attempts to address any session management concerns by discussing how the Ftp component manages session.

Complete Session Management The Ftp component removes any concern for errors/problems that could occur due to a faulty log in or log out. Simply specify the server, user name, and password, then call any method of the Ftp component. When communication needs to occur with the FTP server login will occur transparently. The component will remain logged in to the FTP server until a logout is specifically requested or the Ftp component is destroyed. If you are currently logged in to an FTP server and need to log out and log in to a different server, simply specify the server, port, username, and password of the new server and the next time communication needs to occur, the Ftp component will automatically log out of the previous server, and log in to the new one, without any extra code required within your application.

Closing A Session Explicitly Of course, not everybody will want to rely on the Ftp component to close a connection. Sometimes it may be necessary to explicitly close the connection. You can gracefully close the connection using the Close method. See the topic Closing A Ftp.Connection for a step-by-step description of how to so this.

Aborting A Session Abruptly It may be necessary to close the connection immediately (without waiting for the response from the server that is expected using the Close method). In these cases, you can use the Abort method to immediately close all connections.

Aborting A Data Transfer You may wish to simply abort an in-progress file transfer, but maintain the connection to the FTP server. For this, use the AbortTransfer method to stop the file transfer, but maintain the session. See the topic Aborting A Data Transfer for a step-by-step description of how to so this.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Closing A Connection

Using the Close method to terminate a session between a client and an FTP server is the recommended method of closing a connection. The Close method sends the "QUIT" command to the FTP server, to which the server will reply either positively or negatively. If the server replies positively, the connection is gracefully closed by the server. If the server replies negatively, an exception is thrown and other means must be taken to close the connection (such as the Abort method).

To use the Close method to gracefully close all connections with the FTP server , use the following steps.

  1. It may be helpful, as an extra precaution, to check the connection status to be sure the Ftp component is connected before closing, this can be done using the Connected property.
    [C#]
if (ftp1.Connected)
{
   // Call close here

   ftp1.Close();
}
[Visual Basic]
If Ftp1.Connected Then
   ' Call close here
     Ftp1.Close()
End If
  2. If the Ftp component is connected, attempt to close the connection. Be sure to provide error checking, in case a close is unable to occur.
    [C#]
if (ftp1.Connected)
{
    // Call close here
    try
    {
       ftp1.Close();
    }
    catch(Exception ex)
    {
        // If this is executed, the close failed. You could call Abort to
        // abruptly close the connection.
        ftp1.Abort();
    }
}
[Visual Basic]
If Ftp1.Connected Then
   ' Call close here
   Try
      Ftp1.Close()
   Catch ex As Exception
        // If this is executed, the close failed. You could call Abort to
        // abruptly close the connection.
        Ftp1.Abort()
   End Try
End If

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Aborting A Data Transfer

The AbortTransfer method is used to abort any file transfer in progress while maintaining the control connection.

To use the AbortTransfer method to abort a file transfer, use the following steps.

  1. Create an FTP application that transfers files. See the either of the topics Storing Files Overview or Retrieving Files Overview for instructions on how to do this.
  2. If your application uses synchronous file transfer methods, be sure the DoEvents property is set to true, so user interface events can be processed. If your application uses asynchronous file transfer methods, this property does not need to be set.
  3. Add a button to your application. This button will be used to abort the transfer.
  4. Add the following code to the button's "onclick" event handler.
    [C#]
ftp1.AbortTransfer();
[Visual Basic]
Ftp1.AbortTransfer()
  5. Compile and run your application
  6. Click the button created in step 3.
  7. The file transfer should have been aborted. To check, access either the FtpFile object returned from the method (if using synchronous methods) or the FtpFile object made accessible in the EndXXX event (if using asynchronous methods). If the FtpFile.Position property equals the FtpFile.Length property, the file was fully transferred. If the FtpFile.Position is less than the FtpFile.Length property, the file transfer was aborted. If the FtpFile.Count is equal to -1, the file was aborted before transfer begun (usually only possible when transferring multiple files).

Note: If you are reading or writing directly to the data connection, use the Ftp.AbortTransfer method to close the connection if you only want to read a portion of the file, then close (when writing to the data connection, it is adequate to simply close the connection without sending an abort signal).

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Accessing The TCP Connection

The Ftp component uses the Tcp component for TCP communication. This component is exposed through the Connection property. This property is useful because it allows retrieval of TCP-level information about the client and server, that can then be used within the application.

NOTE: It is not recommended to use methods of the Tcp component to send commands to an FTP server. Due to the internal workings of the Ftp component, this will not work properly. Also, do not change properties of the Tcp component. For example, one of the properties of the Tcp component is the ReceiveTimeout property which specifies how long the Tcp component should attempt to receive before throwing an exception. Setting this property will have unexpected results. Any functionality needed in the Ftp component, has been built-in. In this example, you could use the Timeout property of the Ftp component to specify how long to attempt to receive a response before throwing an exception.

In This Section

Accessing TCP-Level Information
Shows how the exposed Tcp component can be used within your application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Accessing TCP-Level Information

The TCP connection (exposed by Connection) is useful for several reasons. For example, the Connection property can be used to send/receive data directly over TCP (this is NOT recommended, however). Also, the Connection property can be used to retrieve information about the local and remote endpoints.

To Use The Connection Property To Display Information About Endpoints, use the following steps

  1. Create a Windows Application that transfers a file, or otherwise sends commands to the server. For a quick walkthrough, see either of the topics Storing Files Overview, Retrieving Files Overview, or Sending Commands Overview.
  2. Add a multiline TextBox to the application.
  3. Add the code necessary to "wire-up" the ConnectedChanged event. For instructions on how to do this, see the topic Using Events Within The Visual Studio .NET Environment.
  4. Add the code to the ConnectedChanged event to update the TextBox with the current connection state. When finished, the ConnectedChanged event should look like the following:
    [C#]
private void ftp1_ConnectedChanged(object sender, System.EventArgs e)
{
   string text;

   //  Check the connection status
   if(ftp1.Connected)
   {
      // Display the local endpoint
      text = "Connection made from " + ftp1.Connection.LocalEndPoint.ToString() + "\r\n";

      // Display the remote endpoint
      text += "Connection made to " + ftp1.Connection.RemoteEndPoint.ToString() + "\r\n";
   }
   else
      text = "Connection closed\r\n";

   // Write the connection status to the text box
   textBox1.SelectionLength = text.Length;
   textBox1.SelectedText = text;
}
[Visual Basic]
Private Sub Ftp1_ConnectedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Ftp1.ConnectedChanged
   Dim text As string

   ' Check the connection status
   If Ftp1.Connected Then
      ' Display the local endpoint
      text = "Connection made from " + Ftp1.Connection.LocalEndPoint.ToString() + "vbCrLf"

      ' Display the remote endpoint
      text += "Connection made to " + Ftp1.Connection.RemoteEndPoint.ToString() + "vbCrLf"
   Else
      text = "Connection closed" + vbCrLf

   ' Write the connection status to the text box
   textBox1.SelectionLength = text.Length
   textBox1.SelectedText = text;
End Sub
  5. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Proxy Support Overview

The Ftp component provides full, "built-in" support for FTP proxy servers (often referred to as "proxies" or "FTP proxies"). If communication needs to occur through a proxy, simply set the appropriate properties of the FtpProxy object and the necessary proxy communication will take place. If your proxy server type is not supported, you can still connect using the RawConnect method and code up your own requirements. Dart's support staff can help you deal with non-standard proxies.

In This Section

Using The Built-In FtpProxy Object
Shows how to set the properties of the FtpProxy object to enable transparent communication with a proxy server.
Connecting Using Ftp.RawConnect
Shows how to connect to non-standard proxies.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Using The Built-In FtpProxy Object

The FtpProxy object provides a simple way to manage proxy communication when communicating with FTP servers. Simply set the Type property to the correct proxy type, then set other FtpProxy properties if your proxy server configuration requires them, and proxy communication will occur transparently.

To use the FtpProxy object to transparently communicate through a proxy server, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Set the properties necessary to login to your FTP server. Do this by setting the Server, Username, and Password properties. There is no need to explicitly set the ServerPort property, as this property defaults to 21, the well-known port for FTP. (Of course, if your server is operating at a non-standard port, this property can be explicitly set).

    [Visual Basic, C#] The following code demonstrates setting the Server, Username, and Password properties. For the purposes of this walkthrough, simply put this code in the click event of the button you added to the form in step 1.

    [C#]
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";
[Visual Basic]
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"
  4. Set the properties of the FtpProxy object necessary for your proxy's configuration. In this example, the proxy is of type USERNOLOGON, which only requires the server name.
    [C#]
ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.User;
ftp1.Proxy.Server = "myproxy";
ftp1.Proxy.ServerPort = 5050;
[Visual Basic]
Ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.User
Ftp1.Proxy.Server = "myproxy"
Ftp1.Proxy.ServerPort = 5050
  5. Now call any other methods you may need to transfer files or send commands. Proxy communication will occur transparently.
  6. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Connecting Using RawConnect

Sometimes, you may need to communicate with an FTP server that is operating outside of the RFC spec. The Ftp component's auto-login feature only works with FTP servers operating within the spec. This means that the Ftp component is assuming a log in sequence as follows:

Make TCP connection
Receive greeting
Send USER <username>
Receive response
Send PASS <password>
Receive response
Successfully logged in
However, the server may have it's own proprietary login sequence, perhaps something like:

Make TCP connection
Receive greeting
Send USER <username>
Receive response
Send PASS <password>
Receive response
Send GROUP <group name>
Receive response
Successfully logged in
In this situation, the auto-login feature would fail and the Ftp component would not be able to log in. The client must use the RawConnect method to connect. The RawConnect method simply receives the greeting from the server, then allows the use of the Invoke method or BeginInvoke method to send the commands necessary to login.

To use the RawConnect method to log in to an FTP server operating outside of the RFC spec, use the following steps.

  1. Add the Ftp component to a new form. For instructions on how to do this see the topic Creating An Instance Of The Ftp Component.
  2. Add a button to the form.
  3. Connect to the server using the RawConnect method, specifying the server name and port to connect to. This method receives the greeting from the server.

    [Visual Basic, C#]

    [C#]
ftp1.RawConnect("MyFTPServer", 21);
[Visual Basic]
Ftp1.RawConnect("MyFTPServer", 21)
  4. Issue the necessary commands to log in which, using the contrived example above, would be USER <user name>, PASS <password>, and GROUP <group name>. These commands would be issued by using either the Ftp.Invoke method or the Ftp.BeginInvoke method. You must specify an FtpCommand using either of these methods. To send your own command, use FtpCommand.Null as the first parameter and the entire command as the second parameter. Be sure to check for exceptions on each command sent. If an exception was thrown on any command sent, log in was unsuccessful, if not log in was successful. Place the following code directly under the code from step 3.
    [C#]

try
{
   // Send USER command
   ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "USER blah");

   // Send PASS command
   ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "PASS mypass");

   //Send the proprietary GROUP command
   ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "GROUP admin");
}
catch(Dart.PowerTCP.Ftp.ProtocolException ProEx)
{
   Debug.WriteLine("Error. Log in Failed.");
   return;
}

// If it gets this far, log in worked.
Debug.WriteLine("Log in successful");
[Visual Basic]

Try
   ' Send USER command
   Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "USER blah")

   ' Send PASS command
   Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "PASS mypass")

   ' Send the proprietary GROUP command
   Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "GROUP admin")
Catch ProEx As Dart.PowerTCP.Ftp.ProtocolException
   Debug.WriteLine("Error. Log in Failed.")
   Exit Sub
End Try

' If it gets this far, log in worked.
Debug.WriteLine("Log in successful")
  5. After successfully logging in using the Ftp.RawConnect method, you can call any of the higher level methods to transfer files or send commands.
  6. Compile and run the application.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Using Interactive Tools

The Ftp component provides interactive tools that can be used during design-time and run-time to make testing and debugging your application easier.

In This Section

Using The Editor
Describes how to use the Editor to test FTP and FTP proxy connections during design-time in the Visual Studio .NET environment.
Using The TraceForm
Describes how to use the TraceForm to display a visual log of all data sent or received during run-time.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Using The Editor

The Editor is exposed by the Editor property. It is essentially an FTP application which can be used to test FTP and FTP proxy connections. This capability is only available if you are working in the Visual Studio .NET environment and are using the Ftp component by dragging an instance onto a form.

To use the Editor, use the following steps.

  1. Start a new Visual Studio .NET windows application
  2. Drag an instance of the Ftp component onto the form.
  3. The Ftp component icon should appear on a panel beneath the form. Click the icon to select it.
  4. In the Properties Window, click the Properties button if the properties of the Ftp component are not displayed. If the Properties Window is not visible, go to the View menu and choose Properties Window.
  5. Find the Editor property and click it with the mouse. Click the ellipsis that appears next to the Editor property. This should open a form that looks like the screenshot below.
    Note All properties set on the Editor will also be set in your Windows Application, so the Editor can be used as a "WYSIWYG" code editor to quickly create applications.

    The following UI features are available when using the Editor.

    Hostname: Enter the name (or dot address) of the server you wish to connect to.

    Username: Enter the username used to authenticate to the server.

    Password: Enter the password used to authenticate to the server.

    BlockSize: Enter the size of the buffer to use for socket and file I/O.

    Image: Check this box if you wish to transfer a binary file.

    AutoRestart: Check this box if the Editor should attempt to automatically restart partial file transfers.

    DoEvents: Check this box if the Editor should process UI events while executing a method.

    Passive: Check this box if the client should connect to the server for data connections, leave unchecked if the server should connect to the client.

    Refresh: Click this button to retrieve and display a file listing.

    Search Pattern: Enter a wildcard search pattern here to specify what type of files to retrieve in the listing.

    Root Path: Specify the directory to retrieve the listing for.

    Subdirectories: Cheeck this box to include directories under the Root Path in the listing.

    Put: Click this box to open a dialog box to choose a file to store on the server.

    Get: Click this box to open a dialog box to choose a file to retrieve from the server.

    Clear Connection Log: Clears the log which displays data sent and received over the control connection.

    Abort Data Transfer: Click this button to abort any in-process data transfers.

    Close Session: Click this button to end your FTP session by issuing the QUIT command.

    Abort Session: Click this button to abruptly end the FTP session by calling Abort.

    Proxy: Click this button to specify a proxy server.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Using The TraceForm

The TraceForm is included with PowerTCP FTP for .NET to help make debugging and tracing easier.

You can customize this form to show only data received, data sent, or all data. You can also save the data to a text log.

To use the TraceForm, use the following steps.

  1. Start a new Visual Studio .NET windows application
  2. Drag an instance of the Ftp component onto the form.
  3. Add a button to the form.
  4. In the button's "on-click" event, add the following code
    5. [C#]
// Create a new traceform
Dart.PowerTCP.Ftp.Forms.TraceForm tf = new Dart.PowerTCP.Ftp.Forms.TraceForm();

// Assign the TraceHandler event handler method to the Trace event
ftp1.Trace+= new SegmentEventHandler(tf.TraceHandler);

// Supply login information
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Ftp.Invoke a command
ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.NoOp);

// Close the connection
ftp1.Close();
[Visual Basic]
' Create a new traceform
Dim Tf As New Dart.PowerTCP.Ftp.Forms.TraceForm()

' Assign the TraceHandler event handler method to the Trace event
AddHandler Ftp1.Trace, AddressOf Tf.TraceHandler

' Supply login information
Ftp1.Server = "MyFtpServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Ftp.Invoke a command
Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.NoOp)

' Close the connection
Ftp1.Close();
  5. Compile and run the application, a form should appear (see screenshot below). When the button is clicked, data should be shown on the form.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Reference

This section contains reference documentation for all of the objects and classes that comprise the FTP for .NET. This section is intended solely for use as a class reference guide for use while building an application. It is NOT intended to give a "walkthrough" type description of usage. For a description of this type, see the higher-level topics.

In This Section

Dart.PowerTCP Namespace
Contains classes that support and enable creation of FTP applications in the .NET environment.

Related Sections

Using the Ftp Component
Contains links to higher-level topics which discuss usage of the Ftp component.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Dart.PowerTCP.Ftp

Dart.PowerTCP.Ftp Namespace

Namespace hierarchy

Classes

Class | Description
BusyException | Thrown whenever a method is called to perform an operation when an operation is already in progress.
Certificate | Represents a digital certificate.
CertificateReceivedEventArgs | Provides data for any event where certificates are received.
CertificateStore | Use the CertificateStore Object to gain access to a store of certificates on the local system.
EnhancedStream | Adds new methods on top of the Stream interface for type conversion, stream copying, and saving.
ExceptionEventArgs | Provides data for asynchronous event handlers.
FileEventArgs | This class is passed into the EndGet and EndPut events and provides data for these events.
Ftp | The Ftp component supports comprehensive files transfer activities with any FTP server.
FtpFile | Presents the results from an FTP file transfer.
FtpProgressEventArgs | This class is passed into the Progress event and provides data for that event.
FtpProxy | The FtpProxy class provides an easy way to manage communication with FTP proxy servers when transferring files.
FtpWebRequest | Provides an FTP-specific implementation of the WebRequest class.
FtpWebRequestCreator | Provides an FTP-specific implementation of the IWebRequest interface.
FtpWebResponse | Provides an FTP-specific implementation of the WebResponse class.
InvalidParameterTypeException | Thrown whenever a method is called with an invalid parameter.
Invoke | Presents the results from an Internet protocol Request/Response pair.
InvokeEventArgs | This class is passed into EndInvoke events and provides data for these event.
ListEntry | Represents each line of the textual listing received from an FTP server
ListEventArgs | This class is passed into the EndList event and provides data for this event.
Listing | Represents the textual listing received from an FTP server.
PipeStream | Represents a stream that wraps an internal stream.
PreviewEventArgs | This class is passed into the Preview event and provides data for that event.
ProtocolException | Used to throw protocol exceptions for upper-layer protocols like FTP, SMTP and POP3.
Proxy | Provides an easy way to manage communication with proxy servers
Response | Presents the response portion from an Internet protocol Request/Response pair.
Segment | Provides a reference to a data segment where data is sent or received over a TCP stream.
SegmentedStream | Used to provide advanced reading/writing capabilities to Stream-based objects.
SegmentEventArgs | Provides data for any event where data is sent or received.
Tcp | The Tcp component provides comprehensive Transmission Control Protocol support.
TcpStream | TcpStream implements sending and receiving of data through network sockets.
ZStreamException | Indicates a failure in ZLIB compression processing.

Delegates

Delegate | Description
CertificateReceivedEventHandler | Represents the method (event handler) that is raised when a certificate is received.
CertificateRequestedEventHandler | Represents the method (event handler) that is raised when a certificate is requested.
ConnectEventHandler | Represents the method (event handler) that is raised when the BeginConnect operation completes.
EventHandlerEx | Replaces System.EventHandler when the SynchronizingObject property is used.
FileEventHandler | Represents the method (event handler) that will be raised when the BeginPut or BeginGet operation completes.
FtpProgressEventHandler | Represents the method (event handler) that will be raised when file transfer information is available.
InvokeEventHandler | Represents the method (event handler) that will be raised when the Object.BeginInvoke operation completes.
ListEventHandler | Represents the method (event handler) that will be raised when the BeginList operation completes.
PreviewEventHandler | Represents the method (event handler) that will be raised to preview the next file transfer.
SegmentEventHandler | Represents the method (event handler) that is raised when data is received or sent.

Enumerations

Enumeration | Description
CertificateProvider | Enumerates the cryptographic providers allowed by Microsoft.
CertificateStoreLocation | Enumerates the possible locations for certificates
CertificateStoreName | Enumerates the names for commonly used certificate stores.
Compression | Enumerates the compression options for file transfers and listings.
EntryType | Enumerates whether the entry indicates a File, Directory, or is Unknown (if Format is Unknown).
FileType | Enumerates the type of file (ASCII, Image, or Ebcdic).
FtpCommand | Enumerates commands that can be sent using Invoke and BeginInvoke.
FtpFileStatus | Used to report status of a file transfer or deletion.
FtpProxyType | Enumerates the supported proxy types for FTP.
KeyUsage | Enumerates the uses for a key.
ListingFormat | Enumerates the perceived format of the listing.
ProxyType | Enumerates the supported proxy types.
SecureProtocol | Enumerates the type of encryption used in the secure product.
Security | Enumerates the security protocol and authentication types which can be used.
StoreType | Enumerates how a stored file should be treated if a file exists with the same name.

Syntax based on .NET Framework version 1.1.
Documentation version 3.0.0.0.


BusyException Class

Thrown whenever a method is called to perform an operation when an operation is already in progress.

For a list of all members of this type, see BusyException Members.

System.Object
System.Exception
System.ApplicationException
Dart.PowerTCP.Ftp.BusyException

[Visual Basic]
Public Class BusyException
    Inherits ApplicationException
[C#]
public class BusyException : ApplicationException
[C++]
public __gc class BusyException : public ApplicationException
[JScript]
public class BusyException extends ApplicationException

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

This exception is thrown if a method is called to perform an upper-layer protocol operation when an operation is already in progress. To keep this exception from being thrown, check the object.Busy property to see if an operation is already in progress.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

BusyException Members | Dart.PowerTCP.Ftp Namespace


BusyException Members

BusyException overview

Public Instance Constructors

BusyException Overloaded. Initializes a new instance of the BusyException class.

Public Instance Properties

HelpLink (inherited from Exception) | Gets or sets a link to the help file associated with this exception.
InnerException (inherited from Exception) | Gets the Exception instance that caused the current exception.
Message (inherited from Exception) | Gets a message that describes the current exception.
Source (inherited from Exception) | Gets or sets the name of the application or the object that causes the error.
StackTrace (inherited from Exception) | Gets a string representation of the frames on the call stack at the time the current exception was thrown.
TargetSite (inherited from Exception) | Gets the method that throws the current exception.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetBaseException (inherited from Exception) | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetObjectData (inherited from Exception) | When overridden in a derived class, sets the SerializationInfo with information about the exception.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Exception) | Overridden. Creates and returns a string representation of the current exception.

See Also

BusyException Class | Dart.PowerTCP.Ftp Namespace


BusyException Constructor

Initializes a new instance of the BusyException class.

Overload List

Initializes a new instance of the BusyException class.

[Visual Basic] Public Sub New()
[C#] public BusyException();
[C++] public: BusyException();
[JScript] public function BusyException();

Initializes a new instance of the BusyException class.

[Visual Basic] Public Sub New(ByVal String)
[C#] public BusyException(string);
[C++] public: BusyException(String*);
[JScript] public function BusyException(String);

Initializes a new instance of the BusyException class.

[Visual Basic] Public Sub New(ByVal String,ByVal Exception)
[C#] public BusyException(string,Exception);
[C++] public: BusyException(String*,Exception*);
[JScript] public function BusyException(String,Exception);

See Also

BusyException Class | Dart.PowerTCP.Ftp Namespace


BusyException Constructor ()

Initializes a new instance of the BusyException class.

[Visual Basic]
Public Sub New()
[C#]
public BusyException();
[C++]
public: BusyException();
[JScript]
public function BusyException();

See Also

BusyException Class | Dart.PowerTCP.Ftp Namespace | BusyException Constructor Overload List


BusyException Constructor (String)

Initializes a new instance of the BusyException class.

[Visual Basic]
Public Sub New( _
   ByVal message As String _
)
[C#]
public BusyException(
   string message
);
[C++]
public: BusyException(
   String* message
);
[JScript]
public function BusyException(
   String message
);

See Also

BusyException Class | Dart.PowerTCP.Ftp Namespace | BusyException Constructor Overload List


BusyException Constructor (String, Exception)

Initializes a new instance of the BusyException class.

[Visual Basic]
Public Sub New( _
   ByVal message As String, _
   ByVal e As Exception _
)
[C#]
public BusyException(
   string message,
   Exception e
);
[C++]
public: BusyException(
   String* message,
   Exception* e
);
[JScript]
public function BusyException(
   String message,
   Exception e
);

See Also

BusyException Class | Dart.PowerTCP.Ftp Namespace | BusyException Constructor Overload List


Certificate Class

Represents a digital certificate.

For a list of all members of this type, see Certificate Members.

System.Object
System.MarshalByRefObject
Dart.PowerTCP.Ftp.Certificate

[Visual Basic]
Public Class Certificate
    Inherits MarshalByRefObject
    Implements IDisposable
[C#]
public class Certificate : MarshalByRefObject, IDisposable
[C++]
public __gc class Certificate : public MarshalByRefObject, IDisposable
[JScript]
public class Certificate extends MarshalByRefObject, IDisposable

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

A digital certificate is a common credential that provides authentication. A trusted organization, called a Certificate Authority (CA), assigns a certificate to a user or entity who then uses the certificate to prove itself to the other side. The user or entity is able to do this using a digital certificate because the certificate contains information necessary for the client to authenticate the server, including the following information:

  • The Certificate Authority's name.
  • The entity to whom the certificate was issued.
  • The entity's public key.
  • The dates the certificate is valid.

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access certificates
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access certificates
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Certificate Members | Dart.PowerTCP.Ftp Namespace


Certificate Members

Certificate overview

Public Instance Constructors

Certificate Constructor Create a new Certificate object.

Public Instance Properties

Description | Returns the human-readable description of this certificate.
EmailAddress | Returns an email address string associated with the certificate.
ExpirationDate | Returns the date this certificate will cease to be valid.
Handle | Holds a handle to the Certificate object for advanced users.
Hash | Returns the certificate's 20-byte SHA hash value.
IssueDate | Returns the date this certificate was/will be made valid.
IssuedTo | Returns the domain name of the party this certificate was issued to.
IssuerName | Returns the name of the Certificate Authority that issued this certificate.
KeyUsage | Identifies for what purpose a key should be used.
Name | Returns the friendly name of this certificate.
SerialNumber | Returns the serial number of this certificate as a Hex-encoded string.
Version | Returns the version of X.509 certificate being used.

Public Instance Methods

CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose | Overloaded. Releases all resources associated with the object.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
ToString (inherited from Object) | Returns a String that represents the current Object.
Verify | Used to validate server credentials for certificates.

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


Certificate Constructor

Create a new Certificate object.

[Visual Basic]
Public Sub New( _
   ByVal handle As IntPtr _
)
[C#]
public Certificate(
   IntPtr handle
);
[C++]
public: Certificate(
   IntPtr handle
);
[JScript]
public function Certificate(
   IntPtr handle
);

Parameters

handle

Remarks

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


Certificate Properties

The properties of the Certificate class are listed below. For a complete list of Certificate class members, see the Certificate Members topic.

Public Instance Properties

Description | Returns the human-readable description of this certificate.
EmailAddress | Returns an email address string associated with the certificate.
ExpirationDate | Returns the date this certificate will cease to be valid.
Handle | Holds a handle to the Certificate object for advanced users.
Hash | Returns the certificate's 20-byte SHA hash value.
IssueDate | Returns the date this certificate was/will be made valid.
IssuedTo | Returns the domain name of the party this certificate was issued to.
IssuerName | Returns the name of the Certificate Authority that issued this certificate.
KeyUsage | Identifies for what purpose a key should be used.
Name | Returns the friendly name of this certificate.
SerialNumber | Returns the serial number of this certificate as a Hex-encoded string.
Version | Returns the version of X.509 certificate being used.

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


Description Property

Certificate.Description Property

Returns the human-readable description of this certificate.

[Visual Basic]
Public Property ReadOnly Description As String
[C#]
public string Description { get; }
[C++]
public: __property String* get_Description();
[JScript]
public function get Description() : String

Property Value

A string containing the description of this certificate.

Remarks

Sample data: "My Test Cert"

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access certificates
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access certificates
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


EmailAddress Property

Certificate.EmailAddress Property

Returns an email address string associated with the certificate.

[Visual Basic]
Public Property ReadOnly EmailAddress As String
[C#]
public string EmailAddress { get; }
[C++]
public: __property String* get_EmailAddress();
[JScript]
public function get EmailAddress() : String

Property Value

A string containing an email address.

Remarks

If the certificate has a Subject Alternative Name extension or Issuer Alternative Name, the first rfc822Name is returned. If no rfc822Name choice is found in the extension, the Subject Name field for the Email OID is returned. If the certificate does not have an email address embedded in the certificate, an empty string is returned.

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


ExpirationDate Property

Certificate.ExpirationDate Property

Returns the date this certificate will cease to be valid.

[Visual Basic]
Public Property ReadOnly ExpirationDate As Date
[C#]
public DateTime ExpirationDate { get; }
[C++]
public: __property DateTime get_ExpirationDate();
[JScript]
public function get ExpirationDate() : DateTime

Property Value

A System.DateTime value representing the date and time this certificate will cease to be valid.

Remarks

The date/time is reported in Greenwich Mean Time. If a certificate is received with ExpirationDate prior to the current date/time the certificate will be determined to be invalid.

Sample data: "5/13/2002 7:12:44 PM"

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access certificates
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access certificates
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


Handle Property

Certificate.Handle Property

Holds a handle to the Certificate object for advanced users.

[Visual Basic]
Public Property ReadOnly Handle As IntPtr
[C#]
public IntPtr Handle { get; }
[C++]
public: __property IntPtr get_Handle();
[JScript]
public function get Handle() : IntPtr

Remarks

Use this handle in place of PCCERT_CONTEXT values in relevant Crypto API functions.

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


Hash Property

Certificate.Hash Property

Returns the certificate's 20-byte SHA hash value.

[Visual Basic]
Public Property ReadOnly Hash As Byte()
[C#]
public byte[] Hash { get; }
[C++]
public: __property char get_Hash() __gc[];
[JScript]
public function get Hash() : Byte[]

Property Value

A byte array containing the certificate's hash value.

Remarks

The hash value of a certificate is a check sum created with a hash algorithm that the recipient uses to determine if the certificate has been altered.

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


IssueDate Property

Certificate.IssueDate Property

Returns the date this certificate was/will be made valid.

[Visual Basic]
Public Property ReadOnly IssueDate As Date
[C#]
public DateTime IssueDate { get; }
[C++]
public: __property DateTime get_IssueDate();
[JScript]
public function get IssueDate() : DateTime

Property Value

A System.DateTime value representing the starting date and time this certificate is valid.

Remarks

The date/time is reported in Greenwich Mean Time. If a certificate is received with IssueDate prior to the current date/time the certificate will be determined to be invalid.

Sample data: "5/13/2002 7:12:44 PM"

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access certificates
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access certificates
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


IssuedTo Property

Certificate.IssuedTo Property

Returns the domain name of the party this certificate was issued to.

[Visual Basic]
Public Property ReadOnly IssuedTo As String
[C#]
public string IssuedTo { get; }
[C++]
public: __property String* get_IssuedTo();
[JScript]
public function get IssuedTo() : String

Property Value

A string containing the domain name of the entity for whom the certificate was issued.

Remarks

When a certificate is received (causing the CertificateReceivedEvent to be raised) this property is checked to determine whether the certificate is valid for the remote host.

Sample data: "test.dart.com"

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access certificates
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access certificates
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


IssuerName Property

Certificate.IssuerName Property

Returns the name of the Certificate Authority that issued this certificate.

[Visual Basic]
Public Property ReadOnly IssuerName As String
[C#]
public string IssuerName { get; }
[C++]
public: __property String* get_IssuerName();
[JScript]
public function get IssuerName() : String

Property Value

A string containing the name of the issuer.

Remarks

This property returns the name of the entity that signed this certificate. When a certificate is received (causing the CertificateReceivedEvent to be raised) internally the certificate signature is validated with the specified CA. is checked against the local machine Trusted Root Authorities to determine if the certificate is from a valid issuer.

Sample data: "Thawte Test CA Root"

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access certificates
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access certificates
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


KeyUsage Property

Certificate.KeyUsage Property

Identifies for what purpose a key should be used.

[Visual Basic]
Public Property ReadOnly KeyUsage As KeyUsage
[C#]
public KeyUsage KeyUsage { get; }
[C++]
public: __property KeyUsage get_KeyUsage();
[JScript]
public function get KeyUsage() : KeyUsage

Property Value

A KeyUsage constant identifying the purpose of a key.

Remarks

Key usage is an extension to the x.509 certificate format specifying the purpose for a key. For example, KeyUsage.ServerAuth identifies that this certificate can be used to provide server authentication.

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


Name Property

Certificate.Name Property

Returns the friendly name of this certificate.

[Visual Basic]
Public Property ReadOnly Name As String
[C#]
public string Name { get; }
[C++]
public: __property String* get_Name();
[JScript]
public function get Name() : String

Property Value

A string containing the friendly name of this certificate.

Remarks

This is the human-readable name of the certificate. Sometimes this is the same as IssuedTo, if nothing was specified as a "friendlyname" when the certificate was created.

Sample data: "Thawte Server CA"

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access certificates
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access certificates
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


SerialNumber Property

Certificate.SerialNumber Property

Returns the serial number of this certificate as a Hex-encoded string.

[Visual Basic]
Public Property ReadOnly SerialNumber As String
[C#]
public string SerialNumber { get; }
[C++]
public: __property String* get_SerialNumber();
[JScript]
public function get SerialNumber() : String

Property Value

A Hex-encoded string containing the serial number of this certificate

Remarks

The serial number is an identification number used for a certificate. All certificates issued by a given CA have unique serial numbers so combining this property with IssuerName results in a string which can be used to uniquely identify a certificate.

Sample data: "08ea11"

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access certificates
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access certificates
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


Version Property

Certificate.Version Property

Returns the version of X.509 certificate being used.

[Visual Basic]
Public Property ReadOnly Version As Long
[C#]
public long Version { get; }
[C++]
public: __property __int64 get_Version();
[JScript]
public function get Version() : long

Property Value

A long representing the version of X.509 certificate.

Remarks

Currently, this property will return 1, 2, or 3. 1 indicates an X.509 v1 certificate, 2 indicates an X.509 v2 certificate, and 3 indicates an X.509 v3 certificate.

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access certificates
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access certificates
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


Certificate Methods

The methods of the Certificate class are listed below. For a complete list of Certificate class members, see the Certificate Members topic.

Public Instance Methods

CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose | Overloaded. Releases all resources associated with the object.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
ToString (inherited from Object) | Returns a String that represents the current Object.
Verify | Used to validate server credentials for certificates.

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


Dispose Method

Certificate.Dispose Method

Releases all resources associated with the object.

Overload List

Releases all resources associated with the object.

[Visual Basic] Public Sub Dispose() _ Implements IDisposable.Dispose
[C#] public void Dispose();
[C++] public: void Dispose();
[JScript] public function Dispose();

Releases all resources associated with the object.

[Visual Basic] Public Sub Dispose(ByVal Boolean)
[C#] public void Dispose(bool);
[C++] public: void Dispose(bool);
[JScript] public function Dispose(bool);

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


Dispose Method ()

Certificate.Dispose Method ()

Releases all resources associated with the object.

[Visual Basic]
Public Sub Dispose() _
    Implements IDisposable.Dispose
[C#]
public void Dispose();
[C++]
public: void Dispose();
[JScript]
public function Dispose();

Implements

IDisposable.Dispose

Remarks

The Object.Dispose method abruptly aborts the connection and releases all resources.

Object.Dispose should ONLY be used to release all resources used by the object, and the object should not be used subsequently. If an abort is desired, then Object.Close or Object.Connection.Close if available should be used to terminate activity and reset the object. The Object cannot be used once Object.Dispose() or Object.Dispose(true) are called.

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace | Certificate.Dispose Overload List


Dispose Method (Boolean)

Certificate.Dispose Method (Boolean)

Releases all resources associated with the object.

[Visual Basic]
Public Sub Dispose( _
   ByVal disposing As Boolean _
)
[C#]
public void Dispose(
   bool disposing
);
[C++]
public: void Dispose(
   bool disposing
);
[JScript]
public function Dispose(
   bool disposing
);

Remarks

The Object.Dispose method abruptly aborts the connection and releases all resources.

Object.Dispose should ONLY be used to release all resources used by the object, and the object should not be used subsequently. If an abort is desired, then Object.Close or Object.Connection.Close if available should be used to terminate activity and reset the object. The Object cannot be used once Object.Dispose() or Object.Dispose(true) are called.

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace | Certificate.Dispose Overload List


Verify Method

Certificate.Verify Method

Used to validate server credentials for certificates.

[Visual Basic]
Public Sub Verify()
[C#]
public void Verify();
[C++]
public: void Verify();
[JScript]
public function Verify();

Remarks

This method throws an exception if the certificate fails to acquire server credentials. A certificate could fail to acquire credentials for several reasons. For example, the certificate may not have a private key. A certificate must be made to acquire credentials before it can be used.

Exceptions

Exception Type | Condition
ArgumentException | The certificate failed to acquire server credentials.

See Also

Certificate Class | Dart.PowerTCP.Ftp Namespace


CertificateProvider Enumeration

Enumerates the cryptographic providers allowed by Microsoft.

[Visual Basic]
Public Enum CertificateProvider
[C#]
public enum CertificateProvider
[C++]
public __value enum CertificateProvider
[JScript]
public enum CertificateProvider

Remarks

The most commonly used provider for Microsoft certificates is the Microsoft Base Cryptographic Provider

Members

Member Name | Description
GemSafe | Gemplus GemSAFE Card CSP v1.0
Sicrypt | Infineon SICRYPT Base Smart Card CSP
Base | Microsoft Base Cryptographic Provider v1.0
BaseDssDh | Microsoft Base DSS and Diffie-Hellman Cryptographic Provider
BaseDss | Microsoft Base DSS Cryptographic Provider
DhSchannel | Microsoft DH SChannel Cryptographic Provider
EnhancedBase | Microsoft Enhanced Cryptographic Provider v1.0
EnhancedDssDh | Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider
EnhancedRsaAes | Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)
Exchange | Microsoft Exchange Cryptographic Provider v1.0
RsaSchannel | Microsoft RSA SChannel Cryptographic Provider
Strong | Microsoft Strong Cryptographic Provider
Schlumberger | Schlumberger Cryptographic Service Provider

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


CertificateReceivedEventArgs Class

Provides data for any event where certificates are received.

For a list of all members of this type, see CertificateReceivedEventArgs Members.

System.Object
System.EventArgs
Dart.PowerTCP.Ftp.CertificateReceivedEventArgs

[Visual Basic]
Public Class CertificateReceivedEventArgs
    Inherits EventArgs
[C#]
public class CertificateReceivedEventArgs : EventArgs
[C++]
public __gc class CertificateReceivedEventArgs : public EventArgs
[JScript]
public class CertificateReceivedEventArgs extends EventArgs

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

A CertificateReceivedEventArgs object is passed as a parameter to all events that report the receipt of a certificate from the remote server. Use this object to determine if the received certificate is valid. If any portion of the certificate is determined to be invalid (for example, if ExpirationDate has passed), the CertificateEventArgs.Accept property will be false, indicating that the certificate will not be accepted. Set Certificate.Accept to true to override this.

If your code causes an exception, it would be returned to the handling event without you seeing it. To preclude such a condition, you should ALWAYS use a try/ catch block around your event-handling code.

Example

The following example demonstrates creating a simple secure client.

[Visual Basic]
Private Sub CertificateReceived(ByVal sender As Object, ByRef e As CertificateReceivedEventArgs) Handles Tcp1.CertificateReceived
   Dim msg As String = "The certificate was invalid for the following reason(s)" + vbCrLf

   ' Check to see if the certificate is from a trusted root.
   If Not e.TrustedRoot Then
      msg += "This certificate is not from a trusted root" + vbCrLf
   End If

   ' Check to see if the certificate has a valid date.
   If Not e.ValidDate Then
      msg += "This certificate does not have a valid date" + vbCrLf
   End If

   ' Check to see if the certificate has a valid name.
   If Not e.ValidName Then
      msg += "This certificate does not have a valid name" + vbCrLf
   End If

   If msg <> "" Then
      msg += "Would you like to accept this certificate anyway?"
      If MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) = DialogResult.Yes Then
         e.Accept = True
      End If
   End If
End Sub

[C#]
private void CertificateReceived(object sender, CertificateReceivedEventArgs e)
{
   string msg = "The certificate was invalid for the following reason(s)\n";

   // Check to see if the certificate is from a trusted root.
   if(!e.TrustedRoot)
      msg+= "This certificate is not from a trusted root\n";

   // Check to see if the certificate has a valid date.
   if(!e.ValidDate)
      msg+= "This certificate does not have a valid date\n";

   // Check to see if the certificate has a valid name.
   if(!e.ValidName)
      msg+= "This certificate does not have a valid name\n";

   if(!e.Accept)
   {
      msg += "Would you like to accept this certificate anyway?";
      if(MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) == DialogResult.Yes)
         e.Accept = true;
   }
}

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

CertificateReceivedEventArgs Members | Dart.PowerTCP.Ftp Namespace


CertificateReceivedEventArgs Members

CertificateReceivedEventArgs overview

Public Instance Properties

Accept | Controls whether or not the certificate is accepted.
Certificate | The certificate received for authentication.
TrustedRoot | Returns whether or not the certificate is from a Trusted Root Authority.
ValidDate | Returns whether or not the current time-date is within the certificate's life span.
ValidName | Returns whether or not the name is valid.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

CertificateReceivedEventArgs Class | Dart.PowerTCP.Ftp Namespace


CertificateReceivedEventArgs Properties

The properties of the CertificateReceivedEventArgs class are listed below. For a complete list of CertificateReceivedEventArgs class members, see the CertificateReceivedEventArgs Members topic.

Public Instance Properties

Accept | Controls whether or not the certificate is accepted.
Certificate | The certificate received for authentication.
TrustedRoot | Returns whether or not the certificate is from a Trusted Root Authority.
ValidDate | Returns whether or not the current time-date is within the certificate's life span.
ValidName | Returns whether or not the name is valid.

See Also

CertificateReceivedEventArgs Class | Dart.PowerTCP.Ftp Namespace


Accept Property

CertificateReceivedEventArgs.Accept Property

Controls whether or not the certificate is accepted.

[Visual Basic]
Public Property Accept As Boolean
[C#]
public bool Accept { get; set; }
[C++]
public: __property bool get_Accept();
public: __property void set_Accept(bool );
[JScript]
public function get Accept() : bool
public function set Accept(bool);

Property Value

Boolean which determines whether or not a certificate is accepted.

Remarks

If ValidDate, ValidName, and TrustedRoot are all true, this property will return true meaning the certificate was accepted. Set this property to false to override this and reject the certificate.

If any of the properties ValidDate, ValidName, and TrustedRoot are false, this property will return false meaning the certificate was not accepted. Set this property to true to override this and accept the certificate.

Example

The following example demonstrates creating a simple secure client.

[Visual Basic]
Private Sub CertificateReceived(ByVal sender As Object, ByRef e As CertificateReceivedEventArgs) Handles Tcp1.CertificateReceived
   Dim msg As String = "The certificate was invalid for the following reason(s)" + vbCrLf

   ' Check to see if the certificate is from a trusted root.
   If Not e.TrustedRoot Then
      msg += "This certificate is not from a trusted root" + vbCrLf
   End If

   ' Check to see if the certificate has a valid date.
   If Not e.ValidDate Then
      msg += "This certificate does not have a valid date" + vbCrLf
   End If

   ' Check to see if the certificate has a valid name.
   If Not e.ValidName Then
      msg += "This certificate does not have a valid name" + vbCrLf
   End If

   If msg <> "" Then
      msg += "Would you like to accept this certificate anyway?"
      If MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) = DialogResult.Yes Then
         e.Accept = True
      End If
   End If
End Sub

[C#]
private void CertificateReceived(object sender, CertificateReceivedEventArgs e)
{
   string msg = "The certificate was invalid for the following reason(s)\n";

   // Check to see if the certificate is from a trusted root.
   if(!e.TrustedRoot)
      msg+= "This certificate is not from a trusted root\n";

   // Check to see if the certificate has a valid date.
   if(!e.ValidDate)
      msg+= "This certificate does not have a valid date\n";

   // Check to see if the certificate has a valid name.
   if(!e.ValidName)
      msg+= "This certificate does not have a valid name\n";

   if(!e.Accept)
   {
      msg += "Would you like to accept this certificate anyway?";
      if(MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) == DialogResult.Yes)
         e.Accept = true;
   }
}

See Also

CertificateReceivedEventArgs Class | Dart.PowerTCP.Ftp Namespace


Certificate Property

CertificateReceivedEventArgs.Certificate Property

The certificate received for authentication.

[Visual Basic]
Public Property Certificate As Certificate
[C#]
public Certificate Certificate { get; set; }
[C++]
public: __property Certificate* get_Certificate();
public: __property void set_Certificate(Certificate* );
[JScript]
public function get Certificate() : Certificate
public function set Certificate(Certificate);

Property Value

A Certificate object representing the received certificate.

Remarks

This property returns the certificate for which the CertificateReceived event was raised. In order for secure communication to continue with the sender, this certificate must be accepted by the receiver. Whether a certificate is accepted is controlled by the Accept property.

See Also

CertificateReceivedEventArgs Class | Dart.PowerTCP.Ftp Namespace


TrustedRoot Property

CertificateReceivedEventArgs.TrustedRoot Property

Returns whether or not the certificate is from a Trusted Root Authority.

[Visual Basic]
Public Property ReadOnly TrustedRoot As Boolean
[C#]
public bool TrustedRoot { get; }
[C++]
public: __property bool get_TrustedRoot();
[JScript]
public function get TrustedRoot() : bool

Property Value

A boolean indicating whether or not the certificate is from a Trusted Root Authority.

Remarks

Trusted Root Authorities are found in the certificate store named "Trust". When a certificate is received, the IssuedTo is compared to the Trusted Root Authorities. If found, this property will be true. If this property is false, the root is not on the trusted list and you should not accept the certificate unless the authority (IssuerName) is known to you and you trust it (in which case it should be added to the Trusted list).

Example

The following example demonstrates creating a simple secure client.

[Visual Basic]
Private Sub CertificateReceived(ByVal sender As Object, ByRef e As CertificateReceivedEventArgs) Handles Tcp1.CertificateReceived
   Dim msg As String = "The certificate was invalid for the following reason(s)" + vbCrLf

   ' Check to see if the certificate is from a trusted root.
   If Not e.TrustedRoot Then
      msg += "This certificate is not from a trusted root" + vbCrLf
   End If

   ' Check to see if the certificate has a valid date.
   If Not e.ValidDate Then
      msg += "This certificate does not have a valid date" + vbCrLf
   End If

   ' Check to see if the certificate has a valid name.
   If Not e.ValidName Then
      msg += "This certificate does not have a valid name" + vbCrLf
   End If

   If msg <> "" Then
      msg += "Would you like to accept this certificate anyway?"
      If MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) = DialogResult.Yes Then
         e.Accept = True
      End If
   End If
End Sub

[C#]
private void CertificateReceived(object sender, CertificateReceivedEventArgs e)
{
   string msg = "The certificate was invalid for the following reason(s)\n";

   // Check to see if the certificate is from a trusted root.
   if(!e.TrustedRoot)
      msg+= "This certificate is not from a trusted root\n";

   // Check to see if the certificate has a valid date.
   if(!e.ValidDate)
      msg+= "This certificate does not have a valid date\n";

   // Check to see if the certificate has a valid name.
   if(!e.ValidName)
      msg+= "This certificate does not have a valid name\n";

   if(!e.Accept)
   {
      msg += "Would you like to accept this certificate anyway?";
      if(MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) == DialogResult.Yes)
         e.Accept = true;
   }
}

See Also

CertificateReceivedEventArgs Class | Dart.PowerTCP.Ftp Namespace


ValidDate Property

CertificateReceivedEventArgs.ValidDate Property

Returns whether or not the current time-date is within the certificate's life span.

[Visual Basic]
Public Property ReadOnly ValidDate As Boolean
[C#]
public bool ValidDate { get; }
[C++]
public: __property bool get_ValidDate();
[JScript]
public function get ValidDate() : bool

Property Value

A boolean indicating whether or not the certificate has a valid date.

Remarks

If the current date-time is greater than IssueDate and less than ExpirationDate, this property will return true. Otherwise, this property will return false indicating an invalid date.

Example

The following example demonstrates creating a simple secure client.

[Visual Basic]
Private Sub CertificateReceived(ByVal sender As Object, ByRef e As CertificateReceivedEventArgs) Handles Tcp1.CertificateReceived
   Dim msg As String = "The certificate was invalid for the following reason(s)" + vbCrLf

   ' Check to see if the certificate is from a trusted root.
   If Not e.TrustedRoot Then
      msg += "This certificate is not from a trusted root" + vbCrLf
   End If

   ' Check to see if the certificate has a valid date.
   If Not e.ValidDate Then
      msg += "This certificate does not have a valid date" + vbCrLf
   End If

   ' Check to see if the certificate has a valid name.
   If Not e.ValidName Then
      msg += "This certificate does not have a valid name" + vbCrLf
   End If

   If msg <> "" Then
      msg += "Would you like to accept this certificate anyway?"
      If MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) = DialogResult.Yes Then
         e.Accept = True
      End If
   End If
End Sub

[C#]
private void CertificateReceived(object sender, CertificateReceivedEventArgs e)
{
   string msg = "The certificate was invalid for the following reason(s)\n";

   // Check to see if the certificate is from a trusted root.
   if(!e.TrustedRoot)
      msg+= "This certificate is not from a trusted root\n";

   // Check to see if the certificate has a valid date.
   if(!e.ValidDate)
      msg+= "This certificate does not have a valid date\n";

   // Check to see if the certificate has a valid name.
   if(!e.ValidName)
      msg+= "This certificate does not have a valid name\n";

   if(!e.Accept)
   {
      msg += "Would you like to accept this certificate anyway?";
      if(MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) == DialogResult.Yes)
         e.Accept = true;
   }
}

See Also

CertificateReceivedEventArgs Class | Dart.PowerTCP.Ftp Namespace


ValidName Property

CertificateReceivedEventArgs.ValidName Property

Returns whether or not the name is valid.

[Visual Basic]
Public Property ReadOnly ValidName As Boolean
[C#]
public bool ValidName { get; }
[C++]
public: __property bool get_ValidName();
[JScript]
public function get ValidName() : bool

Property Value

A boolean indicating whether or not the certificate has a valid name.

Remarks

This property is true if IssuedTo matches the URL for the Name property; Otherwise this property is false. If this property is false you can:

  • Check whether it is another (non-standard) name known to and trusted by you, and accept if it is.
  • Check whether the SslStream.Name property is an IP, in which case it should be compared against a DNS lookup of the domain name.

Example

The following example demonstrates creating a simple secure client.

[Visual Basic]
Private Sub CertificateReceived(ByVal sender As Object, ByRef e As CertificateReceivedEventArgs) Handles Tcp1.CertificateReceived
   Dim msg As String = "The certificate was invalid for the following reason(s)" + vbCrLf

   ' Check to see if the certificate is from a trusted root.
   If Not e.TrustedRoot Then
      msg += "This certificate is not from a trusted root" + vbCrLf
   End If

   ' Check to see if the certificate has a valid date.
   If Not e.ValidDate Then
      msg += "This certificate does not have a valid date" + vbCrLf
   End If

   ' Check to see if the certificate has a valid name.
   If Not e.ValidName Then
      msg += "This certificate does not have a valid name" + vbCrLf
   End If

   If msg <> "" Then
      msg += "Would you like to accept this certificate anyway?"
      If MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) = DialogResult.Yes Then
         e.Accept = True
      End If
   End If
End Sub

[C#]
private void CertificateReceived(object sender, CertificateReceivedEventArgs e)
{
   string msg = "The certificate was invalid for the following reason(s)\n";

   // Check to see if the certificate is from a trusted root.
   if(!e.TrustedRoot)
      msg+= "This certificate is not from a trusted root\n";

   // Check to see if the certificate has a valid date.
   if(!e.ValidDate)
      msg+= "This certificate does not have a valid date\n";

   // Check to see if the certificate has a valid name.
   if(!e.ValidName)
      msg+= "This certificate does not have a valid name\n";

   if(!e.Accept)
   {
      msg += "Would you like to accept this certificate anyway?";
      if(MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) == DialogResult.Yes)
         e.Accept = true;
   }
}

See Also

CertificateReceivedEventArgs Class | Dart.PowerTCP.Ftp Namespace


CertificateReceivedEventHandler Delegate

Represents the method (event handler) that is raised when a certificate is received.

[Visual Basic]
Public Delegate Function Sub  CertificateReceivedEventHandler( _
   ByVal sender As Object, _
   ByVal e As CertificateReceivedEventArgs _
)
[C#]
public delegate void CertificateReceivedEventHandler(
   object sender,
   CertificateReceivedEventArgs e
)
[C++]
public __gc __delegate void CertificateReceivedEventHandler(
   Object* sender,
   CertificateReceivedEventArgs* e
)

[JScript] In JScript, you can use the delegates defined by a type, but you cannot define your own.

Parameters

sender
The source of the event.
e
A CertificateReceivedEventArgs object that contains the event data.

Remarks

As Microsoft describes in their MSDN documentation, the event model in the .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed:

  • A class that holds the event data. This class must derive from the base class EventArgs.
  • A delegate that points to a method that provides the response to the event.

For more information about event handler delegates, see the Using Events In PowerTCP topic.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


CertificateRequestedEventHandler Delegate

Represents the method (event handler) that is raised when a certificate is requested.

[Visual Basic]
Public Delegate Function Sub  CertificateRequestedEventHandler( _
   ByVal sender As Object, _
   ByVal e As EventArgs _
)
[C#]
public delegate void CertificateRequestedEventHandler(
   object sender,
   EventArgs e
)
[C++]
public __gc __delegate void CertificateRequestedEventHandler(
   Object* sender,
   EventArgs* e
)

[JScript] In JScript, you can use the delegates defined by a type, but you cannot define your own.

Parameters

sender
The source of the event.
e
An EventArgs object that contains the event data.

Remarks

As Microsoft describes in their MSDN documentation, the event model in the .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed:

  • A class that holds the event data. This class must derive from the base class EventArgs.
  • A delegate that points to a method that provides the response to the event.

For more information about event handler delegates, see the Using Events In PowerTCP topic.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


CertificateStore Class

Use the CertificateStore Object to gain access to a store of certificates on the local system.

For a list of all members of this type, see CertificateStore Members.

System.Object
System.Collections.ArrayList
Dart.PowerTCP.Ftp.CertificateStore

[Visual Basic]
Public Class CertificateStore
    Inherits ArrayList
    Implements IDisposable
[C#]
public class CertificateStore : ArrayList, IDisposable
[C++]
public __gc class CertificateStore : public ArrayList, IDisposable
[JScript]
public class CertificateStore extends ArrayList, IDisposable

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

A certificate store is a permanent storage location where certificates, certificate revocation lists, and certificate trust lists are stored. Use this object by creating a new instance of CertificateStore, passing in the certificate store location, certificate store name, and key usage filter. This will create the CertificateStore object (which actually is a collection of Certificate objects which meet the criteria specified). Iterate through this collection to access each Certificate object.

The CertificateListForm control, included with this product, provides a convenient utility for managing local security certificates.

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access certificates
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access certificates
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

CertificateStore Members | Dart.PowerTCP.Ftp Namespace


CertificateStore Members

CertificateStore overview

Public Instance Constructors

CertificateStore Overloaded. Initializes a new instance of the CertificateStore class.

Public Instance Properties

Capacity (inherited from ArrayList) | Gets or sets the number of elements that the ArrayList can contain.
Count (inherited from ArrayList) | Gets the number of elements actually contained in the ArrayList.
IsFixedSize (inherited from ArrayList) | Gets a value indicating whether the ArrayList has a fixed size.
IsReadOnly (inherited from ArrayList) | Gets a value indicating whether the ArrayList is read-only.
IsSynchronized (inherited from ArrayList) | Gets a value indicating whether access to the ArrayList is synchronized (thread-safe).
Item | Overloaded. Gets or sets the element at the specified index.
Location | The location where the certificate store resides.
Name | The name of this certificate store.
SyncRoot (inherited from ArrayList) | Gets an object that can be used to synchronize access to the ArrayList.

Public Instance Methods

Add (inherited from ArrayList) | Adds an object to the end of the ArrayList.
AddRange (inherited from ArrayList) | Adds the elements of an ICollection to the end of the ArrayList.
BinarySearch (inherited from ArrayList) | Overloaded. Searches the entire sorted ArrayList for an element using the specified comparer and returns the zero-based index of the element.
Clear (inherited from ArrayList) | Removes all elements from the ArrayList.
Clone (inherited from ArrayList) | Creates a shallow copy of the ArrayList.
Contains (inherited from ArrayList) | Overloaded. Determines whether an element is in the ArrayList.
Contains | Overloaded. Determines whether an element is in the collection.
CopyTo (inherited from ArrayList) | Overloaded. Copies the entire ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array.
CopyTo | Overloaded. Copies the entire collection to a compatible one-dimensional Array, starting at the specified index of the target array.
Dispose | Overloaded. Releases all resources associated with the object.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetEnumerator (inherited from ArrayList) | Overloaded. Returns an enumerator for the entire ArrayList.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetRange (inherited from ArrayList) | Returns an ArrayList which represents a subset of the elements in the source ArrayList.
GetType (inherited from Object) | Gets the Type of the current instance.
IndexOf (inherited from ArrayList) | Overloaded. Searches for the specified Object and returns the zero-based index of the first occurrence within the entire ArrayList.
IndexOf | Overloaded. Searches for the specified value and returns the zero-based index of the first occurrence within the entire collection.
Insert (inherited from ArrayList) | Overloaded. Inserts an element into the ArrayList at the specified index.
Insert | Overloaded. Inserts an element into the collection at the specified index.
InsertRange (inherited from ArrayList) | Inserts the elements of a collection into the ArrayList at the specified index.
LastIndexOf (inherited from ArrayList) | Overloaded. Searches for the specified Object and returns the zero-based index of the last occurrence within the section of the ArrayList that contains the specified number of elements and ends at the specified index.
Remove (inherited from ArrayList) | Removes the first occurrence of a specific object from the ArrayList.
RemoveAt (inherited from ArrayList) | Removes the element at the specified index of the ArrayList.
RemoveRange (inherited from ArrayList) | Removes a range of elements from the ArrayList.
Reverse (inherited from ArrayList) | Overloaded. Reverses the order of the elements in the specified range.
SetRange (inherited from ArrayList) | Copies the elements of a collection over a range of elements in the ArrayList.
Sort (inherited from ArrayList) | Overloaded. Sorts the elements in a section of ArrayList using the specified comparer.
ToArray (inherited from ArrayList) | Overloaded. Copies the elements of the ArrayList to a new array of the specified type.
ToString (inherited from Object) | Returns a String that represents the current Object.
TrimToSize (inherited from ArrayList) | Sets the capacity to the actual number of elements in the ArrayList.

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace


CertificateStore Constructor

Creates a new CertificateStore object.

Overload List

Creates a new CertificateStore object.

[Visual Basic] Public Sub New()
[C#] public CertificateStore();
[C++] public: CertificateStore();
[JScript] public function CertificateStore();

Creates a new CertificateStore object.

[Visual Basic] Public Sub New(ByVal CertificateStoreLocation,ByVal CertificateStoreName)
[C#] public CertificateStore(CertificateStoreLocation,CertificateStoreName);
[C++] public: CertificateStore(CertificateStoreLocation,CertificateStoreName);
[JScript] public function CertificateStore(CertificateStoreLocation,CertificateStoreName);

Creates a new CertificateStore object.

[Visual Basic] Public Sub New(ByVal CertificateStoreLocation,ByVal String,ByVal KeyUsage)
[C#] public CertificateStore(CertificateStoreLocation,string,KeyUsage);
[C++] public: CertificateStore(CertificateStoreLocation,String*,KeyUsage);
[JScript] public function CertificateStore(CertificateStoreLocation,String,KeyUsage);

Creates a new CertificateStore object, initializing it with a pfx file on disk.

[Visual Basic] Public Sub New(ByVal String)
[C#] public CertificateStore(string);
[C++] public: CertificateStore(String*);
[JScript] public function CertificateStore(String);

Creates a new CertificateStore object, initializing it with a pfx file on disk.

[Visual Basic] Public Sub New(ByVal String,ByVal String)
[C#] public CertificateStore(string,string);
[C++] public: CertificateStore(String*,String*);
[JScript] public function CertificateStore(String,String);

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace


CertificateStore Constructor ()

Creates a new CertificateStore object.

[Visual Basic]
Public Sub New()
[C#]
public CertificateStore();
[C++]
public: CertificateStore();
[JScript]
public function CertificateStore();

Remarks

The default constructor accesses certificates in "My" CurrentUser certificate store.

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access certificates
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access certificates
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace | CertificateStore Constructor Overload List


CertificateStore Constructor (String)

Creates a new CertificateStore object, initializing it with a pfx file on disk.

[Visual Basic]
Public Sub New( _
   ByVal certFileName As String _
)
[C#]
public CertificateStore(
   string certFileName
);
[C++]
public: CertificateStore(
   String* certFileName
);
[JScript]
public function CertificateStore(
   String certFileName
);

Parameters

certFileName
The full filepath of a pfx file on disk.

Remarks

Use this method to load certificates contained in a digital certificate file (pfx file) into the CertificateStore. The desired certificate can then be chosen from the store

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace | CertificateStore Constructor Overload List


CertificateStore Constructor (String, String)

Creates a new CertificateStore object, initializing it with a pfx file on disk.

[Visual Basic]
Public Sub New( _
   ByVal certFileName As String, _
   ByVal password As String _
)
[C#]
public CertificateStore(
   string certFileName,
   string password
);
[C++]
public: CertificateStore(
   String* certFileName,
   String* password
);
[JScript]
public function CertificateStore(
   String certFileName,
   String password
);

Parameters

certFileName
The full filepath of a pfx file on disk.
password
If the pfx file is password protected, specifies the password to use to open the file.

Remarks

Use this method to load certificates contained in a digital certificate file (pfx file) into the CertificateStore. The desired certificate can then be chosen from the store

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace | CertificateStore Constructor Overload List


CertificateStore Constructor (CertificateStoreLocation, CertificateStoreName)

Creates a new CertificateStore object.

[Visual Basic]
Public Sub New( _
   ByVal location As CertificateStoreLocation, _
   ByVal name As CertificateStoreName _
)
[C#]
public CertificateStore(
   CertificateStoreLocation location,
   CertificateStoreName name
);
[C++]
public: CertificateStore(
   CertificateStoreLocation location,
   CertificateStoreName name
);
[JScript]
public function CertificateStore(
   CertificateStoreLocation location,
   CertificateStoreName name
);

Parameters

location
The location of the certificate store.
name
The name of the certificate store.

Remarks

This constructor accesses the certificates located at the parameters specified by location and name.

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace | CertificateStore Constructor Overload List


CertificateStore Constructor (CertificateStoreLocation, String, KeyUsage)

Creates a new CertificateStore object.

[Visual Basic]
Public Sub New( _
   ByVal location As CertificateStoreLocation, _
   ByVal name As String, _
   ByVal filter As KeyUsage _
)
[C#]
public CertificateStore(
   CertificateStoreLocation location,
   string name,
   KeyUsage filter
);
[C++]
public: CertificateStore(
   CertificateStoreLocation location,
   String* name,
   KeyUsage filter
);
[JScript]
public function CertificateStore(
   CertificateStoreLocation location,
   String name,
   KeyUsage filter
);

Parameters

location
The location of the certificate store.
name
The name of the certificate store.
filter
A KeyUsage value specifying what type of certificates to access.

Remarks

This constructor accesses the certificates located at the parameters specified by location and name, and only grabs the certificates which match the filter specified by filter.

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace | CertificateStore Constructor Overload List


CertificateStore Properties

The properties of the CertificateStore class are listed below. For a complete list of CertificateStore class members, see the CertificateStore Members topic.

Public Instance Properties

Capacity (inherited from ArrayList) | Gets or sets the number of elements that the ArrayList can contain.
Count (inherited from ArrayList) | Gets the number of elements actually contained in the ArrayList.
IsFixedSize (inherited from ArrayList) | Gets a value indicating whether the ArrayList has a fixed size.
IsReadOnly (inherited from ArrayList) | Gets a value indicating whether the ArrayList is read-only.
IsSynchronized (inherited from ArrayList) | Gets a value indicating whether access to the ArrayList is synchronized (thread-safe).
Item | Overloaded. Gets or sets the element at the specified index.
Location | The location where the certificate store resides.
Name | The name of this certificate store.
SyncRoot (inherited from ArrayList) | Gets an object that can be used to synchronize access to the ArrayList.

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace


Item Property

CertificateStore.Item Property

Gets or sets the element at the specified index.

[C#] In C#, this property is the indexer for the CertificateStore class.

[Visual Basic]
Public Default Property ReadOnly Item( _
   ByVal index As Integer _
) As Certificate
[C#]
public Certificate this[
   int index
] { get; }
[C++]
public: __property Certificate* get_Item(
   int index
);
[JScript]
returnValue = CertificateStoreObject.Item( index );
-or-
returnValue = CertificateStoreObject( index );

[JScript] In JScript, you can use the default indexed properties defined by a type, but you cannot explicitly define your own. However, specifying the expando attribute on a class automatically provides a default indexed property whose type is Object and whose index type is String.

Parameters

index
The zero-based index of the element to get or set.

Property Value

The element at the specified index.

Remarks

This property provides the ability to access a specific element in the collection by using the following syntax:

myCollection[Index]

Note, intellisense may not work on members of objects referenced by using this indexer. If you would like intellisense to work, get the object referenced by the indexer into it's own variable.

Exceptions

Exception Type | Condition
ArgumentOutOfRangeException | Index is less than zero. -or- Index is equal to or greater than Count.

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access certificates
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access certificates
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStore.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace


Location Property

CertificateStore.Location Property

The location where the certificate store resides.

[Visual Basic]
Public Property ReadOnly Location As CertificateStoreLocation
[C#]
public CertificateStoreLocation Location { get; }
[C++]
public: __property CertificateStoreLocation get_Location();
[JScript]
public function get Location() : CertificateStoreLocation

Property Value

A CertificateStoreLocation value identifying the location of the certificate store.

Remarks

Certificate stores are uniquely identified by two pieces of information found in the registry: location and name.

This property defaults to CertificateStoreLocation.CurrentUser.

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace


Name Property

CertificateStore.Name Property

The name of this certificate store.

[Visual Basic]
Public Property ReadOnly Name As String
[C#]
public string Name { get; }
[C++]
public: __property String* get_Name();
[JScript]
public function get Name() : String

Property Value

A string value identifying the name of the certificate store.

Remarks

Certificate stores are uniquely identified by two pieces of information found in the registry: location and name. Some common names are:

Name | Description
"MY" | Personal certificates.
"CA" | Certifying authority certificates.
"ROOT" | Trusted root certification authorities certificates.
"SPC" | Software publisher certificates.

This property defaults to CertificateStoreLocation.My.

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace


CertificateStore Methods

The methods of the CertificateStore class are listed below. For a complete list of CertificateStore class members, see the CertificateStore Members topic.

Public Instance Methods

Add (inherited from ArrayList) | Adds an object to the end of the ArrayList.
AddRange (inherited from ArrayList) | Adds the elements of an ICollection to the end of the ArrayList.
BinarySearch (inherited from ArrayList) | Overloaded. Searches the entire sorted ArrayList for an element using the specified comparer and returns the zero-based index of the element.
Clear (inherited from ArrayList) | Removes all elements from the ArrayList.
Clone (inherited from ArrayList) | Creates a shallow copy of the ArrayList.
Contains (inherited from ArrayList) | Overloaded. Determines whether an element is in the ArrayList.
Contains | Overloaded. Determines whether an element is in the collection.
CopyTo (inherited from ArrayList) | Overloaded. Copies the entire ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array.
CopyTo | Overloaded. Copies the entire collection to a compatible one-dimensional Array, starting at the specified index of the target array.
Dispose | Overloaded. Releases all resources associated with the object.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetEnumerator (inherited from ArrayList) | Overloaded. Returns an enumerator for the entire ArrayList.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetRange (inherited from ArrayList) | Returns an ArrayList which represents a subset of the elements in the source ArrayList.
GetType (inherited from Object) | Gets the Type of the current instance.
IndexOf (inherited from ArrayList) | Overloaded. Searches for the specified Object and returns the zero-based index of the first occurrence within the entire ArrayList.
IndexOf | Overloaded. Searches for the specified value and returns the zero-based index of the first occurrence within the entire collection.
Insert (inherited from ArrayList) | Overloaded. Inserts an element into the ArrayList at the specified index.
Insert | Overloaded. Inserts an element into the collection at the specified index.
InsertRange (inherited from ArrayList) | Inserts the elements of a collection into the ArrayList at the specified index.
LastIndexOf (inherited from ArrayList) | Overloaded. Searches for the specified Object and returns the zero-based index of the last occurrence within the section of the ArrayList that contains the specified number of elements and ends at the specified index.
Remove (inherited from ArrayList) | Removes the first occurrence of a specific object from the ArrayList.
RemoveAt (inherited from ArrayList) | Removes the element at the specified index of the ArrayList.
RemoveRange (inherited from ArrayList) | Removes a range of elements from the ArrayList.
Reverse (inherited from ArrayList) | Overloaded. Reverses the order of the elements in the specified range.
SetRange (inherited from ArrayList) | Copies the elements of a collection over a range of elements in the ArrayList.
Sort (inherited from ArrayList) | Overloaded. Sorts the elements in a section of ArrayList using the specified comparer.
ToArray (inherited from ArrayList) | Overloaded. Copies the elements of the ArrayList to a new array of the specified type.
ToString (inherited from Object) | Returns a String that represents the current Object.
TrimToSize (inherited from ArrayList) | Sets the capacity to the actual number of elements in the ArrayList.

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace


Contains Method

CertificateStore.Contains Method

Determines whether an element is in the collection.

Overload List

Determines whether an element is in the collection.

[Visual Basic] Public Function Contains(ByVal Certificate) As Boolean
[C#] public bool Contains(Certificate);
[C++] public: bool Contains(Certificate*);
[JScript] public function Contains(Certificate): bool;

Determines whether an element is in the ArrayList.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Function Contains(ByVal Object) _ Implements IList.Contains As Boolean
[C#] public virtual bool Contains(object);
[C++] public: virtual bool Contains(Object*);
[JScript] public virtual function Contains(Object): bool;

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace


Contains Method (Certificate)

CertificateStore.Contains Method (Certificate)

Determines whether an element is in the collection.

[Visual Basic]
Public Function Contains( _
   ByVal value As Certificate _
) As Boolean
[C#]
public bool Contains(
   Certificate value
);
[C++]
public: bool Contains(
   Certificate* value
);
[JScript]
public function Contains(
   Certificate value
): bool;

Parameters

value
The Object to locate in the collection. The element to locate can be a null reference (Nothing in Visual Basic).

Return Value

true if item is found in the collection; otherwise, false.

Remarks

This method performs a linear search; therefore, the average execution time is proportional to Count. That is, this method is an O(n) operation, where n is Count.

This method determines equality by calling Object.Equals.

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace | CertificateStore.Contains Overload List


CopyTo Method

CertificateStore.CopyTo Method

Copies the entire collection to a compatible one-dimensional Array, starting at the specified index of the target array.

Overload List

Copies the entire collection to a compatible one-dimensional Array, starting at the specified index of the target array.

[Visual Basic] Public Sub CopyTo(ByVal CertificateStore,ByVal Integer)
[C#] public void CopyTo(CertificateStore,int);
[C++] public: void CopyTo(CertificateStore*,int);
[JScript] public function CopyTo(CertificateStore,int);

Copies the entire ArrayList to a compatible one-dimensional Array, starting at the beginning of the target array.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Sub CopyTo(ByVal Array)
[C#] public virtual void CopyTo(Array);
[C++] public: virtual void CopyTo(Array*);
[JScript] public virtual function CopyTo(Array);

Copies the entire ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Sub CopyTo(ByVal Array,ByVal Integer) _ Implements ICollection.CopyTo
[C#] public virtual void CopyTo(Array,int);
[C++] public: virtual void CopyTo(Array*,int);
[JScript] public virtual function CopyTo(Array,int);

Copies a range of elements from the ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Sub CopyTo(ByVal Integer,ByVal Array,ByVal Integer,ByVal Integer)
[C#] public virtual void CopyTo(int,Array,int,int);
[C++] public: virtual void CopyTo(int,Array*,int,int);
[JScript] public virtual function CopyTo(int,Array,int,int);

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace


CopyTo Method (CertificateStore, Int32)

CertificateStore.CopyTo Method (CertificateStore, Int32)

Copies the entire collection to a compatible one-dimensional Array, starting at the specified index of the target array.

[Visual Basic]
Public Sub CopyTo( _
   ByVal array As CertificateStore, _
   ByVal index As Integer _
)
[C#]
public void CopyTo(
   CertificateStore array,
   int index
);
[C++]
public: void CopyTo(
   CertificateStore* array,
   int index
);
[JScript]
public function CopyTo(
   CertificateStore array,
   int index
);

Parameters

array
The one-dimensional Array that is the destination of the elements copied from ArrayList. The Array must have zero-based indexing.
index
The zero-based index in array at which copying begins.

Remarks

The specified array must be of a compatible type.

This method uses Array.Copy to copy the elements.

Exceptions

Exception Type | Condition
ArgumentNullException | array is a null reference (Nothing in Visual Basic).
ArgumentException | array is multidimensional.
InvalidCastException | The type of the source ArrayList cannot be cast automatically to the type of the destination array.

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace | CertificateStore.CopyTo Overload List


Dispose Method

CertificateStore.Dispose Method

Releases all resources associated with the object.

Overload List

Releases all resources associated with the object.

[Visual Basic] Public Sub Dispose() _ Implements IDisposable.Dispose
[C#] public void Dispose();
[C++] public: void Dispose();
[JScript] public function Dispose();

Releases all resources associated with the object.

[Visual Basic] Public Sub Dispose(ByVal Boolean)
[C#] public void Dispose(bool);
[C++] public: void Dispose(bool);
[JScript] public function Dispose(bool);

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace


Dispose Method ()

CertificateStore.Dispose Method ()

Releases all resources associated with the object.

[Visual Basic]
Public Sub Dispose() _
    Implements IDisposable.Dispose
[C#]
public void Dispose();
[C++]
public: void Dispose();
[JScript]
public function Dispose();

Implements

IDisposable.Dispose

Remarks

The Object.Dispose method abruptly aborts the connection and releases all resources.

Object.Dispose should ONLY be used to release all resources used by the object, and the object should not be used subsequently. If an abort is desired, then Object.Close or Object.Connection.Close if available should be used to terminate activity and reset the object. The Object cannot be used once Object.Dispose() or Object.Dispose(true) are called.

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace | CertificateStore.Dispose Overload List


Dispose Method (Boolean)

CertificateStore.Dispose Method (Boolean)

Releases all resources associated with the object.

[Visual Basic]
Public Sub Dispose( _
   ByVal disposing As Boolean _
)
[C#]
public void Dispose(
   bool disposing
);
[C++]
public: void Dispose(
   bool disposing
);
[JScript]
public function Dispose(
   bool disposing
);

Remarks

The Object.Dispose method abruptly aborts the connection and releases all resources.

Object.Dispose should ONLY be used to release all resources used by the object, and the object should not be used subsequently. If an abort is desired, then Object.Close or Object.Connection.Close if available should be used to terminate activity and reset the object. The Object cannot be used once Object.Dispose() or Object.Dispose(true) are called.

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace | CertificateStore.Dispose Overload List


IndexOf Method

CertificateStore.IndexOf Method

Searches for the specified value and returns the zero-based index of the first occurrence within the entire collection.

Overload List

Searches for the specified value and returns the zero-based index of the first occurrence within the entire collection.

[Visual Basic] Public Function IndexOf(ByVal Certificate) As Integer
[C#] public int IndexOf(Certificate);
[C++] public: int IndexOf(Certificate*);
[JScript] public function IndexOf(Certificate): int;

Searches for the specified Object and returns the zero-based index of the first occurrence within the entire ArrayList.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Function IndexOf(ByVal Object) _ Implements IList.IndexOf As Integer
[C#] public virtual int IndexOf(object);
[C++] public: virtual int IndexOf(Object*);
[JScript] public virtual function IndexOf(Object): int;

Searches for the specified Object and returns the zero-based index of the first occurrence within the section of the ArrayList that extends from the specified index to the last element.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Function IndexOf(ByVal Object,ByVal Integer) As Integer
[C#] public virtual int IndexOf(object,int);
[C++] public: virtual int IndexOf(Object*,int);
[JScript] public virtual function IndexOf(Object,int): int;

Searches for the specified Object and returns the zero-based index of the first occurrence within the section of the ArrayList that starts at the specified index and contains the specified number of elements.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Function IndexOf(ByVal Object,ByVal Integer,ByVal Integer) As Integer
[C#] public virtual int IndexOf(object,int,int);
[C++] public: virtual int IndexOf(Object*,int,int);
[JScript] public virtual function IndexOf(Object,int,int): int;

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace


IndexOf Method (Certificate)

CertificateStore.IndexOf Method (Certificate)

Searches for the specified value and returns the zero-based index of the first occurrence within the entire collection.

[Visual Basic]
Public Function IndexOf( _
   ByVal value As Certificate _
) As Integer
[C#]
public int IndexOf(
   Certificate value
);
[C++]
public: int IndexOf(
   Certificate* value
);
[JScript]
public function IndexOf(
   Certificate value
): int;

Parameters

value
The Object to locate in the collection.

Return Value

The zero-based index of the first occurrence of value within the entire collection, if found; otherwise, -1.

Remarks

The collection is searched forward starting at the first element and ending at the last element.

This method performs a linear search. On average, this is an O(n/2) operation, where n is Count. The longest search is an O(n) operation.

This method determines equality by calling Object.Equals.

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace | CertificateStore.IndexOf Overload List


Insert Method

CertificateStore.Insert Method

Inserts an element into the collection at the specified index.

Overload List

Inserts an element into the collection at the specified index.

[Visual Basic] Public Sub Insert(ByVal Integer,ByVal Certificate)
[C#] public void Insert(int,Certificate);
[C++] public: void Insert(int,Certificate*);
[JScript] public function Insert(int,Certificate);

Inserts an element into the ArrayList at the specified index.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Sub Insert(ByVal Integer,ByVal Object) _ Implements IList.Insert
[C#] public virtual void Insert(int,object);
[C++] public: virtual void Insert(int,Object*);
[JScript] public virtual function Insert(int,Object);

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace


Insert Method (Int32, Certificate)

CertificateStore.Insert Method (Int32, Certificate)

Inserts an element into the collection at the specified index.

[Visual Basic]
Public Sub Insert( _
   ByVal index As Integer, _
   ByVal value As Certificate _
)
[C#]
public void Insert(
   int index,
   Certificate value
);
[C++]
public: void Insert(
   int index,
   Certificate* value
);
[JScript]
public function Insert(
   int index,
   Certificate value
);

Parameters

index
The zero-based index at which value should be inserted.
value
The Object to insert.

Remarks

If Count already equals Capacity, the capacity of the list is doubled by automatically reallocating the internal array before the new element is inserted.

If index is equal to Count, value is added to the end of ArrayList.

In collections of contiguous elements, such as lists, the elements that follow the insertion point move down to accommodate the new element. If the collection is indexed, the indexes of the elements that are moved are also updated. This behavior does not apply to collections where elements are conceptually grouped into buckets, such as a hashtable.

Exceptions

Exception Type | Condition
ArgumentOutOfRangeException | index is less than zero. -or- index is greater than Count.
NotSupportedException | The ArrayList is read-only. -or- The ArrayList has a fixed size.

See Also

CertificateStore Class | Dart.PowerTCP.Ftp Namespace | CertificateStore.Insert Overload List


CertificateStoreLocation Enumeration

Enumerates the possible locations for certificates

[Visual Basic]
Public Enum CertificateStoreLocation
[C#]
public enum CertificateStoreLocation
[C++]
public __value enum CertificateStoreLocation
[JScript]
public enum CertificateStoreLocation

Remarks

The system store is the certificate store located in the HKEY_CURRENT_USER registry key. The machine store is the certificate store located in the HKEY_LOCAL_MACHINE registry key. Applications installed as a service should store their certificates in the machine store since there is no current user when running as a service.

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access the "MY" certificate store
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStoreName.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access the "MY" certificate store
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStoreName.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

Members

Member Name | Description
CurrentUser | The current user’s certificates.
LocalMachine | The local machine’s certificates.
CurrentService | The current service’s certificates.
Services | Certificates for services
Users | Certificates for users
CurrentUserGroupPolicy | Certificates for the current user’s groups
LocalMachineGroupPolicy | Certificates for the local machine’s groups
LocalMachineEnterprise | Certificates for the enterprise

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


CertificateStoreName Enumeration

Enumerates the names for commonly used certificate stores.

[Visual Basic]
Public Enum CertificateStoreName
[C#]
public enum CertificateStoreName
[C++]
public __value enum CertificateStoreName
[JScript]
public enum CertificateStoreName

Remarks

A certificate store is a location on the system (memory, disk, registry, etc.) where certificates are stored for use. Although there are many certificate stores, there are two commonly used system stores.

  • MY – personal certificates go here
  • ROOT – certificates for Trusted Root Certificate Authorities

Example

The following example demonstrates accessing a certificate and displaying info about it.

[Visual Basic]
Private Sub DisplayCertificateInfo(ByVal certNum as Integer)

   ' Create a new CertificateStore to access the "MY" certificate store
   Dim store as new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStoreName.My)

   Try
      ' Get the requested certificate
      Dim cert as Certificate = store(certNum)

      ' Display info about the certificate
      Dim msg as String
      msg+= "The following information about the certificate is available." + vbCrLF + vbCrLf
      msg+= "Name: " + cert.Name + vbCrLf
      msg+= "Description: " + cert.Description + vbCrLf
      msg+= "Expires: " + cert.ExpirationDate + vbCrLf
      msg+= "Issued: " + cert.IssueDate + vbCrLf
      msg+= "Issues to: " + cert.IssuedTo + vbCrLf
      msg+= "Serial number: " + cert.SerialNumber + vbCrLf
      msg+= "Version: " + cert.Versio
      MessageBox.Show(msg)
   Catch ex as Exception
      MessageBox.Show("Error. No certificate found at index " + certNum)
   End Try
End Sub

[C#]
private void DisplayCertificateInfo(int certNum)
{
   // Create a new CertificateStore to access the "MY" certificate store
   CertificateStore store = new CertificateStore(CertificateStoreLocation.LocalMachine, CertificateStoreName.My);

   try
   {
      // Get the requested certificate
      Certificate cert = store[certNum];

      // Display info about the certificate
      string msg = "";
      msg+= "The following information about the certificate is available.\r\n\r\n";
      msg+= "Name: " + cert.Name + "\r\n";
      msg+= "Description: " + cert.Description + "\r\n";
      msg+= "Expires: " + cert.ExpirationDate + "\r\n";
      msg+= "Issued: " + cert.IssueDate + "\r\n";
      msg+= "Issues to: " + cert.IssuedTo + "\r\n";
      msg+= "Serial number: " + cert.SerialNumber + "\r\n";
      msg+= "Version: " + cert.Version;
      MessageBox.Show(msg);
   }
   catch(Exception ex)
   {
      MessageBox.Show("Error. No certificate found at index " + certNum);
   }
}

Members

Member Name | Description
My | The normal name for user certificate stores.
CA | The name of Certificate Authority certificate stores.
Root | The normal name for root certificate stores.
Trust | The name for trusted certificates stores
Request | The name for pending certificate request stores.
Acrs | The name for Automatic Certificate Request Service certificate stores.
Spc | The name for software publisher's certificate stores.
NtAuth | The name for NT authentication certificate stores.
Efs | The name for Windows encrypting file systems certificate stores.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


Compression Enumeration

Enumerates the compression options for file transfers and listings.

[Visual Basic]
Public Enum Compression
[C#]
public enum Compression
[C++]
public __value enum Compression
[JScript]
public enum Compression

Remarks

Some servers support 'MODE Z' zlib compression. This enumeration is used to indicate how compression should be used.

Members

Member Name | Description
None | No compression/decompression is used. 'MODE S' is the transfer mode used and no compression/decompression takes place.
Archive | Local compression/decompression is used, but the server is not instructed to compress/decompress. 'MODE S' is the transfer mode used and files are stored in a compressed state.
Full | Local and server compression/decompression is used. 'MODE Z' is the transfer mode used and files on the server are not compressed.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


ConnectEventHandler Delegate

Represents the method (event handler) that is raised when the BeginConnect operation completes.

[Visual Basic]
Public Delegate Function Sub  ConnectEventHandler( _
   ByVal sender As Object, _
   ByVal e As ExceptionEventArgs _
)
[C#]
public delegate void ConnectEventHandler(
   object sender,
   ExceptionEventArgs e
)
[C++]
public __gc __delegate void ConnectEventHandler(
   Object* sender,
   ExceptionEventArgs* e
)

[JScript] In JScript, you can use the delegates defined by a type, but you cannot define your own.

Parameters

sender
The source of the event.
e
A ExceptionEventArgs object that contains the event data.

Remarks

As Microsoft describes in their MSDN documentation, the event model in the .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed:

  • A class that holds the event data. This class must derive from the base class EventArgs.
  • A delegate that points to a method that provides the response to the event.
When using the BeginConnect method, the class that holds the event data is the ExceptionEventArgs class. A method must be created with the same signature as the delegate. In this example that would mean a method would have to be defined to accept two arguments (an object and a ExceptionEventArgs) and return void. Once this has been done, the delegate must be "connected" to the handling event. This is done by adding an instance of the delegate to the event.

For more information about event handler delegates, see the Using Events In PowerTCP topic.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


EnhancedStream Class

Adds new methods on top of the Stream interface for type conversion, stream copying, and saving.

For a list of all members of this type, see EnhancedStream Members.

System.Object
System.MarshalByRefObject
System.IO.Stream
Dart.PowerTCP.Ftp.EnhancedStream
Dart.PowerTCP.Ftp.PipeStream
Dart.PowerTCP.Ftp.TcpStream

[Visual Basic]
MustInherit Public Class EnhancedStream
    Inherits Stream
[C#]
public abstract class EnhancedStream : Stream
[C++]
public __gc __abstract class EnhancedStream : public Stream
[JScript]
public  class EnhancedStream extends Stream

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

Inherit from this abstract class to create a Stream class with enhanced methods. For example, Save allows you to save Stream data directly to a file. ToString returns a string representation of the data contained within the Stream.

All PowerTCP Stream classes (such as SegmentedStream, PipeStream) inherit from this class to provide the enhanced capabilities described above to these classes.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

EnhancedStream Members | Dart.PowerTCP.Ftp Namespace


EnhancedStream Members

EnhancedStream overview

Public Instance Properties

CanRead | Overridden. Gets a value indicating whether the current stream supports reading.
CanSeek | Overridden. Gets a value indicating whether the current stream supports seeking.
CanWrite | Overridden. Gets a value indicating whether the current stream supports writing.
Charset | Gets and sets the character set used for string/byte array conversions.
Encoding | Gets or sets the type of encoding to use.
Length | Overridden. The length of data available on the stream. This method always throws a NotSupportedException.
Position | Overridden. Gets or sets the position in the stream. This method always throws a NotSupportedException.

Public Instance Methods

BeginRead (inherited from Stream) | Begins an asynchronous read operation.
BeginWrite (inherited from Stream) | Begins an asynchronous write operation.
Close (inherited from Stream) | Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose | Releases all resources associated with the object.
EndRead (inherited from Stream) | Waits for the pending asynchronous read to complete.
EndWrite (inherited from Stream) | Ends an asynchronous write operation.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
Flush | Overridden. Default implementation is no-op. May be overridden by derived classes
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
Read (inherited from Stream) | Overloaded. When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
Read | Overloaded. Reads at least one byte of data from the Stream and copies it into the provided buffer.
ReadByte (inherited from Stream) | Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
Save | Overloaded. Saves the data in the stream to the file specified by fileName.
Seek | Overridden. Sets the position within the current Stream to the specified value. Always throws a NotSupportedException.
SetLength | Overridden. Sets the length of the current Stream to the specified value. Always throws a NotSupportedException.
ToArray | Returns the byte array representation of the Stream data.
ToString | Overridden. Returns the string representation of the Stream data.
Write (inherited from Stream) | Overloaded. When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
Write | Overloaded. Writes a sequence of bytes to the Stream and returns when the operation is complete.
WriteByte (inherited from Stream) | Writes a byte to the current position in the stream and advances the position within the stream by one byte.
WriteTo | Overloaded. Writes all of the data contained in this Stream to a destination Stream.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


EnhancedStream Properties

The properties of the EnhancedStream class are listed below. For a complete list of EnhancedStream class members, see the EnhancedStream Members topic.

Public Instance Properties

CanRead | Overridden. Gets a value indicating whether the current stream supports reading.
CanSeek | Overridden. Gets a value indicating whether the current stream supports seeking.
CanWrite | Overridden. Gets a value indicating whether the current stream supports writing.
Charset | Gets and sets the character set used for string/byte array conversions.
Encoding | Gets or sets the type of encoding to use.
Length | Overridden. The length of data available on the stream. This method always throws a NotSupportedException.
Position | Overridden. Gets or sets the position in the stream. This method always throws a NotSupportedException.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


CanRead Property

EnhancedStream.CanRead Property

Gets a value indicating whether the current stream supports reading.

[Visual Basic]
Overrides Public Property ReadOnly CanRead As Boolean
[C#]
public override bool CanRead { get; }
[C++]
public: __property bool get_CanRead();
[JScript]
public override function get CanRead() : bool

Remarks

This property returns true unless overridden in a derived class.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


CanSeek Property

EnhancedStream.CanSeek Property

Gets a value indicating whether the current stream supports seeking.

[Visual Basic]
Overrides Public Property ReadOnly CanSeek As Boolean
[C#]
public override bool CanSeek { get; }
[C++]
public: __property bool get_CanSeek();
[JScript]
public override function get CanSeek() : bool

Remarks

This property always returns false.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


CanWrite Property

EnhancedStream.CanWrite Property

Gets a value indicating whether the current stream supports writing.

[Visual Basic]
Overrides Public Property ReadOnly CanWrite As Boolean
[C#]
public override bool CanWrite { get; }
[C++]
public: __property bool get_CanWrite();
[JScript]
public override function get CanWrite() : bool

Remarks

This property returns true unless overridden in a derived class.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


Charset Property

EnhancedStream.Charset Property

Gets and sets the character set used for string/byte array conversions.

[Visual Basic]
Public Property Charset As String
[C#]
public string Charset { get; set; }
[C++]
public: __property String* get_Charset();
public: __property void set_Charset(String* );
[JScript]
public function get Charset() : String
public function set Charset(String);

Property Value

A string representing the character set used.

Remarks

This value defaults to the language used on the runtime machine (accessible through System.Text.Encoding.Default.BodyName). Set this property to the desired character set string to override this behavior. An example charset for Kanji is "ISO-2022-JP", while Latin-1 is "ISO-8859-1". "UTF-8" will always encode unicode strings, but not all mail readers support decoding this character set.

When communicating with clients from other countries set this property based on the standard string defined for the language intended. This enables the International client to be able to properly decode the message.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


Encoding Property

EnhancedStream.Encoding Property

Gets or sets the type of encoding to use.

[Visual Basic]
Public Property Encoding As Encoding
[C#]
public Encoding Encoding { get; set; }
[C++]
public: __property Encoding* get_Encoding();
public: __property void set_Encoding(Encoding* );
[JScript]
public function get Encoding() : Encoding
public function set Encoding(Encoding);

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


Length Property

EnhancedStream.Length Property

The length of data available on the stream. This method always throws a NotSupportedException.

[Visual Basic]
Overrides Public Property ReadOnly Length As Long
[C#]
public override long Length { get; }
[C++]
public: __property __int64 get_Length();
[JScript]
public override function get Length() : long

Exceptions

Exception Type | Condition
NotSupportedException | Always throws this exception.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


Position Property

EnhancedStream.Position Property

Gets or sets the position in the stream. This method always throws a NotSupportedException.

[Visual Basic]
Overrides Public Property Position As Long
[C#]
public override long Position { get; set; }
[C++]
public: __property __int64 get_Position();
public: __property void set_Position(__int64 );
[JScript]
public override function get Position() : long
public override function set Position(long);

Exceptions

Exception Type | Condition
NotSupportedException | Always throws this exception.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


EnhancedStream Methods

The methods of the EnhancedStream class are listed below. For a complete list of EnhancedStream class members, see the EnhancedStream Members topic.

Public Instance Methods

BeginRead (inherited from Stream) | Begins an asynchronous read operation.
BeginWrite (inherited from Stream) | Begins an asynchronous write operation.
Close (inherited from Stream) | Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose | Releases all resources associated with the object.
EndRead (inherited from Stream) | Waits for the pending asynchronous read to complete.
EndWrite (inherited from Stream) | Ends an asynchronous write operation.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
Flush | Overridden. Default implementation is no-op. May be overridden by derived classes
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
Read (inherited from Stream) | Overloaded. When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
Read | Overloaded. Reads at least one byte of data from the Stream and copies it into the provided buffer.
ReadByte (inherited from Stream) | Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
Save | Overloaded. Saves the data in the stream to the file specified by fileName.
Seek | Overridden. Sets the position within the current Stream to the specified value. Always throws a NotSupportedException.
SetLength | Overridden. Sets the length of the current Stream to the specified value. Always throws a NotSupportedException.
ToArray | Returns the byte array representation of the Stream data.
ToString | Overridden. Returns the string representation of the Stream data.
Write (inherited from Stream) | Overloaded. When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
Write | Overloaded. Writes a sequence of bytes to the Stream and returns when the operation is complete.
WriteByte (inherited from Stream) | Writes a byte to the current position in the stream and advances the position within the stream by one byte.
WriteTo | Overloaded. Writes all of the data contained in this Stream to a destination Stream.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


Dispose Method

EnhancedStream.Dispose Method

Releases all resources associated with the object.

[Visual Basic]
Public Sub Dispose() _
    Implements IDisposable.Dispose
[C#]
public void Dispose();
[C++]
public: void Dispose();
[JScript]
public function Dispose();

Implements

IDisposable.Dispose

Remarks

The Object.Dispose method abruptly aborts the connection and releases all resources.

Object.Dispose should ONLY be used to release all resources used by the object, and the object should not be used subsequently. If an abort is desired, then Object.Close or Object.Connection.Close if available should be used to terminate activity and reset the object. The Object cannot be used once Object.Dispose() or Object.Dispose(true) are called.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


Flush Method

EnhancedStream.Flush Method

Default implementation is no-op. May be overridden by derived classes

[Visual Basic]
Overrides Public Sub Flush()
[C#]
public override void Flush();
[C++]
public: void Flush();
[JScript]
public override function Flush();

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


Read Method

EnhancedStream.Read Method

Reads at least one byte of data from the Stream and copies it into the provided buffer.

Overload List

Reads at least one byte of data from the Stream and copies it into the provided buffer.

[Visual Basic] Public Function Read(ByVal Byte()) As Integer
[C#] public int Read(byte[]);
[C++] public: int Read(char __gc[]);
[JScript] public function Read(Byte[]): int;

When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
Inherited from Stream.

[Visual Basic] MustOverride OverloadsPublic Function Read(ByVal Byte(),ByVal Integer,ByVal Integer) As Integer
[C#] public abstract int Read(byte[],int,int);
[C++] public: abstract int Read(char __gc[],int,int);
[JScript] public abstract function Read(Byte[],int,int): int;

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


Read Method (Byte[])

EnhancedStream.Read Method (Byte[])

Reads at least one byte of data from the Stream and copies it into the provided buffer.

[Visual Basic]
Public Function Read( _
   ByVal buffer As Byte() _
) As Integer
[C#]
public int Read(
   byte[] buffer
);
[C++]
public: int Read(
   char buffer __gc[]
);
[JScript]
public function Read(
   Byte[] buffer
): int;

Parameters

buffer
The storage location for the received data.

Return Value

The total number of bytes read into the buffer.

Remarks

This is a convenience method for all derived classes, calling Read(buffer,0, buffer.Length) on the stream.

Exceptions

Exception Type | Condition
IOException | Thrown when the Stream is not readable.
ArgumentNullException | Thrown when the buffer or callback is null.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace | EnhancedStream.Read Overload List


Save Method

EnhancedStream.Save Method

Saves the data in the stream to the file specified by fileName.

Overload List

Saves the data in the stream to the file specified by fileName.

[Visual Basic] Overridable OverloadsPublic Function Save(ByVal String) As String
[C#] public virtual string Save(string);
[C++] public: virtual String* Save(String*);
[JScript] public virtual function Save(String): String;

Saves the data in the stream to the file specified by fileName.

[Visual Basic] Overridable OverloadsPublic Function Save(ByVal String,ByVal Boolean) As String
[C#] public virtual string Save(string,bool);
[C++] public: virtual String* Save(String*,bool);
[JScript] public virtual function Save(String,bool): String;

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


Save Method (String)

EnhancedStream.Save Method (String)

Saves the data in the stream to the file specified by fileName.

[Visual Basic]
Overridable  OverloadsPublic Function Save( _
   ByVal fileName As String _
) As String
[C#]
public virtual string Save(
   string fileName
);
[C++]
public: virtual String* Save(
   String* fileName
);
[JScript]
public virtual function Save(
   String fileName
): String;

Parameters

fileName
The desired name of the destination file.

Return Value

A string containing the name of the file the data was written to.

Remarks

This method saves all of the data in the stream to the file specified by fileName. This method will always create a new file, creating a unique filename if the file already exists.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace | EnhancedStream.Save Overload List


Save Method (String, Boolean)

EnhancedStream.Save Method (String, Boolean)

Saves the data in the stream to the file specified by fileName.

[Visual Basic]
Overridable  OverloadsPublic Function Save( _
   ByVal fileName As String, _
   ByVal overwrite As Boolean _
) As String
[C#]
public virtual string Save(
   string fileName,
   bool overwrite
);
[C++]
public: virtual String* Save(
   String* fileName,
   bool overwrite
);
[JScript]
public virtual function Save(
   String fileName,
   bool overwrite
): String;

Parameters

fileName
The desired name of the destination file.
overwrite
Controls whether or not to overwrite existing files.

Return Value

A string containing the name of the file the data was written to.

Remarks

This method saves all of the data in the stream to the file specified by fileName. If overwrite is true, this method will create a new file if the specified file does not exist and will overwrite the specified file if it does exist. If overwrite is false, this method will always create a new file, creating a unique filename if the file already exists.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace | EnhancedStream.Save Overload List


Seek Method

EnhancedStream.Seek Method

Sets the position within the current Stream to the specified value. Always throws a NotSupportedException.

[Visual Basic]
Overrides Public Function Seek( _
   ByVal offset As Long, _
   ByVal origin As SeekOrigin _
) As Long
[C#]
public override long Seek(
   long offset,
   SeekOrigin origin
);
[C++]
public: __int64 Seek(
   __int64 offset,
   SeekOrigin origin
);
[JScript]
public override function Seek(
   long offset,
   SeekOrigin origin
): long;

Parameters

offset
The new position within the stream
origin
A value of type SeekOrigin, which acts as the seek reference point.

Remarks

This method is not supported, and always throws a NotSupportedException.

Exceptions

Exception Type | Condition
NotSupportedException | Always thrown by this method.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


SetLength Method

EnhancedStream.SetLength Method

Sets the length of the current Stream to the specified value. Always throws a NotSupportedException.

[Visual Basic]
Overrides Public Sub SetLength( _
   ByVal value As Long _
)
[C#]
public override void SetLength(
   long value
);
[C++]
public: void SetLength(
   __int64 value
);
[JScript]
public override function SetLength(
   long value
);

Parameters

value
The value at which to set the length.

Remarks

This method is not supported, and always throws a NotSupportedException.

Exceptions

Exception Type | Condition
NotSupportedException | Always thrown by this method.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


ToArray Method

EnhancedStream.ToArray Method

Returns the byte array representation of the Stream data.

[Visual Basic]
Overridable Public Function ToArray() As Byte()
[C#]
public virtual byte[] ToArray();
[C++]
public: virtual char ToArray()  __gc[];
[JScript]
public virtual function ToArray(): Byte[];

Return Value

The byte array representation of the Stream data.

Remarks

Use this method to easily return the data in the stream as a byte array. Position should be reset after calling this method.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


ToString Method

EnhancedStream.ToString Method

Returns the string representation of the Stream data.

[Visual Basic]
Overrides Public Function ToString() As String
[C#]
public override string ToString();
[C++]
public: String* ToString();
[JScript]
public override function ToString(): String;

Return Value

The string representation of the Stream data.

Remarks

This method returns the string representation the data contained in the stream, based on the Charset.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


Write Method

EnhancedStream.Write Method

Writes a sequence of bytes to the Stream and returns when the operation is complete.

Overload List

Writes a sequence of bytes to the Stream and returns when the operation is complete.

[Visual Basic] Public Sub Write(ByVal Byte())
[C#] public void Write(byte[]);
[C++] public: void Write(char __gc[]);
[JScript] public function Write(Byte[]);

When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
Inherited from Stream.

[Visual Basic] MustOverride OverloadsPublic Sub Write(ByVal Byte(),ByVal Integer,ByVal Integer)
[C#] public abstract void Write(byte[],int,int);
[C++] public: abstract void Write(char __gc[],int,int);
[JScript] public abstract function Write(Byte[],int,int);

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


Write Method (Byte[])

EnhancedStream.Write Method (Byte[])

Writes a sequence of bytes to the Stream and returns when the operation is complete.

[Visual Basic]
Public Sub Write( _
   ByVal buffer As Byte() _
)
[C#]
public void Write(
   byte[] buffer
);
[C++]
public: void Write(
   char buffer __gc[]
);
[JScript]
public function Write(
   Byte[] buffer
);

Parameters

buffer
The source location of the data to write.

Remarks

This method is a convenience overload for all derived classes by writing the entire buffer to the Stream. This method calls Write(buffer, 0, buffer.length).

Exceptions

Exception Type | Condition
IOException | Thrown when the Stream is not writable.
ArgumentNullException | Thrown when the buffer is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when count is less than or equal to zero.
ArgumentException | Thrown when the (offset + count) > buffer.Length.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace | EnhancedStream.Write Overload List


WriteTo Method

EnhancedStream.WriteTo Method

Writes all of the data contained in this Stream to a destination Stream.

Overload List

Writes all of the data contained in this Stream to a destination Stream.

[Visual Basic] Public Sub WriteTo(ByVal Stream)
[C#] public void WriteTo(Stream);
[C++] public: void WriteTo(Stream*);
[JScript] public function WriteTo(Stream);

Writes all of the data contained in this Stream to a destination Stream.

[Visual Basic] Public Sub WriteTo(ByVal Stream,ByVal Boolean)
[C#] public void WriteTo(Stream,bool);
[C++] public: void WriteTo(Stream*,bool);
[JScript] public function WriteTo(Stream,bool);

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace


WriteTo Method (Stream)

EnhancedStream.WriteTo Method (Stream)

Writes all of the data contained in this Stream to a destination Stream.

[Visual Basic]
Public Sub WriteTo( _
   ByVal destination As Stream _
)
[C#]
public void WriteTo(
   Stream destination
);
[C++]
public: void WriteTo(
   Stream* destination
);
[JScript]
public function WriteTo(
   Stream destination
);

Parameters

destination
The destination stream.

Remarks

This method essentially "copies" one stream to another by setting the destination Stream position to zero, writing all of the data in the source Stream to the destination, resetting the source Stream back to its original position, and resetting the destination to a position of zero.

Exceptions

Exception Type | Condition
NullReferenceException | destination is null.
IOException | Stream is not readable or writeable.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace | EnhancedStream.WriteTo Overload List


WriteTo Method (Stream, Boolean)

EnhancedStream.WriteTo Method (Stream, Boolean)

Writes all of the data contained in this Stream to a destination Stream.

[Visual Basic]
Public Sub WriteTo( _
   ByVal destination As Stream, _
   ByVal resetPosition As Boolean _
)
[C#]
public void WriteTo(
   Stream destination,
   bool resetPosition
);
[C++]
public: void WriteTo(
   Stream* destination,
   bool resetPosition
);
[JScript]
public function WriteTo(
   Stream destination,
   bool resetPosition
);

Parameters

destination
The destination stream.
resetPosition
Controls whether or not the positions of the source and destination streams are reset during the "copy" process.

Remarks

If resetPositions is true, this method essentially "copies" one stream to another by setting the destination Stream position to zero, writing all of the data in the source Stream to the destination, resetting the source Stream back to its original position, and resetting the destination to a position of zero.

If resetPositions is false, it copies from the current location of the source Stream to the current location of destination, and positions are not set.

Exceptions

Exception Type | Condition
NullReferenceException | destination is null.
IOException | Stream is not readable or writeable.

See Also

EnhancedStream Class | Dart.PowerTCP.Ftp Namespace | EnhancedStream.WriteTo Overload List


EntryType Enumeration

Enumerates whether the entry indicates a File, Directory, or is Unknown (if Format is Unknown).

[Visual Basic]
Public Enum EntryType
[C#]
public enum EntryType
[C++]
public __value enum EntryType
[JScript]
public enum EntryType

Remarks

This enumeration is used by the Type property in the ListEntry class. It is useful in detecting whether a list entry is a file or a directory. For example, perhaps you are retrieving a listing and wish to populate a ListBox, displaying a folder icon by the entry if the ListEntry represents a Directory and a file icon by the entry if the ListEntry represents a file. You can simply iterate through the Listing collection, check this property, and set the proper icon.

Example

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Retrieve file list. Listing details will be contained in the Listing Object
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Begin setting up the ListView diplay
' Show gridlines.
ListView1.GridLines = True

' Set View to Details
ListView1.View = View.Details

' Add column headings for file name, size, and date.
ListView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left)

' Iterate through the listing, adding a row to the ListBox for each
Dim le As Dart.PowerTCP.Ftp.ListEntry
For Each le In list

   ' Display files only
   If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then
      Dim cols() As String = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp}
      ListView1.Items.Add(New ListViewItem(cols))
   End If
Next

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Retrieve file list. Listing details will be contained in the Listing Object
Dart.PowerTCP.Ftp.Listing list = ftp1.List("*", true);

// Begin setting up the ListView diplay

// Show gridlines.
listView1.GridLines = true;

// Set View to Details
listView1.View = View.Details;

// Add column headings for file name, size, and date.
listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

// Iterate through the listing, adding a row to the ListBox for each
foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
{
    // Display files only
    if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
    {
        string[] cols = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp};
        listView1.Items.Add(new ListViewItem(cols));
    }
}

// Close the connection
ftp1.Close();

Members

Member Name | Description
File | Indicates the Name contains a filename.
Directory | Indicates the Name contains a directory name.
Link | Indicates the ListEntry contains a link.
Unknown | Indicates the ListEntry could not be parsed.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


EventHandlerEx Delegate

Replaces System.EventHandler when the SynchronizingObject property is used.

[Visual Basic]
Public Delegate Function Sub  EventHandlerEx( _
   ByVal sender As Object, _
   ByVal e As EventArgs _
)
[C#]
public delegate void EventHandlerEx(
   object sender,
   EventArgs e
)
[C++]
public __gc __delegate void EventHandlerEx(
   Object* sender,
   EventArgs* e
)

[JScript] In JScript, you can use the delegates defined by a type, but you cannot define your own.

Parameters

sender
The source of the event.
e
An EventArgs object that contains the event data.

Remarks

When the SynchronizingObject is used, the ConnectedChanged event handler reports the SynchronizingObject as "sender". The EventHandlerEx is used to force the SynchronizingObject to correctly report the appropriate Tcp object as "sender".

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


ExceptionEventArgs Class

Provides data for asynchronous event handlers.

For a list of all members of this type, see ExceptionEventArgs Members.

System.Object
System.EventArgs
Dart.PowerTCP.Ftp.ExceptionEventArgs

[Visual Basic]
Public Class ExceptionEventArgs
    Inherits EventArgs
[C#]
public class ExceptionEventArgs : EventArgs
[C++]
public __gc class ExceptionEventArgs : public EventArgs
[JScript]
public class ExceptionEventArgs extends EventArgs

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

A ExceptionEventArgs object is passed into asynchronous event handlers after an asynchronous operation has completed. If an exception occurred during the asynchronous operation, it is returned in Exception.

For more information on implementing and handling events using PowerTCP.NET, see the topic, "Events in PowerTCP".

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

ExceptionEventArgs Members | Dart.PowerTCP.Ftp Namespace


ExceptionEventArgs Members

ExceptionEventArgs overview

Public Instance Constructors

ExceptionEventArgs Constructor Initialize default instance of the ExceptionEventArgs class.

Public Instance Properties

Exception | Gets any exception which occurred during the asynchronous operation.
State | Gets the object that was included as part of the associated method call.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

ExceptionEventArgs Class | Dart.PowerTCP.Ftp Namespace


ExceptionEventArgs Constructor

Initialize default instance of the ExceptionEventArgs class.

[Visual Basic]
Public Sub New( _
   ByVal exception As Exception, _
   ByVal state As Object _
)
[C#]
public ExceptionEventArgs(
   Exception exception,
   object state
);
[C++]
public: ExceptionEventArgs(
   Exception* exception,
   Object* state
);
[JScript]
public function ExceptionEventArgs(
   Exception exception,
   Object state
);

Parameters

exception
state

See Also

ExceptionEventArgs Class | Dart.PowerTCP.Ftp Namespace


ExceptionEventArgs Properties

The properties of the ExceptionEventArgs class are listed below. For a complete list of ExceptionEventArgs class members, see the ExceptionEventArgs Members topic.

Public Instance Properties

Exception | Gets any exception which occurred during the asynchronous operation.
State | Gets the object that was included as part of the associated method call.

See Also

ExceptionEventArgs Class | Dart.PowerTCP.Ftp Namespace


Exception Property

ExceptionEventArgs.Exception Property

Gets any exception which occurred during the asynchronous operation.

[Visual Basic]
Public Property ReadOnly Exception As Exception
[C#]
public Exception Exception { get; }
[C++]
public: __property Exception* get_Exception();
[JScript]
public function get Exception() : Exception

Property Value

If any exception occurred during the asynchronous operation, this property will contain an Exception object describing the exception.

Remarks

Check this property to tell if an exception occurred during the asynchronous operation. If this property is null, no exception occurred.

The exception property is useful for checking exceptions and handling them appropriately. For example, if a bad command was sent to the server, a ProtocolException may be thrown. You could check this property to see if it was of type ProtocolException, than handle appropriately.

See Also

ExceptionEventArgs Class | Dart.PowerTCP.Ftp Namespace


State Property

ExceptionEventArgs.State Property

Gets the object that was included as part of the associated method call.

[Visual Basic]
Public Property ReadOnly State As Object
[C#]
public object State { get; }
[C++]
public: __property Object* get_State();
[JScript]
public function get State() : Object

Property Value

An object containing data passed into the calling asynchronous method.

Remarks

The EndEventArgs.State property can be used in the calling asynchronous method to make data accessible to the handling event.

This property is useful for making data accessible to the handling event. Since asynchronous methods are "disconnected" (meaning that when one is called, it executes on it's own and returns in the event handler) data that you were using in the code that called the asynchronous method may not be available in the event handler. Simply pass this data in as state when calling the asynchronous method (usually a BeginXXX method) and it is available in the event handler. If you do not wish to make an object accessible in the EndXXX event, simple pass in null as state.

See Also

ExceptionEventArgs Class | Dart.PowerTCP.Ftp Namespace


FileEventArgs Class

This class is passed into the EndGet and EndPut events and provides data for these events.

For a list of all members of this type, see FileEventArgs Members.

System.Object
System.EventArgs
Dart.PowerTCP.Ftp.FileEventArgs

[Visual Basic]
Public Class FileEventArgs
    Inherits EventArgs
[C#]
public class FileEventArgs : EventArgs
[C++]
public __gc class FileEventArgs : public EventArgs
[JScript]
public class FileEventArgs extends EventArgs

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

A FileEventArgs object is passed into the EndGet and EndPut events after asynchronous file transfer has taken place, containing data about the transfer. This data will vary depending on what type of file transfer operation has taken place. For example, if BeginPut was used to store multiple files (MPUT), the Files array will be filled with data about the transfer for each file transferred. The Stream property will be null however, as this operation did not involve a stream. Another example would be in the case of storing a stream from memory as a file on the server. In this instance FileEventArgs.File.RemoteFileName would contain the filename of the file created on the server. FileEventArgs.File.LocalFileName would be null, however, as the "file" only existed in memory on the local machine.

If any error occurred during the asynchronous method call, it would be returned in the handling event. To trap the error, check the Exception property.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

For more information on asynchronous file transfer, see either of the topics Storing Files Asynchronously Overview (Advanced Users) or Retrieving Files Asynchronously Overview (Advanced Users).

Example

The following example demonstrates how to asynchronously retrieve a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToGet As String = "test.txt"

' Call BeginGet, this will begin an asynchronous Get. Upon completion the EndGet Event will be fired.
Ftp1.BeginGet(FileToGet, "RetrievedFile.txt", Nothing)

' Display message, because BeginGet is asynchronous, this will be immediately executed.
Debug.WriteLine("Retrieving " + FileToGet)

' When the BeginGet operation has completed, the EndGet Event will fire.

Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

    ' If an error occurred, it would be returned in the event. Be sure to check for it.
    If e.Exception Is Nothing Then
       Debug.WriteLine("Get completed for file " + file.RemoteFileName)
    Else
       Debug.WriteLine("Error: " + e.Exception.ToString())
    End If

   ' Close the connection
   Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToGet = "test.txt";

// Call BeginGet, this will begin an asynchronous Get. Upon completion the EndGet Event will be fired.
ftp1.BeginGet(FileToGet, Application.StartupPath + "\\" + new System.IO.FileInfo(FileToGet).Name, null);

// Display message, because BeginGet is asynchronous, this will be immediately executed.
Debug.WriteLine("Retrieving " + FileToGet);

// When the BeginGet operation has completed, the EndGet Event will fire.
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{

    // If an error occurred, it would be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
       Debug.WriteLine("Get completed for file " + file.RemoteFileName);
    }
    else
    {
       Debug.WriteLine("Error: " + e.Exception.ToString());
    }

    // Close the connection
    ftp1.Close();
}

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

FileEventArgs Members | Dart.PowerTCP.Ftp Namespace


FileEventArgs Members

FileEventArgs overview

Public Instance Properties

Exception | Gets any exception which occurred during the asynchronous operation.
File | Gets the FtpFile that represents a completed file transfer.
Files | Gets the FtpFile array that represents a completed file transfer.
State | Gets the object that was included as part of the associated method call.
Stream | Gets the FileEventArgs.Stream object that was part of the associated method call.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

FileEventArgs Class | Dart.PowerTCP.Ftp Namespace


FileEventArgs Properties

The properties of the FileEventArgs class are listed below. For a complete list of FileEventArgs class members, see the FileEventArgs Members topic.

Public Instance Properties

Exception | Gets any exception which occurred during the asynchronous operation.
File | Gets the FtpFile that represents a completed file transfer.
Files | Gets the FtpFile array that represents a completed file transfer.
State | Gets the object that was included as part of the associated method call.
Stream | Gets the FileEventArgs.Stream object that was part of the associated method call.

See Also

FileEventArgs Class | Dart.PowerTCP.Ftp Namespace


Exception Property

FileEventArgs.Exception Property

Gets any exception which occurred during the asynchronous operation.

[Visual Basic]
Public Property ReadOnly Exception As Exception
[C#]
public Exception Exception { get; }
[C++]
public: __property Exception* get_Exception();
[JScript]
public function get Exception() : Exception

Property Value

If any exception occurred during the asynchronous operation, this property will contain an Exception object describing the exception.

Remarks

Check this property to tell if an exception occurred during the asynchronous operation. If this property is null, no exception occurred.

The exception property is useful for checking exceptions and handling them appropriately. For example, if a bad command was sent to the server, a ProtocolException may be thrown. You could check this property to see if it was of type ProtocolException, than handle appropriately.

Example

The following example demonstrates an asynchronous BeginGet for a single file, with that file being returned as a stream that can be used to read the FTP data connection in the EndGet event. In this example the user-defined method GetTextFilePreview accepts a file and the amount of characters to preview. In the EndGet event, the amount of characters to preview is read from the data connection and displayed.

[Visual Basic]
' This user-defined method is used to generate a preview of text files residing on the FTP Server. The user enters the
' FileName of the file on the server that they would like a preview of and the number of characters to preview. BeginGet is
' called with the FileName and CharactersToPreview (as the object) being passed in. The EndGet event will fire when the
' stream has been opened and is ready for reading.

Private Sub GetTextPreview(ByVal FileName As String, ByVal CharactersToPreview As Long)

   ' Set server and user properties. This will allow calling of other
   ' Ftp Component methods with the log in taking place "behind the scenes"
   Ftp1.Server = "MyFTPServer"
   Ftp1.Username = "blah"
   Ftp1.Password = "mypass"

   ' Begin an asynchronous Get. This also demonstrates using the third parameter (object State) to pass the
   ' number of characters to preview. This variable will be accessible in the EndGet Event

   Ftp1.BeginGet(FileName, 0, CharactersToPreview)

End Sub

' When the BeginGet operation has completed, the EndGet Event will fire.
Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

   Debug.WriteLine("Attempting to read from data stream")

   ' If an error occurred, it would be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then
      'Retrieve the number of characters to preview from the object State.
      Dim AmountOfChars As Integer = Convert.ToInt32(e.State)

      ' Create a byte array the size of the amount of characters to preview.
      Dim data(AmountOfChars) As Byte

      ' Read the amount of characters to preview from the stream
      e.Stream.Read(data, 0, AmountOfChars)

      e.Stream.Close()

      ' Close the stream
      Ftp1.AbortTransfer()

      ' Display the preview characters
      TextBox1.Text = System.Text.Encoding.ASCII.GetString(data)
   Else
      Debug.WriteLine("Error: " + e.Exception.ToString())
   End If

   ' Close the connection
   Ftp1.Close()

End Sub

[C#]
/*
/*
This user-defined method is used to generate a preview of text files residing on the FTP Server.
The user enters the FileName of the file on the server that they would like a preview of and the
number of characters to preview. BeginGet is called with the FileName and CharactersToPreview
(as the object) being passed in. The EndGet event will fire when the stream has been opened and is
ready for reading.
*/

private void GetTextFilePreview(string FileName, long CharactersToPreview)
{
    // Set server and user properties. This will allow calling of other
    // Ftp Component methods with the log in taking place "behind the scenes"
    ftp1.Server = "MyFTPServer";
    ftp1.Username = "blah";
    ftp1.Password = "mypass";

    // Begin an asynchronous Get. This also demonstrates using the third parameter (object State) to pass the
    // number of characters to preview. This variable will be accessible in the EndGet Event
    ftp1.BeginGet(FileName, 0, CharactersToPreview);
}

// When the BeginGet operation has completed, the EndGet Event will fire.
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
    Debug.WriteLine("Attempting to read from data stream");

    // If an error occurred, it would be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
       int AmountOfChars;

       // Retrieve the number of characters to preview from the object State.
       AmountOfChars = Convert.ToInt32(e.State);

       // Create a byte array the size of the amount of characters to preview.
       byte[] data = new byte[AmountOfChars];

       // Read the amount of characters to preview from the stream
       e.Stream.Read(data, 0, AmountOfChars);

       // Close the stream
       ftp1.AbortTransfer();

       // Display the preview characters.
       textBox1.Text = System.Text.Encoding.ASCII.GetString(data);
    }
    else
    {
       Debug.WriteLine("Error: " + e.Exception.ToString());
    }

    // Close the connection
    ftp1.Close();
}

See Also

FileEventArgs Class | Dart.PowerTCP.Ftp Namespace


File Property

FileEventArgs.File Property

Gets the FtpFile that represents a completed file transfer.

[Visual Basic]
Public Property ReadOnly File As FtpFile
[C#]
public FtpFile File { get; }
[C++]
public: __property FtpFile* get_File();
[JScript]
public function get File() : FtpFile

Property Value

An FtpFile object describing the file transfer on both the local and remote machines.

Remarks

When BeginPut or BeginGet has been called to transfer one file, multiple files, or streams, the FtpFile object will contain data about the file transferred. For example, the amount of bytes transferred is accessible through Count, the file's local file name is accessible through LocalFileName, and the file's name on the server is accessible through RemoteFileName.

Example

The following example demonstrates how to asynchronously retrieve a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToGet As String = "test.txt"

' Call BeginGet, this will begin an asynchronous Get. Upon completion the EndGet Event will be fired.
Ftp1.BeginGet(FileToGet, "RetrievedFile.txt", Nothing)

' Display message, because BeginGet is asynchronous, this will be immediately executed.
Debug.WriteLine("Retrieving " + FileToGet)

' When the BeginGet operation has completed, the EndGet Event will fire.

Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

    ' If an error occurred, it would be returned in the event. Be sure to check for it.
    If e.Exception Is Nothing Then
       Debug.WriteLine("Get completed for file " + file.RemoteFileName)
    Else
       Debug.WriteLine("Error: " + e.Exception.ToString())
    End If

   ' Close the connection
   Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToGet = "test.txt";

// Call BeginGet, this will begin an asynchronous Get. Upon completion the EndGet Event will be fired.
ftp1.BeginGet(FileToGet, Application.StartupPath + "\\" + new System.IO.FileInfo(FileToGet).Name, null);

// Display message, because BeginGet is asynchronous, this will be immediately executed.
Debug.WriteLine("Retrieving " + FileToGet);

// When the BeginGet operation has completed, the EndGet Event will fire.
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{

    // If an error occurred, it would be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
       Debug.WriteLine("Get completed for file " + file.RemoteFileName);
    }
    else
    {
       Debug.WriteLine("Error: " + e.Exception.ToString());
    }

    // Close the connection
    ftp1.Close();
}

See Also

FileEventArgs Class | Dart.PowerTCP.Ftp Namespace


Files Property

FileEventArgs.Files Property

Gets the FtpFile array that represents a completed file transfer.

[Visual Basic]
Public Property ReadOnly Files As FtpFile()
[C#]
public FtpFile[] Files { get; }
[C++]
public: __property FtpFile* get_Files() __gc[];
[JScript]
public function get Files() : FtpFile[]

Property Value

FtpFile objects describing the file transfer on both the local and remote machines.

Remarks

When BeginPut or BeginGet has been called to transfer one file, multiple files, or streams, the Files array will contain an FtpFile object containing data about each file transferred. Iterate through this collection to retrieve data about each file transferred. For example, the amount of bytes transferred is accessible through FtpFiles[i].Count, the file's local file name is accessible through FtpFiles[i].LocalFileName, and the file's name on the server is accessible through FtpFiles[i].RemoteFileName.

Example

The following example demonstrates how to asynchronously retrieve multiple files.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Call BeginGet, this will begin an asynchronous Get. Upon completion the EndGet Event will be fired.
Ftp1.BeginGet("mydir", "*", Application.StartupPath + "/", false, Nothing)

' Display message, because BeginGet is asynchronous, this will be immediately executed.
Debug.WriteLine("Retrieving all files in mydir")

' When the BeginGet operation has completed, the EndGet Event will fire.

Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

   ' If an error occurred, it would be returned in the event. Be sure to =check for it.
   If e.Exception Is Nothing Then

       Dim file As Dart.PowerTCP.Ftp.FtpFile

      ' Iterate through files collection and display info. This will contain a File object
      ' for each file retrieved.
      For Each file In e.Files
         Debug.WriteLine("Get completed for " + file.RemoteFileName)
      Next
   Else
      Debug.WriteLine("Error: " + e.Exception.ToString())
   End If
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Call BeginGet for all files in the directory "mydir", this will begin an asynchronous MGet. Upon completion
// the EndGet Event will be fired.
ftp1.BeginGet("mydir", "*", Application.StartupPath + "//", false, null);

// Display message, because BeginGet is asynchronous, this will be immediately executed.
Debug.WriteLine("Retrieving all files in mydir");

// When the BeginGet operation has completed, the EndGet Event will fire.
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{

    // If an error occurred, it would be returned in the event. Be sure to check for it
    if(e.Exception == null)
    {
        // Iterate through files collection and display info. This will contain a File object
        // for each file retrieved.
        foreach(Dart.PowerTCP.Ftp.FtpFile file in e.Files)
            Debug.WriteLine("Get completed for file " + file.RemoteFileName);
    }
    else
    {
        Debug.WriteLine("Error: " + e.Exception.ToString());
    }
}

See Also

FileEventArgs Class | Dart.PowerTCP.Ftp Namespace


State Property

FileEventArgs.State Property

Gets the object that was included as part of the associated method call.

[Visual Basic]
Public Property ReadOnly State As Object
[C#]
public object State { get; }
[C++]
public: __property Object* get_State();
[JScript]
public function get State() : Object

Property Value

An object containing data passed into the calling asynchronous method.

Remarks

The EndEventArgs.State property can be used in the calling asynchronous method to make data accessible to the handling event.

This property is useful for making data accessible to the handling event. Since asynchronous methods are "disconnected" (meaning that when one is called, it executes on it's own and returns in the event handler) data that you were using in the code that called the asynchronous method may not be available in the event handler. Simply pass this data in as state when calling the asynchronous method (usually a BeginXXX method) and it is available in the event handler. If you do not wish to make an object accessible in the EndXXX event, simple pass in null as state.

Example

The following example demonstrates an asynchronous BeginGet for a single file, with that file being returned as a stream that can be used to read the FTP data connection in the EndGet event. In this example the user-defined method GetTextFilePreview accepts a file and the amount of characters to preview. In the EndGet event, the amount of characters to preview is read from the data connection and displayed.

[Visual Basic]
' This user-defined method is used to generate a preview of text files residing on the FTP Server. The user enters the
' FileName of the file on the server that they would like a preview of and the number of characters to preview. BeginGet is
' called with the FileName and CharactersToPreview (as the object) being passed in. The EndGet event will fire when the
' stream has been opened and is ready for reading.

Private Sub GetTextPreview(ByVal FileName As String, ByVal CharactersToPreview As Long)

   ' Set server and user properties. This will allow calling of other
   ' Ftp Component methods with the log in taking place "behind the scenes"
   Ftp1.Server = "MyFTPServer"
   Ftp1.Username = "blah"
   Ftp1.Password = "mypass"

   ' Begin an asynchronous Get. This also demonstrates using the third parameter (object State) to pass the
   ' number of characters to preview. This variable will be accessible in the EndGet Event

   Ftp1.BeginGet(FileName, 0, CharactersToPreview)

End Sub

' When the BeginGet operation has completed, the EndGet Event will fire.
Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

   Debug.WriteLine("Attempting to read from data stream")

   ' If an error occurred, it would be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then
      'Retrieve the number of characters to preview from the object State.
      Dim AmountOfChars As Integer = Convert.ToInt32(e.State)

      ' Create a byte array the size of the amount of characters to preview.
      Dim data(AmountOfChars) As Byte

      ' Read the amount of characters to preview from the stream
      e.Stream.Read(data, 0, AmountOfChars)

      e.Stream.Close()

      ' Close the stream
      Ftp1.AbortTransfer()

      ' Display the preview characters
      TextBox1.Text = System.Text.Encoding.ASCII.GetString(data)
   Else
      Debug.WriteLine("Error: " + e.Exception.ToString())
   End If

   ' Close the connection
   Ftp1.Close()

End Sub

[C#]
/*
/*
This user-defined method is used to generate a preview of text files residing on the FTP Server.
The user enters the FileName of the file on the server that they would like a preview of and the
number of characters to preview. BeginGet is called with the FileName and CharactersToPreview
(as the object) being passed in. The EndGet event will fire when the stream has been opened and is
ready for reading.
*/

private void GetTextFilePreview(string FileName, long CharactersToPreview)
{
    // Set server and user properties. This will allow calling of other
    // Ftp Component methods with the log in taking place "behind the scenes"
    ftp1.Server = "MyFTPServer";
    ftp1.Username = "blah";
    ftp1.Password = "mypass";

    // Begin an asynchronous Get. This also demonstrates using the third parameter (object State) to pass the
    // number of characters to preview. This variable will be accessible in the EndGet Event
    ftp1.BeginGet(FileName, 0, CharactersToPreview);
}

// When the BeginGet operation has completed, the EndGet Event will fire.
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
    Debug.WriteLine("Attempting to read from data stream");

    // If an error occurred, it would be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
       int AmountOfChars;

       // Retrieve the number of characters to preview from the object State.
       AmountOfChars = Convert.ToInt32(e.State);

       // Create a byte array the size of the amount of characters to preview.
       byte[] data = new byte[AmountOfChars];

       // Read the amount of characters to preview from the stream
       e.Stream.Read(data, 0, AmountOfChars);

       // Close the stream
       ftp1.AbortTransfer();

       // Display the preview characters.
       textBox1.Text = System.Text.Encoding.ASCII.GetString(data);
    }
    else
    {
       Debug.WriteLine("Error: " + e.Exception.ToString());
    }

    // Close the connection
    ftp1.Close();
}

See Also

FileEventArgs Class | Dart.PowerTCP.Ftp Namespace


Stream Property

FileEventArgs.Stream Property

Gets the FileEventArgs.Stream object that was part of the associated method call.

[Visual Basic]
Public Property ReadOnly Stream As Stream
[C#]
public Stream Stream { get; }
[C++]
public: __property Stream* get_Stream();
[JScript]
public function get Stream() : Stream

Property Value

If BeginGet or BeginPut were called, passing in an already created Stream object, in the EndGet and EndPut event handler, the FileEventArgs.Stream object will contain this stream. If BeginGet or BeginPut were called to directly read/write to a file on the server, in the EndGet and EndPut event handler, the FileEventArgs.Stream object will contain that opened stream, which can then be used to read to or write from the data connection.

Remarks

The FileEventArgs.Stream object is used two ways. The first is when BeginGet is called to retrieve a file as a stream or BeginPut is called to store a stream as a file. In both cases, the FileEventArgs.Stream object will contain that completed stream.

The second way to use this property is when BeginGet is used to read directly from the data connection or BeginPut is used to write directly to the data connection. In these cases, Stream will contain a SegmentedStream object to use to read from/write to the data connection. Simply call Read or Write to read/write data to/from the stream. When reading is complete. the Ftp component will close the stream. If you do not wish to read the entire file, call Ftp.AbortConnection to close the data connection.

Example

The following example demonstrates an asynchronous BeginGet for a single file, with that file being returned as a stream that can be used to read the FTP data connection in the EndGet event. In this example the user-defined method GetTextFilePreview accepts a file and the amount of characters to preview. In the EndGet event, the amount of characters to preview is read from the data connection and displayed.

[Visual Basic]
' This user-defined method is used to generate a preview of text files residing on the FTP Server. The user enters the
' FileName of the file on the server that they would like a preview of and the number of characters to preview. BeginGet is
' called with the FileName and CharactersToPreview (as the object) being passed in. The EndGet event will fire when the
' stream has been opened and is ready for reading.

Private Sub GetTextPreview(ByVal FileName As String, ByVal CharactersToPreview As Long)

   ' Set server and user properties. This will allow calling of other
   ' Ftp Component methods with the log in taking place "behind the scenes"
   Ftp1.Server = "MyFTPServer"
   Ftp1.Username = "blah"
   Ftp1.Password = "mypass"

   ' Begin an asynchronous Get. This also demonstrates using the third parameter (object State) to pass the
   ' number of characters to preview. This variable will be accessible in the EndGet Event

   Ftp1.BeginGet(FileName, 0, CharactersToPreview)

End Sub

' When the BeginGet operation has completed, the EndGet Event will fire.
Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

   Debug.WriteLine("Attempting to read from data stream")

   ' If an error occurred, it would be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then
      'Retrieve the number of characters to preview from the object State.
      Dim AmountOfChars As Integer = Convert.ToInt32(e.State)

      ' Create a byte array the size of the amount of characters to preview.
      Dim data(AmountOfChars) As Byte

      ' Read the amount of characters to preview from the stream
      e.Stream.Read(data, 0, AmountOfChars)

      e.Stream.Close()

      ' Close the stream
      Ftp1.AbortTransfer()

      ' Display the preview characters
      TextBox1.Text = System.Text.Encoding.ASCII.GetString(data)
   Else
      Debug.WriteLine("Error: " + e.Exception.ToString())
   End If

   ' Close the connection
   Ftp1.Close()

End Sub

[C#]
/*
/*
This user-defined method is used to generate a preview of text files residing on the FTP Server.
The user enters the FileName of the file on the server that they would like a preview of and the
number of characters to preview. BeginGet is called with the FileName and CharactersToPreview
(as the object) being passed in. The EndGet event will fire when the stream has been opened and is
ready for reading.
*/

private void GetTextFilePreview(string FileName, long CharactersToPreview)
{
    // Set server and user properties. This will allow calling of other
    // Ftp Component methods with the log in taking place "behind the scenes"
    ftp1.Server = "MyFTPServer";
    ftp1.Username = "blah";
    ftp1.Password = "mypass";

    // Begin an asynchronous Get. This also demonstrates using the third parameter (object State) to pass the
    // number of characters to preview. This variable will be accessible in the EndGet Event
    ftp1.BeginGet(FileName, 0, CharactersToPreview);
}

// When the BeginGet operation has completed, the EndGet Event will fire.
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
    Debug.WriteLine("Attempting to read from data stream");

    // If an error occurred, it would be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
       int AmountOfChars;

       // Retrieve the number of characters to preview from the object State.
       AmountOfChars = Convert.ToInt32(e.State);

       // Create a byte array the size of the amount of characters to preview.
       byte[] data = new byte[AmountOfChars];

       // Read the amount of characters to preview from the stream
       e.Stream.Read(data, 0, AmountOfChars);

       // Close the stream
       ftp1.AbortTransfer();

       // Display the preview characters.
       textBox1.Text = System.Text.Encoding.ASCII.GetString(data);
    }
    else
    {
       Debug.WriteLine("Error: " + e.Exception.ToString());
    }

    // Close the connection
    ftp1.Close();
}

See Also

FileEventArgs Class | Dart.PowerTCP.Ftp Namespace


FileEventHandler Delegate

Represents the method (event handler) that will be raised when the BeginPut or BeginGet operation completes.

[Visual Basic]
Public Delegate Function Sub  FileEventHandler( _
   ByVal sender As Object, _
   ByVal e As FileEventArgs _
)
[C#]
public delegate void FileEventHandler(
   object sender,
   FileEventArgs e
)
[C++]
public __gc __delegate void FileEventHandler(
   Object* sender,
   FileEventArgs* e
)

[JScript] In JScript, you can use the delegates defined by a type, but you cannot define your own.

Parameters

sender
The source of the event.
e
A FileEventArgs object that contains the event data.

Remarks

As Microsoft describes in their MSDN documentation, the event model in the .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed:

  • A class that holds the event data. This class must derive from the base class EventArgs.
  • A delegate that points to a method that provides the response to the event.
When using the BeginPut or BeginGet method, the class that holds the event data is the FileEventArgs class. A method must be created with the same signature as the FileEventArgs delegate. If you are working within the Visual Studio.NET environment, this can be automatically done for you. See the "Using Events In PowerTCP" topic for more information. If you are not working within the Visual Studio.NET environment, you must do this yourself. In this example that would mean a method would have to be defined to accept two arguments (an object and a FileEventArgs) and return void. Once this has been done, the delegate must be "connected" to the handling event. This is done by adding an instance of the delegate to the event (see examples below).

For more information about event handler delegates, see the "Using Events In PowerTCP" topic.

Example

The following example demonstrates how to assign an event handler to an event.

[Visual Basic]
' *** EndPut Event ***

' You can either use the AddHandler statement to associate an event with an event handler in your init code
AddHandler Ftp1.EndPut, New Dart.PowerTCP.Ftp.FileEventHandler(AddressOf Ftp1_EndPut)

' Or you can use the Handles keyword to associate an event handler with an event
Private Sub Ftp1_EndPut(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndPut

[C#]
// EndPut event
this.ftp1.EndPut += new Dart.PowerTCP.Ftp.FileEventHandler(this.ftp1_EndPut);

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


FileType Enumeration

Enumerates the type of file (ASCII, Image, or Ebcdic).

[Visual Basic]
Public Enum FileType
[C#]
public enum FileType
[C++]
public __value enum FileType
[JScript]
public enum FileType

Remarks

This enumeration is used by the FileType property.

When set to FileType.Ascii, a CR/LF pair should be put at the end of every line in the file before sending it. Since the Windows operating system already uses a CR/LF pair as the native line separator, there is no need to modify the stream as it is received or sent. Another operating system that uses a single CR as the native line separator, however, must expand the size of most files it sends, and shrink the size of most files it receives (to change the line separator to/from a CR/LF pair).

When set to Image, the line separator remains unmodified, making this property setting necessary for sending and receiving binary files (that may contain line separators).

Example

The following example demonstrates checking to see the type of file (by looking at the bytes) and setting the FileType accordingly.

[Visual Basic]
' This method demonstrates checking the bytes of a file to determine if
' it is binary or ASCII, then FTPing accordingly

' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FilePath As String = "C:\FtpTest\log.txt"

' Create new filestream
Dim fstream As New System.IO.FileStream(FilePath, IO.FileMode.Open)

' Create new byte array to hold the FileStream's data
Dim data(fstream.Length) As Byte

' Read data from the file into the buffer.
fstream.Read(data, 0, fstream.Length)
fstream.Close()

Dim binary As Boolean = False

' Iterate through the bytes, checking to see if any are above 128. If so it is
' binary. (This is not a 100% accurate way of checking a file because the file
' may be a binary file whose bytes all happen to be below 128.)

Dim i As Integer
For i = 0 To data.Length - 1
   If data(i) > 128 Then
      binary = True
   End If
Next

' Set the file type
If binary Then
   Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image
Else
   Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Ascii
End If

' Put the file (The FileInfo object parses the name from the path)
Ftp1.Put(FilePath, New System.IO.FileInfo(FilePath).Name)

[C#]
// This method demonstrates checking the bytes of a file to determine if
// it is binary or ASCII, then FTPing accordingly

// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FilePath = "C:\\Files\\binaryfile.exe";

// Create new filestream
System.IO.FileStream fstream = new System.IO.FileStream(FilePath, System.IO.FileMode.Open);

// Create new byte array to hold the FileStream's data
byte[] data = new byte[fstream.Length];

// Read data from the file into the buffer.
fstream.Read(data, 0, (int)fstream.Length);
fstream.Close();

bool binary = false;

// Iterate through the bytes, checking to see if any are above 128. If so it is
// binary. (This is not a 100% accurate way of checking a file because the file
// may be a binary file whose bytes all happen to be below 128.)
for(int i = 0; i < data.Length; i++)
    if(data[i] > 128)
        binary = true;

// Set the file type
if(binary)
    ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;
else
    ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Ascii;

// Put the file (The FileInfo object parses the name from the path)
ftp1.Put(FilePath,  new System.IO.FileInfo(FilePath).Name);

Members

Member Name | Description
Image | Transfer the file as a binary image.
Ascii | Convert between local EOL indications and network CR/LF during transmission.
Ebcdic | Send/receive EBCDIC 8-bit characters.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


Ftp Class

The Ftp component supports comprehensive files transfer activities with any FTP server.

For a list of all members of this type, see Ftp Members.

System.Object
System.MarshalByRefObject
System.ComponentModel.Component
Dart.PowerTCP.Ftp.Ftp

[Visual Basic]
Public Class Ftp
    Inherits Component
[C#]
public class Ftp : Component
[C++]
public __gc class Ftp : public Component
[JScript]
public class Ftp extends Component

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

The Ftp component provides high-level File Transfer Protocol capabilities to your application including the ability to transfer files and streams, and the ability to read/write to the data connection. Also supported is the ability to send any command (including proprietary commands to the server). These capabilities are all encapsulated by high-level methods, so no knowledge of low-level protocols is required. Asynchronous and synchronous use is fully supported.

Using the Ftp Component

What follows are short descriptions of common usability issues. For a more complete description, see the topic Using The Ftp Component Overview.

Logging in/out: Before any communication with the server can take place, the Server, ServerPort, Username, and Password properties must first be set. Once set, whenever communication needs to occur with the server, the client will automatically be logged in. The client will stay logged in until either the Ftp component is destroyed or either the Close or Abort methods are called. In addition, any time the Server, ServerPort, Username, or Password properties change, this change will be detected and the next time communication with a server is required, it will occur using the newly updated information.

For more information about logging in and out, see the topic Session Management Overview.

Synchronous Use: Most applications written with the Ftp component will be synchronous meaning that the application, when calling a synchronous method, will not execute the next line of code until the response is received. Use synchronous methods when file transfer does not have to be transparent to the user.

Asynchronous Use: The Ftp component fully supports asynchronous use, meaning that the application, when calling an asynchronous method, will immediately execute the next line of code without waiting for the response from the method. When the response is received, an event will be raised. Contained within this event will be an object derived from EventArgs, supplying necessary data about the method called. So when calling any asynchronous method in PowerTCP, you must create an event handler to handle the response from the method call. This means for each asynchronous method BeginXXX, there will be a corresponding event to handle the response, EndXXX. Use asynchronous methods when file transfer needs to occur transparently to the user, allowing continued use of the application while transfer is occurring.

For more information about using synchronous and asynchronous methods, see the topic Synchronous Versus Asynchronous Methods.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

Transferring files: Files can be synchronously retrieved using the Get method. Files can be synchronously stored using the Put method. The asynchronous counterparts to these two methods are the BeginGet and BeginPut methods, (handling the response from these two methods in the EndGet and EndPut events, respectively). All of these methods are overloaded to support storing and retrieving of multiple files.

For more information about transferring files, see either the topic Storing Files Overview or Retrieving Files Overview.

Transferring streams: Files can be synchronously retrieved as streams using the Get method (when passing in a stream), and streams can be synchronously put to the server as files using the Put method (when passing in a stream). The asynchronous counterparts to these synchronous methods are the BeginGet and BeginPut methods (handling the response from these methods in the EndGet and EndPut events, respectively).

For more information about transferring streams, see the topic Transferring Streams Overview.

Reading/Writing to the data stream: The Ftp component can be used to read and write to an opened data stream. To do this synchronously, use the Get and Put methods, and asynchronously, use the BeginGet and BeginPut methods (handling the response from these methods in the EndGet and EndPut events, respectively). These methods return a SegmentedStream object, which can then be used to read/write data from/to the data connection.

For more information about reading and writing to the data stream, see the topic Accessing The Data Connection Overview.

Sending commands: Commands are sent two ways using the Ftp component. The first is when they are encapsulated by a high-level method. For example, the Rename method encapsulates the sending of the RNFR (rename from) and RNTO (rename to) commands. Other high-level commands include GetSize (issues the SIZE command and parses the response), GetDirectory (issues a PWD and parses the response), and List (synchronous) and BeginList (asynchronous), returns an encapsulated listing. The second is when commands are explicitly using the Invoke (synchronous) or BeginInvoke (asynchronous) methods. Use this method to send any command not included in any higher level method (including proprietary commands).

For more information about sending commands to the server, see the topic Sending Commands Overview.

Retrieving info about the control connection: The TCP control connection is exposed through the Connection property, allowing access to low-level properties and methods. This can be used to view TCP-level activity such as the local and remote IP address. The Tcp class can't be used on its own without a license for the PowerTCP Socket Objects.

Example

The following example demonstrates simple use of the client/server properties in storing a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToStore As String = "c:\FtpTest\mynewfile.bmp"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file transfer
Dim file As Dart.PowerTCP.Ftp.FtpFile
Debug.WriteLine("Attempting to store file " + FileToStore)

Try
   ' Attempt to store the file (The FileInfo object parses the filename from the path)
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

// Put method returns an FtpFile object containing information about the file transfer
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

try
{
    // Attempt to store the file (The FileInfo object parses the filename from the path)
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

// Close the connection
ftp1.Close();

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Ftp Members | Dart.PowerTCP.Ftp Namespace


Ftp Members

Ftp overview

Public Instance Constructors

Ftp Overloaded. Initializes a new instance of the Ftp class.

Public Instance Properties

Account | Gets or sets account information required by the server. Not normally used.
Allocate | Gets or sets a value that controls the use of the ALLO command before files are stored on the server.
BlockSize | Gets or sets the buffer size used during file and socket I/O.
Busy | Returns true if a method is currently in use.
Certificate | The Certificate object representing the certificate to use for optional client-side authentication.
Client | Gets or sets the client hostname or address when a specific interface binding is desired.
ClientDataPort | Gets or sets a string used to restrict the local data port to a value or range compatible with your firewall.
ClientPort | Gets or sets a string used to restrict the local data port to a value or range of values.
Compression | Gets or sets the type of compression desired.
Connected | Gets the connected state of the connection.
Connection | Gets the Tcp component instance used for the connection.
Container (inherited from Component) | Gets the IContainer that contains the Component.
DoEvents | Gets or sets a value that controls the processing of events during blocking method calls.
Editor | In Visual Studio.NET, displays an interactive form to use to test real time protocol operations.
FileType | Gets or sets the data type for subsequent transfers.
MaxTransferRate | Gets or sets the maximum transfer rate of the Ftp component in bytes per second.
Passive | Gets or sets a value that determines if the server should accept a passive data connection.
Password | Gets or sets the password used during session login.
ProgressSize | Gets or sets a value that controls the frequency for raising the Progress event.
Proxy | Returns the FtpProxy instance that controls proxy server use.
Restart | Gets or sets a value that controls the automatic use of file transfer restarts.
Security | Specifies the security protocol and authentication type used.
Server | Gets or sets the FTP server hostname or address.
ServerPort | Gets or sets the FTP server port.
Site (inherited from Component) | Gets or sets the ISite of the Component.
StoreType | Gets or sets the type of store to use when the Put method or BeginPut method is called.
SynchronizingObject | Set this object to automatically control thread marshalling between worker threads and the main UI thread.
Timeout | Specifies the maximum number of milliseconds to wait for responses to commands or time between data buffer transfers.
UseAuthentication | Gets or sets a value that determines if certificate authentication is used.
UseControlAddressForPassive | Gets or sets or a value that determines what server address should be used when doing a Passive data connection.
UseIpSync | Indicates whether 'Interrupt Process and Synch' bytes are sent with the ABOR command.
Username | Gets or sets the Username used during session login.
UseSslShutdown | Controls whether or not shut-down bytes are sent to the server when the connection is closed.

Public Instance Methods

Abort | Abruptly close both the control and data connection.
AbortTransfer | Abort the current file transfer operation.
BeginDelete | Deletes a file or directory tree asynchronously.
BeginGet | Overloaded. Get a single file from the server asynchronously and store it in a local file.
BeginInvoke | Invoke an FTP command (with a parameter) asynchronously.
BeginList | Get a file listing from the server asynchronously.
BeginPut | Overloaded. Put multiple files to the server asynchronously and store them in the root specified.
Close | Wait for all activity to complete and gracefully close the control connection.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Delete | Overloaded. Deletes a file or directory tree synchronously.
Dispose (inherited from Component) | Releases all resources used by the Component.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
ExpandLocalFiles | Gets a string array of local file pathnames that match the wildcard search pattern.
ExpandRemoteFiles | Gets a string array of remote file pathnames that match the wildcard search pattern.
Get | Overloaded. Get a single file from the server synchronously.
GetDirectory | Gets the server's working directory.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetSize | Gets the size of any file.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
Invoke | Overloaded. Send an FTP command (with a command modifier) synchronously.
List | Retrieve a file listing from the server synchronously.
Put | Overloaded. Store a single file to the server synchronously.
RawConnect | Optional method you can use if you need to connect to an FTP server that expects a login sequence that is non-standard.
Rename | Rename a file on the server.
SendCommand | Send an FTP command synchronously.
ToString (inherited from Component) | Overridden.

Public Instance Events

BusyChanged | Raised when the value of the Object.Busy property changes.
CertificateReceived | This event is raised when a certificate has been received to be authenticated.
CertificateRequested | This event is raised when a certificate has been requested.
ConnectedChanged | Raised when the value of the Object.Connected property changes.
Disposed (inherited from Component) | Adds an event handler to listen to the Disposed event on the component.
EndDelete | Raised when the BeginDelete request completes.
EndGet | Raised when the BeginGet request completes.
EndInvoke | Raised when the BeginInvoke request completes.
EndList | Raised when the BeginList request completes.
EndPut | Raised when the BeginPut request completes.
Preview | Raised before each file is transferred.
Progress | Raised repeatedly while a file transfer is in progress.
Trace | Raised when data has been sent/received.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Ftp Constructor

Initializes a new instance of the Ftp component.

Overload List

Initializes a new instance of the Ftp component.

[Visual Basic] Public Sub New()
[C#] public Ftp();
[C++] public: Ftp();
[JScript] public function Ftp();

Initializes a new instance of the Ftp component.

[Visual Basic] Public Sub New(ByVal IContainer)
[C#] public Ftp(IContainer);
[C++] public: Ftp(IContainer*);
[JScript] public function Ftp(IContainer);

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Ftp Constructor (IContainer)

Initializes a new instance of the Ftp component.

[Visual Basic]
Public Sub New( _
   ByVal container As IContainer _
)
[C#]
public Ftp(
   IContainer container
);
[C++]
public: Ftp(
   IContainer* container
);
[JScript]
public function Ftp(
   IContainer container
);

Parameters

container
The IContainer which contains the Ftp component.

Remarks

Use this constructor to add the Ftp component to the IContainer container. When using Visual Studio.NET, simply add the Ftp component to the form and the object will automatically be created and initialized. If working out of the Visual Studio.NET environment (or using the Ftp component as a reference), the Ftp component will have to be explicitly created and initialized.

For information on how to use the Ftp component, see "Using The Ftp Component".

The following table shows initial property values for an instance of Ftp.

Property | Initial Value
Account | zero-length string
Allocate | false
BlockSize | 8196
Client | zero-length string
ClientDataPort | 0
ClientPort | 0
Connected | false
Connection | reference to Tcp component
DoEvents | true
FileType | FileType.Ascii
Passive | true
Password | zero-length string
Proxy | FtpProxy object
Restart | false
Server | zero-length string
ServerPort | 21
StoreType | StoreType.Replace
Timeout | 30000
Username | zero-length string

Example

The following example demonstrates creating an Ftp object.

[Visual Basic]
' Declare as class member
Friend WithEvents Ftp1 As Dart.PowerTCP.Ftp.Design.Ftp

' Create in class initilization
Me.Ftp1 = New Dart.PowerTCP.Ftp.Design.Ftp(Me.components)

[C#]
private Dart.PowerTCP.Ftp.Design.Ftp ftp1 = new Dart.PowerTCP.Ftp.Design.Ftp(this.components);

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp Constructor Overload List


Ftp Constructor ()

Initializes a new instance of the Ftp component.

[Visual Basic]
Public Sub New()
[C#]
public Ftp();
[C++]
public: Ftp();
[JScript]
public function Ftp();

Remarks

The default constructor initializes a new Ftp component. When using Visual Studio.NET, simply add the Ftp component to the form and the object will automatically be created and initialized. If working out of the Visual Studio.NET environment (or using the Ftp component as a reference), the Ftp component will have to be explicitly created and initialized.

For information on how to use the Ftp component, see "Using The Ftp Component".

The following table shows initial property values for an instance of Ftp.

Property | Initial Value
Account | zero-length string
Allocate | false
BlockSize | 8196
Client | zero-length string
ClientDataPort | 0
ClientPort | 0
Connected | false
Connection | reference to Tcp component
DoEvents | true
FileType | FileType.Ascii
Passive | true
Password | zero-length string
Proxy | FtpProxy object
Restart | false
Server | zero-length string
ServerPort | 21
StoreType | StoreType.Replace
Timeout | 30000
Username | zero-length string

Example

The following example demonstrates creating an Ftp object.

[Visual Basic]
' Declare as class member
Friend WithEvents Ftp1 As Dart.PowerTCP.Ftp.Ftp

' Create in class initilization
Me.Ftp1 = New Dart.PowerTCP.Ftp.Design.Ftp

[C#]
private Dart.PowerTCP.Ftp.Ftp ftp1 = new Dart.PowerTCP.Ftp.Ftp();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp Constructor Overload List


Ftp Properties

The properties of the Ftp class are listed below. For a complete list of Ftp class members, see the Ftp Members topic.

Public Instance Properties

Account | Gets or sets account information required by the server. Not normally used.
Allocate | Gets or sets a value that controls the use of the ALLO command before files are stored on the server.
BlockSize | Gets or sets the buffer size used during file and socket I/O.
Busy | Returns true if a method is currently in use.
Certificate | The Certificate object representing the certificate to use for optional client-side authentication.
Client | Gets or sets the client hostname or address when a specific interface binding is desired.
ClientDataPort | Gets or sets a string used to restrict the local data port to a value or range compatible with your firewall.
ClientPort | Gets or sets a string used to restrict the local data port to a value or range of values.
Compression | Gets or sets the type of compression desired.
Connected | Gets the connected state of the connection.
Connection | Gets the Tcp component instance used for the connection.
Container (inherited from Component) | Gets the IContainer that contains the Component.
DoEvents | Gets or sets a value that controls the processing of events during blocking method calls.
Editor | In Visual Studio.NET, displays an interactive form to use to test real time protocol operations.
FileType | Gets or sets the data type for subsequent transfers.
MaxTransferRate | Gets or sets the maximum transfer rate of the Ftp component in bytes per second.
Passive | Gets or sets a value that determines if the server should accept a passive data connection.
Password | Gets or sets the password used during session login.
ProgressSize | Gets or sets a value that controls the frequency for raising the Progress event.
Proxy | Returns the FtpProxy instance that controls proxy server use.
Restart | Gets or sets a value that controls the automatic use of file transfer restarts.
Security | Specifies the security protocol and authentication type used.
Server | Gets or sets the FTP server hostname or address.
ServerPort | Gets or sets the FTP server port.
Site (inherited from Component) | Gets or sets the ISite of the Component.
StoreType | Gets or sets the type of store to use when the Put method or BeginPut method is called.
SynchronizingObject | Set this object to automatically control thread marshalling between worker threads and the main UI thread.
Timeout | Specifies the maximum number of milliseconds to wait for responses to commands or time between data buffer transfers.
UseAuthentication | Gets or sets a value that determines if certificate authentication is used.
UseControlAddressForPassive | Gets or sets or a value that determines what server address should be used when doing a Passive data connection.
UseIpSync | Indicates whether 'Interrupt Process and Synch' bytes are sent with the ABOR command.
Username | Gets or sets the Username used during session login.
UseSslShutdown | Controls whether or not shut-down bytes are sent to the server when the connection is closed.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Account Property

Ftp.Account Property

Gets or sets account information required by the server. Not normally used.

[Visual Basic]
Public Property Account As String
[C#]
public string Account { get; set; }
[C++]
public: __property String* get_Account();
public: __property void set_Account(String* );
[JScript]
public function get Account() : String
public function set Account(String);

Property Value

A string to be automatically sent (along with the ACCT command) in response to a 332 reply code.

Remarks

Although most servers either allow anonymous FTP, or simply use USER and PASS for authentication, a small portion of servers require account information as well. In this case, the server will issue a reply code of 332 in response to the PASS <password> command, expecting a response in the form ACCT <account name>. The server may issue this response later in the dialogue as well (for example, when attempting to access a file). When the Account property is set, the ACCT command is automatically sent in response to a reply code of 332.

Use the Account property if you expect your application could be used against servers that issue a 332 reply code as a response to PASS or other commands.

Example

The following example demonstrates simple use of the Account property to cause the ACCT command to be transparently issued in response to a 332 response code.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' If response to PASS command (or any other command) is 332, the ACCT command
' will automatically be issued if the Account property is set.
Ftp1.Account = "myaccount"

Dim FileToStore As String = "c:\FtpTest\mynewgfile.bmp"

' Sending an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to store file " + FileToStore)

' Store the file (FileInfo object parses the name from the path)
Try
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// If response to PASS command (or any other command) is 332, the ACCT command
// will automatically be issued if the Account property is set.
ftp1.Account = "myaccount";

// Sending an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// Put method returns an FtpFile object containing information about the file
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

// Store the file (FileInfo object parses the name from the path)
try
{
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Allocate Property

Ftp.Allocate Property

Gets or sets a value that controls the use of the ALLO command before files are stored on the server.

[Visual Basic]
Public Property Allocate As Boolean
[C#]
public bool Allocate { get; set; }
[C++]
public: __property bool get_Allocate();
public: __property void set_Allocate(bool );
[JScript]
public function get Allocate() : bool
public function set Allocate(bool);

Property Value

true if the ALLO command is to be sent before any file storage takes place, otherwise false. The default value is false.

Remarks

When set to true, the ALLO command will be sent to the server with the proper file size before the STOR, APPE or STOU commands are sent. Most servers do not require it's use and should ignore it. However, some servers need to allocate room for an incoming file and the ALLO command is used for that purpose. Use the Allocate property if you expect your application could be used against servers which require the ALLO command to be sent with the file size of files to be transferred.

Example

The following example demonstrates simple use of the Allocate property to transparently issue the ALLO command before storing a file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set Allocate property to true, this will cause the ALLO command to be sent before storing a
' file to reserve space on the server.
Ftp1.Allocate = true

Dim FileToStore As String = "c:\FtpTest\mynewgfile.bmp"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to store file " + FileToStore)

' Store the file. The ALLO command will be transparently issued before the file is stored.
' (The FileInfo object is used to parse the filename from the filepath)
Try
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set Allocate property to true, this will cause the ALLO command to be sent before storing a
// file to reserve space on the server.
ftp1.Allocate = true;

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

// Put method returns an FtpFile object containing information about the file
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

// Store the file. The ALLO command will be transparently issued before the file is stored.
// (The FileInfo object is used to parse the filename from the filepath)
try
{
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


BlockSize Property

Ftp.BlockSize Property

Gets or sets the buffer size used during file and socket I/O.

[Visual Basic]
Public Property BlockSize As Integer
[C#]
public int BlockSize { get; set; }
[C++]
public: __property int get_BlockSize();
public: __property void set_BlockSize(int );
[JScript]
public function get BlockSize() : int
public function set BlockSize(int);

Property Value

An integer value indicating the buffer size to use during file and socket I/O. Defaults to 8196.

Remarks

When sending a file, this value determines how many bytes are processed for each file read. When receiving a file, this value determines how large a buffer will be used for receiving file data.

The Progress event will be raised in the frequency specified by this property.

Set the BlockSize property to a lower number if you wish to have the Progress event be raised more frequently.

Example

The following example demonstrates capturing file transfer progress info.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFtpServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
Ftp1.BlockSize = 1024

' Set the MaxTransfer Rate to 5 kbps
Ftp1.MaxTransferRate = 5

' Attempt to put multiple files to the server
Try
   Ftp1.Put("C:\Test", "*", "", True)
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Complete!")

' Monitor the progress using the progress event.
Private Sub Ftp1_Progress(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ProgressEventArgs) Handles Ftp1.Progress
   ' Display the currently transferring file
   Label1.Text = "Currently transferring " + e.FileName

   ' Display the total bytes transferred
   Label2.Text = "Total bytes transferred: " + e.Count

   ' Display the current transfer rate
   Label3.Text = "Transfer Rate: " + e.TransferRate

   ' Set the properties of ProgressBar1 (this ProgressBar displays progress
   ' for each individual file)
   ProgressBar1.Minimum = 0
   ProgressBar1.Maximum = e.Length
   ProgressBar1.Value = e.Position

   ' Set the properties of progressBar2 (this ProgressBar displays progress
   ' for all files, useful when transferring multiple files - MPUT).
   ProgressBar2.Minimum = 0
   ProgressBar2.Maximum = e.TotalFiles
   ProgressBar2.Value = e.CurrentFile
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
ftp1.BlockSize = 1024;

// Set the MaxTransferRate to 5 kbps
ftp1.MaxTransferRate = 5;

// Attempt to put multiple files to the server
try
{
   ftp1.Put("C:\\Test", "*", "", true);
}
catch(Exception ex)
{
   Debug.WriteLine("Error: " + ex.Message);
   return;
}

// Success
Debug.WriteLine("Complete!");

// Monitor the progress using the progress event.
private void ftp1_Progress(object sender, Dart.PowerTCP.Ftp.ProgressEventArgs e)
{
   // Display the currently transferring file
   label1.Text = "Currently transferring " + e.FileName;

   // Display the total bytes transferred
   label2.Text = "Total bytes transferred: " + e.Count;

   // Display the current transfer rate
   label3.Text = "Transfer Rate: " + e.TransferRate;

   // Set the properties of progressBar1 (this ProgressBar displays progress
   // for each individual file)
   progressBar1.Minimum = 0;
   progressBar1.Maximum = (int)e.Length;
   progressBar1.Value = (int)e.Position;

   // Set the properties of progressBar2 (this ProgressBar displays progress
   // for all files, useful when transferring multiple files - MPUT).
   progressBar2.Minimum = 0;
   progressBar2.Maximum = (int)e.TotalFiles;
   progressBar2.Value = (int)e.CurrentFile;
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Busy Property

Ftp.Busy Property

Returns true if a method is currently in use.

[Visual Basic]
Public Property ReadOnly Busy As Boolean
[C#]
public bool Busy { get; }
[C++]
public: __property bool get_Busy();
[JScript]
public function get Busy() : bool

Property Value

true if a method is currently is use, otherwise false

Remarks

When used in PowerTCP Zip Compression for .NET, this property provides protection against accessing a method that is still processing a command.

When used in an Internet communications component, this property provides protection against sending commands over a busy socket. For example, if the PowerTCP component is engaged in sending or receiving data, and another method is called that requires use of the same socket, a BusyException is thrown.

The Object.BusyChanged event is raised whenever the value of this property changes.

For Internet communications components, check this property within your code if you feel a new operation could be attempted over a socket that is already engaged in sending or receiving data. This property is also useful for displaying socket status to the user. For example, a "stoplight" could be part of the user interface that would be red when the Object.Busy property is true, and green when false.

Example

The following example demonstrates the Busy property, the BusyChanged event, and the BusyException.

[Visual Basic]
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
   ' Set server and user properties. This will allow calling of other
   ' Ftp Component methods with the log in taking place "behind the scenes"
   Ftp1.Server = "MyFtpServer"
   Ftp1.Username = "blah"
   Ftp1.Password = "mypass"

   ' Storing a binary file
   Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

   ' Store a large file, Ftp.Busy will be true for the duration
   ' of the store operation.
   Ftp1.BeginPut("C:\Test\Test.bmp", "newtest.bmp", Nothing)

   ' Try another asynchronous method immediately after the
   'first, this should throw a BusyException
   Try
      Ftp1.BeginPut("C:\Test\Test.bmp", "newtest2.bmp", Nothing)
   Catch BusyEx As Dart.PowerTCP.Ftp.BusyException
      Debug.WriteLine("BusyException: " + BusyEx.Message)
   End Try
End Sub

Private Sub Ftp1_BusyChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Ftp1.BusyChanged
   Debug.WriteLine("Busy property changed. Busy now = " + Ftp1.Busy)
End Sub

Private Sub Ftp1_EndPut(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndPut
   If e.Exception Is Nothing Then
      Debug.WriteLine("Put complete")
   Else
      Debug.WriteLine("Error: " + e.Exception.Message)
   End If
End Sub

[C#]
private void button1_Click(object sender, System.EventArgs e)
{
   // Set server and user properties. This will allow calling of other
   // Ftp Component methods with the log in taking place "behind the scenes"
   ftp1.Server = "MyFtpServer";
   ftp1.Username = "blah";
   ftp1.Password = "mypass";

   // Storing a binary file
   ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

   // Store a large file, Ftp.Busy will be true for the duration
   // of the store operation.
   ftp1.BeginPut("C:\\Test\\Test.bmp", "newtest.bmp", null);

   // Try another asynchronous method immediately after the
   // first, this should throw a BusyException
   try
   {
      ftp1.BeginPut("C:\\Test\\Test.bmp", "newtest2.bmp", null);
   }
   catch(Dart.PowerTCP.Ftp.BusyException BusyEx)
   {
                Debug.WriteLine("BusyException: " + BusyEx.Message);
   }
}

// BusyChanged event fires whenever the Busy property changes
private void ftp1_BusyChanged(object sender, System.EventArgs e)
{
   Debug.WriteLine("Busy property changed. Busy now = " + ftp1.Busy);
}

// EndPut event fires when the asynchronous BeginGet completes.
private void ftp1_EndPut(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
   if(e.Exception == null)
      Debug.WriteLine("Put complete");
   else
      Debug.WriteLine("Error: " + e.Exception.Message);
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Certificate Property

Ftp.Certificate Property

The Certificate object representing the certificate to use for optional client-side authentication.

[Visual Basic]
Public Property Certificate As Certificate
[C#]
public Certificate Certificate { get; set; }
[C++]
public: __property Certificate* get_Certificate();
public: __property void set_Certificate(Certificate* );
[JScript]
public function get Certificate() : Certificate
public function set Certificate(Certificate);

Property Value

A Certificate object representing the certificate to use for optional client-side authentication; null otherwise.

Remarks

If a secure server requests a certificate from the client for client-authentication, the value of this property is sent to the server.

Typically this property can either be set before attempting to connect or from within the CertificateRequested event which is raised when the server requests a certificate from the client.

Example

The following example demonstrates assigning a certificate for client certificate authentication.

[Visual Basic]
Private Sub Ftp1_CertificateRequested(ByVal sender As Object, ByVal e As System.EventArgs) Handles Ftp1.CertificateRequested
    'The server has requested a certificate from the client
    'There is a certificate in the CurrentUser/MY store that we want to use
    'Here it is found and the Certificate property is set to it
    Dim store As CertificateStore = New CertificateStore(CertificateStoreLocation.CurrentUser, CertificateStoreName.My)
    Dim c As Certificate
    For Each c In store
        If (c.IssuerName = "PowerTCPTest-CA" And c.IssuedTo = "PowerTCPTest") Then Ftp1.Certificate = c
    Next
End Sub

[C#]
private void ftp1_CertificateRequested(object sender, System.EventArgs e)
{
    //The server has requested a certificate from the client
    //There is a certificate in the CurrentUser/MY store that we want to use
    //Here it is found and the Certificate property is set to it
    CertificateStore store = new CertificateStore(CertificateStoreLocation.CurrentUser, CertificateStoreName.My);
    foreach (Certificate c in store)
    {
        if (c.IssuerName == "PowerTCPTest-CA" && c.IssuedTo == "PowerTCPTest")
            ftp1.Certificate = c;
    }
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Client Property

Ftp.Client Property

Gets or sets the client hostname or address when a specific interface binding is desired.

[Visual Basic]
Public Property Client As String
[C#]
public string Client { get; set; }
[C++]
public: __property String* get_Client();
public: __property void set_Client(String* );
[JScript]
public function get Client() : String
public function set Client(String);

Property Value

A string representing a host name or dot address.

Remarks

If the local host has multiply interfaces, set this property to either a dot address ("111.111.111.111") or a hostname (which is resolved by DNS), specifying the local interface to use.

Normally, the default interface binding is chosen. Use this property to override the default behavior, which is to bind to the first (default) adapter.

Example

The following example demonstrates nonstandard use of the server/client properties.

[Visual Basic]
Ftp1.Server = "MyFTPServer"

' ServerPort defaults to 21, the well-known port for FTP control connection.
' This demonstrates changing the control port to a non-standard port.
Ftp1.ServerPort = 1121

Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set Client property to request a specific interface binding
Ftp1.Client = "111.111.111.111"

' Explicitly set a client control port. (This defaults to 0 - no preference).
Ftp1.ClientPort = 1122

' Set ClientDataPort. The server will attempt to connect to any port in the
' range 5000-5100 and stop attempting upon success.
Ftp1.ClientDataPort = "5000:5100"

' Begin a Put. The Ftp control will (attempt to) make the control connection on port 1121 (the non-standard port
' specified in the code above). When data is ready to be transferred, the data connection will take place on the
' first open port between the range specified (in this case 5000-5100).
Ftp1.Put("myfile.txt", "myfile.txt")

[C#]
ftp1.Server = "MyFTPServer";

// ServerPort defaults to 21, the well-known port for FTP control connection.
// This demonstrates changing the control port to a non-standard port.
ftp1.ServerPort = 1121;

ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set Client property to request a specific interface binding
ftp1.Client = "111.111.111.111";

// Explicitly set a client control port. (This defaults to 0 - no preference).
ftp1.ClientPort = 1122;

// The control will attempt to connect to any port in the
// range 5000-5100 and stop attempting upon success.
ftp1.ClientDataPort = "5000:5100";

// Begin a Put. The Ftp control will (attempt to) make the control connection on port 1121 (the non-standard port
// specified in the code above). When data is ready to be transferred, the data connection will take place on the
// first open port between the range specified (in this case 5000-5100).
ftp1.Put("myfile.txt", "myfile.txt");

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


ClientDataPort Property

Ftp.ClientDataPort Property

Gets or sets a string used to restrict the local data port to a value or range compatible with your firewall.

[Visual Basic]
Public Property ClientDataPort As String
[C#]
public string ClientDataPort { get; set; }
[C++]
public: __property String* get_ClientDataPort();
public: __property void set_ClientDataPort(String* );
[JScript]
public function get ClientDataPort() : String
public function set ClientDataPort(String);

Property Value

A string representing the local port or range of local ports to which the data connection is restricted. A "0" indicates that any port can be used. The default is "0".

Remarks

This property is used to set a range of ports to use for data transfers. This is useful for traversing firewalls where the firewall administrator can configure the firewall to allow these data connections to pass.

RECOMMENDED USE: Set Passive property to true. In this scenario, a single port may be specified (ClientDataPort = "10000"). The server will cycle through available ports, accepting data connections are they are requested by the client.

ALTERNATIVE USE: Set Passive property to false. In this scenario, the server always binds to its port 20, and makes an active connection to the client. If ClientDataPort was set to "10000:10010", then the server will connect to port 10010, then port 10009, etc, as new data connections are established. Once the list of ports is exhaused, however, it is restarted from the beginning (port 10010 in this case). In the event that the first use is still in "TIME_WAIT", then the server will not complete the connection to the client until TIME_WAIT state expires (this may be over a minute on some servers). You can sense this condition by setting the value of the Timeout property to a small number.

Example

The following example demonstrates nonstandard use of the server/client properties.

[Visual Basic]
Ftp1.Server = "MyFTPServer"

' ServerPort defaults to 21, the well-known port for FTP control connection.
' This demonstrates changing the control port to a non-standard port.
Ftp1.ServerPort = 1121

Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set Client property to request a specific interface binding
Ftp1.Client = "111.111.111.111"

' Explicitly set a client control port. (This defaults to 0 - no preference).
Ftp1.ClientPort = 1122

' Set ClientDataPort. The server will attempt to connect to any port in the
' range 5000-5100 and stop attempting upon success.
Ftp1.ClientDataPort = "5000:5100"

' Begin a Put. The Ftp control will (attempt to) make the control connection on port 1121 (the non-standard port
' specified in the code above). When data is ready to be transferred, the data connection will take place on the
' first open port between the range specified (in this case 5000-5100).
Ftp1.Put("myfile.txt", "myfile.txt")

[C#]
ftp1.Server = "MyFTPServer";

// ServerPort defaults to 21, the well-known port for FTP control connection.
// This demonstrates changing the control port to a non-standard port.
ftp1.ServerPort = 1121;

ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set Client property to request a specific interface binding
ftp1.Client = "111.111.111.111";

// Explicitly set a client control port. (This defaults to 0 - no preference).
ftp1.ClientPort = 1122;

// The control will attempt to connect to any port in the
// range 5000-5100 and stop attempting upon success.
ftp1.ClientDataPort = "5000:5100";

// Begin a Put. The Ftp control will (attempt to) make the control connection on port 1121 (the non-standard port
// specified in the code above). When data is ready to be transferred, the data connection will take place on the
// first open port between the range specified (in this case 5000-5100).
ftp1.Put("myfile.txt", "myfile.txt");

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


ClientPort Property

Ftp.ClientPort Property

Gets or sets a string used to restrict the local data port to a value or range of values.

[Visual Basic]
Public Property ClientPort As Integer
[C#]
public int ClientPort { get; set; }
[C++]
public: __property int get_ClientPort();
public: __property void set_ClientPort(int );
[JScript]
public function get ClientPort() : int
public function set ClientPort(int);

Property Value

A string representing the local port or range of local ports to which communication is restricted. A "0" indicates that any port can be used. The default is "0".

Remarks

Set this property if for some reason the client machine is limited in the ports that can be used. This is often the case in intranet environments where client are restricted or behind a firewall for security purposes.

The default value, "0", indicates that any port may be used. When set to a single value, such as "20", only that port is used. When set to a range of values, such as "1024:1028", successive ports in this range are tried until one can be opened.

Example

The following example demonstrates nonstandard use of the server/client properties.

[Visual Basic]
Ftp1.Server = "MyFTPServer"

' ServerPort defaults to 21, the well-known port for FTP control connection.
' This demonstrates changing the control port to a non-standard port.
Ftp1.ServerPort = 1121

Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set Client property to request a specific interface binding
Ftp1.Client = "111.111.111.111"

' Explicitly set a client control port. (This defaults to 0 - no preference).
Ftp1.ClientPort = 1122

' Set ClientDataPort. The server will attempt to connect to any port in the
' range 5000-5100 and stop attempting upon success.
Ftp1.ClientDataPort = "5000:5100"

' Begin a Put. The Ftp control will (attempt to) make the control connection on port 1121 (the non-standard port
' specified in the code above). When data is ready to be transferred, the data connection will take place on the
' first open port between the range specified (in this case 5000-5100).
Ftp1.Put("myfile.txt", "myfile.txt")

[C#]
ftp1.Server = "MyFTPServer";

// ServerPort defaults to 21, the well-known port for FTP control connection.
// This demonstrates changing the control port to a non-standard port.
ftp1.ServerPort = 1121;

ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set Client property to request a specific interface binding
ftp1.Client = "111.111.111.111";

// Explicitly set a client control port. (This defaults to 0 - no preference).
ftp1.ClientPort = 1122;

// The control will attempt to connect to any port in the
// range 5000-5100 and stop attempting upon success.
ftp1.ClientDataPort = "5000:5100";

// Begin a Put. The Ftp control will (attempt to) make the control connection on port 1121 (the non-standard port
// specified in the code above). When data is ready to be transferred, the data connection will take place on the
// first open port between the range specified (in this case 5000-5100).
ftp1.Put("myfile.txt", "myfile.txt");

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Compression Property

Ftp.Compression Property

Gets or sets the type of compression desired.

[Visual Basic]
Public Property Compression As Compression
[C#]
public Compression Compression { get; set; }
[C++]
public: __property Compression get_Compression();
public: __property void set_Compression(Compression );
[JScript]
public function get Compression() : Compression
public function set Compression(Compression);

Property Value

A Dart.PowerTCP.Ftp.Compression value indicating the desired compression. The default is Compression.None.

Remarks

Some servers support 'MODE Z' and will compress/decompress files and listings that are uploaded or downloaded. This is useful when bandwidth is restricted. On a 100 MB LAN, the use of compression results in slower transfers.

Compression.None indicates no compression is used.

Compression.Archive is used for client/side compression/decompression only, resulting in server files that are stored in their compressed state.

Compression.Full is used for client AND server compression/decompression, resulting in server files that are stored in their uncompressed state. If the server does not support 'MODE Z', then this

Compression software is provided by the generosity of ComponentAce:

Copyright (c) 2006-2007, ComponentAce

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Connected Property

Ftp.Connected Property

Gets the connected state of the connection.

[Visual Basic]
Public Property ReadOnly Connected As Boolean
[C#]
public bool Connected { get; }
[C++]
public: __property bool get_Connected();
[JScript]
public function get Connected() : bool

Property Value

true if the TCP connection is connected to a remote resource and authenticated; otherwise, false.

Remarks

If the PowerTCP component is connected to a remote resource AND authenticated, this property returns true. If this property is false, the connection was either never connected, is no longer connected, or is connected but not yet authenticated. When receiving data from the server, this property is a good way to tell if all data has been received. Keep receiving data in a loop until this property equals false.

When using PowerTCP components which make use of the Tcp component as the underlying connection, this property returns the same value as the Object.Connection.Connected property (where Object.Connection exposes the Tcp object used for the connection).

The Object.ConnectedChanged and Object.ConnectedChangedEx events are raised whenever this property changes.

Example

The following example demonstrates accessing the exposed TCP connection.

[Visual Basic]
Private Sub DisplayConnectionInfo()
   ' Check current connection state. If connected display info about the connection.
   If Ftp1.Connected Then
      label1.Text = "Connected to " + Ftp1.Connection.RemoteEndPoint.Address.ToString()
   Else
      label1.Text = "Not Connected"
   End If
End Sub

[C#]
private void DisplayConnectionInfo()
{
   // Check current connection state. If connected display info about the connection.
   if(ftp1.Connected)
      label1.Text = "Connected to " + ftp1.Connection.RemoteEndPoint.Address.ToString();
   else
      label1.Text = "Not connected";
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Connection Property

Ftp.Connection Property

Gets the Tcp component instance used for the connection.

[Visual Basic]
Public Property ReadOnly Connection As Tcp
[C#]
public Tcp Connection { get; }
[C++]
public: __property Tcp* get_Connection();
[JScript]
public function get Connection() : Tcp

Property Value

The Tcp instance that the PowerTCP component uses for the connection.

Remarks

Many PowerTCP components use the Tcp component for the connection. This property exposes that object, allowing such actions as sending server requests directly over the TCP connection or getting information about the socket (such as local/remote IP addresses). If you need to communicate with a proxy server, set the properties of Object.Connection.Proxy to enable proxy communication. In addition, Object.Connection.Send can be used to send any command to the server.

Use the Object.Connection property to directly access the TCP connection. This could be useful if:

  • You need to use the Proxy object to communicate with proxy servers.
  • You wish to display information about the socket endpoints to the user (local/remote IP addresses, for example).
  • You want to use the Tcp object used by the PowerTCP component as an initializer for the TraceForm.
  • You wish to capture trace information by using the Trace event.
  • You wish to close the connection.

Example

The following example demonstrates accessing the exposed TCP connection.

[Visual Basic]
Private Sub DisplayConnectionInfo()
   ' Check current connection state. If connected display info about the connection.
   If Ftp1.Connected Then
      label1.Text = "Connected to " + Ftp1.Connection.RemoteEndPoint.Address.ToString()
   Else
      label1.Text = "Not Connected"
   End If
End Sub

[C#]
private void DisplayConnectionInfo()
{
   // Check current connection state. If connected display info about the connection.
   if(ftp1.Connected)
      label1.Text = "Connected to " + ftp1.Connection.RemoteEndPoint.Address.ToString();
   else
      label1.Text = "Not connected";
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


DoEvents Property

Ftp.DoEvents Property

Gets or sets a value that controls the processing of events during blocking method calls.

[Visual Basic]
Public Property DoEvents As Boolean
[C#]
public bool DoEvents { get; set; }
[C++]
public: __property bool get_DoEvents();
public: __property void set_DoEvents(bool );
[JScript]
public function get DoEvents() : bool
public function set DoEvents(bool);

Property Value

true if user-interface events should be processed during synchronous method calls; otherwise, false. The default value is true.

Remarks

When performing a synchronous (blocking) method, PowerTCP will process user-interface events (such as window painting) if this property is set to true AND the current thread has an event message queue. If no message queue is present (such as on an ASP page or under any worker thread), the value of this property has no effect. This property is used only for synchronous methods. Object.DoEvents is not needed if using asynchronous methods because the asynchronous method will execute on a different thread, allowing the UI thread to continue working unblocked.

For example, this property is beneficial when an interactive application is being used and the user may want to abort a currently processing operation by clicking an "Abort" button. If Object.DoEvents is set to false, this will not be possible. Set the Object.DoEvents property to true and the application will respond to other events (such as button clicks) during synchronous operations.

Example

The following example demonstrates

[Visual Basic]
Private Sub ButtonPutFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    ' Set server and user properties. This will allow calling of other
    ' Ftp Component methods with the log in/log out taking place "behind the scenes"
    Ftp1.Server = "MyFTPServer"
    Ftp1.Username = "blah"
    Ftp1.Password = "MyPass"

    ' Make sure DoEvents is true so UI events will be processed.
    Ftp1.DoEvents = True

    ' Put method returns an FtpFile object
    Dim file As Dart.PowerTCP.Ftp.FtpFile

    ' File is an image
    Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

    Try

       ' Begin a transfer, the user can click a button which calls Ftp.AbortTransfer.
       ' If this happens, the transfer should stop and return an FtpFile object.
       file = Ftp1.Put("C:\Test\Test.bmp", "Test.bmp")
    Catch ex As Exception
        Debug.WriteLine("Error: " + ex.Message)
        Exit Sub
    End Try

    ' Success, the file was either successfully transferred, or the transfer
    ' was successfully aborted. Find out which occurred.
    If file.Position = file.Length Then
       ' Transfer not aborted.
       Debug.WriteLine("File successfully transferred.")
       Debug.WriteLine("Name of file on server: " + file.RemoteFileName)
    Else
       ' Transfer was aborted
       Debug.WriteLine("File transfer aborted")
       Debug.WriteLine("Bytes transferred: " + file.Count)
    End If
End Sub

Private Sub ButtonAbortTransfer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
   Ftp1.AbortTransfer()
End Sub

[C#]
private void buttonPutFile_Click(object sender, System.EventArgs e)
{
    // Set server and user properties. This will allow calling of other
    // Ftp Component methods with the log in/log out taking place "behind the scenes"
    ftp1.Server = "MyFTPServer";
    ftp1.Username = "blah";
    ftp1.Password = "MyPass";

    // Make sure DoEvents is true so UI events will be processed.
    ftp1.DoEvents = true;

    // Put method returns an FtpFile object
    Dart.PowerTCP.Ftp.FtpFile file;

    // File is an image
    ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

    // Begin a transfer, the user can click a button which calls Ftp.AbortTransfer.
    // If this happens, the transfer should stop and return an FtpFile object.
    try
    {
       file = ftp1.Put("C:\\Test\\test.bmp", "test.bmp");
    }
    catch(Exception ex)
    {
       Debug.WriteLine("Error: " + ex.Message);
       return;
    }

    // Success, the file was either successfully transferred, or the transfer
    // was successfully aborted. Find out which occurred.
    if(file.Position == file.Length)
    {
       // Transfer not aborted.
       Debug.WriteLine("File successfully transferred.");
       Debug.WriteLine("Name of file on server: " + file.RemoteFileName);
    }
    else
    {
       // Transfer was aborted
       Debug.WriteLine("File transfer aborted");
       Debug.WriteLine("Bytes transferred: " + file.Count);
    }

}

private void buttonAbort_Click(object sender, System.EventArgs e)
{
    // If DoEvents is true, this button we be able to be clicked, aborting the transfer
    ftp1.AbortTransfer();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Editor Property

Ftp.Editor Property

In Visual Studio.NET, displays an interactive form to use to test real time protocol operations.

[Visual Basic]
Public Property Editor As Object
[C#]
public object Editor { get; set; }
[C++]
public: __property Object* get_Editor();
public: __property void set_Editor(Object* );
[JScript]
public function get Editor() : Object
public function set Editor(Object);

Property Value

An EditorForm to use in VS.NET to test protocol operations.

Remarks

This property can only be used by clicking this property in the Properties Window in Visual Studio.NET. This will open an application which can be used to test protocol operation. The EditorForm will not be available if the PowerTCP component is being used as a reference.

The Object.Editor property can ONLY be used at design time in the Visual Studio.NET environment.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


FileType Property

Ftp.FileType Property

Gets or sets the data type for subsequent transfers.

[Visual Basic]
Public Property FileType As FileType
[C#]
public FileType FileType { get; set; }
[C++]
public: __property FileType get_FileType();
public: __property void set_FileType(FileType );
[JScript]
public function get FileType() : FileType
public function set FileType(FileType);

Property Value

One of the FileType values. The default value is FileType.Ascii.

Remarks

Sending an ASCII file as Image or an binary file as ASCII can alter the formatting of the file. Set FileType to FileType.Ascii if you are transferring files made entirely of ASCII characters (usually text files)and set FileType to FileType.Image to transfer binary files without changing the formatting of the file.

The TYPE command is automatically sent with the value of this property before any file transfer takes place.

When set to FileType.Ascii, a CR/LF pair should be put at the end of every line in the file before sending it. Since the Windows operating system already uses a CR/LF pair as the native line separator, there is no need to modify the stream as it is received or sent. Another operating system that uses a single CR as the native line separator, however, must expand the size of most files it sends, and shrink the size of most files it receives (to change the line separator to/from a CR/LF pair).

When set to FileType.Image, the line separator remains unmodified, making this property setting necessary for sending and receiving binary files (that may contain line separators).

Example

The following example demonstrates checking to see the type of file (by looking at the bytes) and setting the FileType accordingly.

[Visual Basic]
' This method demonstrates checking the bytes of a file to determine if
' it is binary or ASCII, then FTPing accordingly

' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FilePath As String = "C:\FtpTest\log.txt"

' Create new filestream
Dim fstream As New System.IO.FileStream(FilePath, IO.FileMode.Open)

' Create new byte array to hold the FileStream's data
Dim data(fstream.Length) As Byte

' Read data from the file into the buffer.
fstream.Read(data, 0, fstream.Length)
fstream.Close()

Dim binary As Boolean = False

' Iterate through the bytes, checking to see if any are above 128. If so it is
' binary. (This is not a 100% accurate way of checking a file because the file
' may be a binary file whose bytes all happen to be below 128.)

Dim i As Integer
For i = 0 To data.Length - 1
   If data(i) > 128 Then
      binary = True
   End If
Next

' Set the file type
If binary Then
   Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image
Else
   Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Ascii
End If

' Put the file (The FileInfo object parses the name from the path)
Ftp1.Put(FilePath, New System.IO.FileInfo(FilePath).Name)

[C#]
// This method demonstrates checking the bytes of a file to determine if
// it is binary or ASCII, then FTPing accordingly

// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FilePath = "C:\\Files\\binaryfile.exe";

// Create new filestream
System.IO.FileStream fstream = new System.IO.FileStream(FilePath, System.IO.FileMode.Open);

// Create new byte array to hold the FileStream's data
byte[] data = new byte[fstream.Length];

// Read data from the file into the buffer.
fstream.Read(data, 0, (int)fstream.Length);
fstream.Close();

bool binary = false;

// Iterate through the bytes, checking to see if any are above 128. If so it is
// binary. (This is not a 100% accurate way of checking a file because the file
// may be a binary file whose bytes all happen to be below 128.)
for(int i = 0; i < data.Length; i++)
    if(data[i] > 128)
        binary = true;

// Set the file type
if(binary)
    ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;
else
    ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Ascii;

// Put the file (The FileInfo object parses the name from the path)
ftp1.Put(FilePath,  new System.IO.FileInfo(FilePath).Name);

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


MaxTransferRate Property

Ftp.MaxTransferRate Property

Gets or sets the maximum transfer rate of the Ftp component in bytes per second.

[Visual Basic]
Public Property MaxTransferRate As Integer
[C#]
public int MaxTransferRate { get; set; }
[C++]
public: __property int get_MaxTransferRate();
public: __property void set_MaxTransferRate(int );
[JScript]
public function get MaxTransferRate() : int
public function set MaxTransferRate(int);

Property Value

An integer value indicating the desired speed of transfer in bytes per second. The default is 0.

Remarks

A value of 0 indicates that all available bandwidth will be used.

The MaxTransferRate property is used to throttle the speed of data transfer and can be changed during a transfer. By default the component will utilize all available bandwidth.

Example

The following example demonstrates capturing file transfer progress info.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFtpServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
Ftp1.BlockSize = 1024

' Set the MaxTransfer Rate to 5 kbps
Ftp1.MaxTransferRate = 5

' Attempt to put multiple files to the server
Try
   Ftp1.Put("C:\Test", "*", "", True)
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Complete!")

' Monitor the progress using the progress event.
Private Sub Ftp1_Progress(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ProgressEventArgs) Handles Ftp1.Progress
   ' Display the currently transferring file
   Label1.Text = "Currently transferring " + e.FileName

   ' Display the total bytes transferred
   Label2.Text = "Total bytes transferred: " + e.Count

   ' Display the current transfer rate
   Label3.Text = "Transfer Rate: " + e.TransferRate

   ' Set the properties of ProgressBar1 (this ProgressBar displays progress
   ' for each individual file)
   ProgressBar1.Minimum = 0
   ProgressBar1.Maximum = e.Length
   ProgressBar1.Value = e.Position

   ' Set the properties of progressBar2 (this ProgressBar displays progress
   ' for all files, useful when transferring multiple files - MPUT).
   ProgressBar2.Minimum = 0
   ProgressBar2.Maximum = e.TotalFiles
   ProgressBar2.Value = e.CurrentFile
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
ftp1.BlockSize = 1024;

// Set the MaxTransferRate to 5 kbps
ftp1.MaxTransferRate = 5;

// Attempt to put multiple files to the server
try
{
   ftp1.Put("C:\\Test", "*", "", true);
}
catch(Exception ex)
{
   Debug.WriteLine("Error: " + ex.Message);
   return;
}

// Success
Debug.WriteLine("Complete!");

// Monitor the progress using the progress event.
private void ftp1_Progress(object sender, Dart.PowerTCP.Ftp.ProgressEventArgs e)
{
   // Display the currently transferring file
   label1.Text = "Currently transferring " + e.FileName;

   // Display the total bytes transferred
   label2.Text = "Total bytes transferred: " + e.Count;

   // Display the current transfer rate
   label3.Text = "Transfer Rate: " + e.TransferRate;

   // Set the properties of progressBar1 (this ProgressBar displays progress
   // for each individual file)
   progressBar1.Minimum = 0;
   progressBar1.Maximum = (int)e.Length;
   progressBar1.Value = (int)e.Position;

   // Set the properties of progressBar2 (this ProgressBar displays progress
   // for all files, useful when transferring multiple files - MPUT).
   progressBar2.Minimum = 0;
   progressBar2.Maximum = (int)e.TotalFiles;
   progressBar2.Value = (int)e.CurrentFile;
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Passive Property

Ftp.Passive Property

Gets or sets a value that determines if the server should accept a passive data connection.

[Visual Basic]
Public Property Passive As Boolean
[C#]
public bool Passive { get; set; }
[C++]
public: __property bool get_Passive();
public: __property void set_Passive(bool );
[JScript]
public function get Passive() : bool
public function set Passive(bool);

Property Value

true if the data connection should be passive; otherwise, false. The default value is true.

Remarks

When true, a PASV command is sent before a data transfer and the client connects to the server. When false, a PORT command is sent before a data transfer and the server connects to the client.

Set the Passive property to true to make your application firewall friendly since firewalls often restrict incoming connections, while allowing outgoing connections.

Example

The following example demonstrates simple use of the Passive property in storing a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Specify a non-passive connection. The server will connect to the client
' for any data connections.
Ftp1.Passive = false

Dim FileToStore As String = "c:\FtpTest\mynewfile.bmp"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file transfer
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to store file " + FileToStore)

Try
   ' Attempt to store the file (The FileInfo object parses the filename from the path)
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Specify a non-passive connection. The server will connect to the client
// for any data connections.
ftp1.Passive = false;

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

// Put method returns an FtpFile object containing information about the file transfer
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

try
{
    // Attempt to store the file (The FileInfo object parses the filename from the path)
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Password Property

Ftp.Password Property

Gets or sets the password used during session login.

[Visual Basic]
Public Property Password As String
[C#]
public string Password { get; set; }
[C++]
public: __property String* get_Password();
public: __property void set_Password(String* );
[JScript]
public function get Password() : String
public function set Password(String);

Property Value

A string value representing the password to be issued during session login.

Remarks

The value of this property is automatically sent (with the PASS command) when the server requests password information, which normally occurs after the username is sent. When "anonymous" is used for Username, this value is normally your email address.

The Ftp component was designed to automatically log in to the server when any communication with the server needs to take place. In order for this to occur the Username, Password, and Server properties all have to be set to valid values. Once this has been done, the user will be automatically logged in transparently whenever communication with the server needs to occur. If either the Server, ServerPort, Username, or Password properties change, this will automatically be detected and login will automatically occur using the new data specified. It is recommended to use this method of logging into an FTP server over using the RawConnect method, which is reserved for special connection cases not defined in the FTP RFC.

For more information about logging in and out, see the topic Session Management Overview.

You must set the Password property if you wish to connect to any server that requires authentication. If your application requires authentication communication that is NOT defined in the RFC spec, use the RawConnect method to connect to the server, then use the Invoke or BeginInvoke methods to send your login information.

Example

The following example demonstrates simple use of the client/server properties in storing a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToStore As String = "c:\FtpTest\mynewfile.bmp"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file transfer
Dim file As Dart.PowerTCP.Ftp.FtpFile
Debug.WriteLine("Attempting to store file " + FileToStore)

Try
   ' Attempt to store the file (The FileInfo object parses the filename from the path)
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

// Put method returns an FtpFile object containing information about the file transfer
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

try
{
    // Attempt to store the file (The FileInfo object parses the filename from the path)
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


ProgressSize Property

Ftp.ProgressSize Property

Gets or sets a value that controls the frequency for raising the Progress event.

[Visual Basic]
Public Property ProgressSize As Integer
[C#]
public int ProgressSize { get; set; }
[C++]
public: __property int get_ProgressSize();
public: __property void set_ProgressSize(int );
[JScript]
public function get ProgressSize() : int
public function set ProgressSize(int);

Property Value

An integer value representing the password to be issued during session login.

Remarks

When using blocking programming techniques (i.e. using Put, Get, etc) this property controls the amount of time-slices given to the UI thread. A lower value will provide finer granularity for a progress bar, but may saturate the UI thread when larger files are transferred. A larger value will provide fewer Progress events, depending on the needs of the application.

Note, when using blocking techniques, it is possible for some messages on the UI thread to not be processed properly. This will cause such behavior as button clicks not registering, minimized windows not being able to be restored, etc. To eliminate any such behavior, use non-blocking techniques (i.e. use BeginPut, BeginGet, etc).

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Proxy Property

Ftp.Proxy Property

Returns the FtpProxy instance that controls proxy server use.

[Visual Basic]
Public Property ReadOnly Proxy As FtpProxy
[C#]
public FtpProxy Proxy { get; }
[C++]
public: __property FtpProxy* get_Proxy();
[JScript]
public function get Proxy() : FtpProxy

Property Value

The FtpProxy object to use to control proxy server use.

Remarks

Some networks are configured to require your use of an FTP proxy server. PowerTCP supports most types. Configure your proxy use by specifying the properties of this FtpProxy object.

If any communication needs to occur outside of the proxies defined in the FtpProxy object (for example, perhaps you need to connect to a server that expects a proprietary command for successfully login) use the RawConnect method, which receives the greeting from the server. The Invoke or BeginInvoke methods can then be used to sent any command (including the proprietary command) to the server.

Use the Proxy property if your application needs to connect with one of the following proxies:

  • SOCKS v4
  • SOCKS v5
  • SITE hostname
  • USER after logon
  • USER with no logon
  • OPEN Proxy
  • PIPE Proxy

Example

The following example demonstrates basic proxy use.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in/log out taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set Proxy properties and all proxy issues will be handled "behind the scenes"
Ftp1.Proxy.Server = "MyProxy"
Ftp1.Proxy.ServerPort = 8888
Ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.Socks5
Ftp1.Proxy.Username = "proxyblah"
Ftp1.Proxy.Password = "myproxypass"

Dim FileToStore As String = "c:\FtpTest\mypic.gif"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to store file " + FileToStore)

' Store the file
Try
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set Proxy properties and all proxy issues will be handled "behind the scenes"
ftp1.Proxy.Server = "MyProxy";
ftp1.Proxy.ServerPort = 8888;
ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.User;
ftp1.Proxy.Username = "proxyblah";
ftp1.Proxy.Password = "myproxypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

// Put method returns an FtpFile object containing information about the file
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

// Store the file
try
{
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Restart Property

Ftp.Restart Property

Gets or sets a value that controls the automatic use of file transfer restarts.

[Visual Basic]
Public Property Restart As Boolean
[C#]
public bool Restart { get; set; }
[C++]
public: __property bool get_Restart();
public: __property void set_Restart(bool );
[JScript]
public function get Restart() : bool
public function set Restart(bool);

Property Value

true if file transfer restart should be automatically used; otherwise, false. The default value is false.

Remarks

When set to false, file transfers always transfer the entire file. If you wish to resume a previously incomplete transfer, set this property to true and the local and remote file sizes will be compared. If a partial file is seen, then the REST (restart) command is used to preserve that portion of the file that was previously transferred. If a partial file was transferred, Count (the number of bytes transferred) will not equal Length.

If the server does not support restarts, this value will be ignored and the entire file will be transferred.

If Compression is set to Compression.Archive and you attempt to set this property to true an InvalidOperationException will be raised.

Example

The following example demonstrates using the Restart property to specify whether a file transfer should be restarted if possible.

[Visual Basic]
' Set server and user properties. This will allow us to call other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Storing a binary file
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Specify a restart
Ftp1.Restart = true

' Put returns an FtpFile object
Dart.PowerTCP.Ftp.FtpFile File

' Put the file, if it partially exists on the server AND the server
' supports restarts, it will automatically be restarted
File = Ftp1.Put("C:\Test\Test.bmp", "Test.Bmp")

' Display. If the file transfer was restarted Length will not Equal count. If the
' file transfer was restarted, Length and Count will be equal
Debug.WriteLine("Length of the file: " + File.Length)
Debug.WriteLine("Bytes transferred: " + File.Count)

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypaass";

// Storing a binary file
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

// Specify a restart
ftp1.Restart = true;

// Put returns an FtpFile object
Dart.PowerTCP.Ftp.FtpFile File;

// Put the file, if it partially exists on the server AND the server
// supports restarts, it will automatically be restarted
File = ftp1.Put("C:\\Test\\Test.bmp", "Test.Bmp");

// Display. If the file transfer was restarted Length will not Equal count. If the
// file transfer was restarted, Length and Count will be equal
Debug.WriteLine("Length of the file: " + File.Length);
Debug.WriteLine("Bytes transferred: " + File.Count);

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Security Property

Ftp.Security Property

Specifies the security protocol and authentication type used.

[Visual Basic]
Public Property Security As Security
[C#]
public Security Security { get; set; }
[C++]
public: __property Security get_Security();
public: __property void set_Security(Security );
[JScript]
public function get Security() : Security
public function set Security(Security);

Property Value

One of the Security values. The default type is Security.None.

Remarks

Set this value to the type of security protocol and authentication type used by the server. For example, if explicit SSL is used, set this property to Security.Explicit and connect to the secure server. Typically when using explicit security, you will connect to the well-known port for the protocol you are using. If implicit SSL is used, set this property to Security.Implicit and connect to the secure server. Typically, when using implicit security, you will connect to a port other than the well-known port for the protocol you are using. in this case.

For more information about implicit and explicit SSL, see the topic Explicit vs Implicit Security.

Example

The following example demonstrates receiving a remote certificate.

[Visual Basic]
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Use Implicit Secure FTP
        Ftp1.Security = Security.Implicit

        'Do not ignore problems with remote certificates
        Ftp1.UseAuthentication = True

        'Login and get working directory
        Ftp1.Server = "myServer"
        Ftp1.Username = "myUser"
        Ftp1.Password = "myPassword"
        Ftp1.Invoke(FtpCommand.PrintDir)
    End Sub

    Private Sub Ftp1_CertificateReceived(ByVal sender As Object, ByVal e As CertificateReceivedEventArgs) Handles Ftp1.CertificateReceived
        'Fires during SSL handshake when server presents its certificate
        Dim msg As String = "The server could not be validated for the following reason(s):"
        e.Accept = True

        'Security checks
        If (Not e.TrustedRoot) Then
            msg = msg + vbCrLf + "    -The certificate CA was not trusted"
            e.Accept = False
        End If
        If (Not e.ValidName) Then
            msg = msg + vbCrLf + "    -The certificate name was invalid"
            e.Accept = False
        End If
        If (Not e.ValidDate) Then
            msg = msg + vbCrLf + "   -The certificate date was invalid"
            e.Accept = False
        End If

        'If Validation failed, show message to user
        If (e.Accept = False) Then
            msg = msg + vbCrLf + vbCrLf + "Do you wish to override the security check?"
            If (MessageBox.Show(msg, "Security Alert: Server could not be validated", _
             MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = DialogResult.Yes) Then e.Accept = True
        End If
    End Sub

[C#]
private void button1_Click(object sender, System.EventArgs e)
{
    //Use Implicit Secure FTP
    ftp1.Security = Security.Implicit;

    //Do not ignore problems with remote certificates
    ftp1.UseAuthentication = true;

    //Login and get working directory
    ftp1.Server = "myServer";
    ftp1.Username = "myUser";
    ftp1.Password = "myPassword";
    ftp1.Invoke(FtpCommand.PrintDir);
}

private void ftp1_CertificateReceived(object sender, CertificateReceivedEventArgs e)
{
    //Fires during SSL handshake when server presents its certificate
    string msg = "The server could not be validated for the following reason(s):";
    e.Accept = true;

    //Security checks
    if (!e.TrustedRoot)
    {
        msg = msg + "\r\n    -The certificate CA was not trusted";
        e.Accept = false;
    }
    if (!e.ValidName)
    {
        msg = msg + "\r\n    -The certificate name was invalid";
        e.Accept = false;
    }
    if (!e.ValidDate)
    {
        msg = msg + "\r\n    -The certificate date was invalid";
        e.Accept = false;
    }

    //If Validation failed, show message to user
    if (e.Accept == false)
    {
        msg = msg + "\r\n\r\nDo you wish to override the security check?";
        if (MessageBox.Show(msg, "Security Alert: Server could not be validated",
            MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            e.Accept = true;
    }
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Server Property

Ftp.Server Property

Gets or sets the FTP server hostname or address.

[Visual Basic]
Public Property Server As String
[C#]
public string Server { get; set; }
[C++]
public: __property String* get_Server();
public: __property void set_Server(String* );
[JScript]
public function get Server() : String
public function set Server(String);

Property Value

A string value representing the FTP resource to connect to.

Remarks

Used to identify the FTP resource by either hostname (that is resolved by DNS) or dot address (of the form 11.22.33.44). The object always checks this property, so you can change it at any time and subsequent sessions will be automatically established with the correct server.

The Ftp objects were designed to automatically log in to the server when any communication with the server needs to take place. In order for this to occur the Username, Password, and Server properties all have to be set to valid values. Once this has been done, the user will be automatically logged in transparently. If either the Server, ServerPort, Username, or Password properties change, this will automatically be detected and login will automatically occur using the new data specified. It is recommended to use this method of logging into an FTP server over using the RawConnect method, which is reserved for special connection cases not defined in the FTP RFC.

You must set the Server property before proper use. The only exception to this is in the rare case where a connection is required to an FTP server that is operating outside of the RFC spec. In this situation, use the RawConnect method to specify a server to connect to and the Invoke or BeginInvoke methods to send the required commands.

Example

The following example demonstrates simple use of the client/server properties in storing a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToStore As String = "c:\FtpTest\mynewfile.bmp"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file transfer
Dim file As Dart.PowerTCP.Ftp.FtpFile
Debug.WriteLine("Attempting to store file " + FileToStore)

Try
   ' Attempt to store the file (The FileInfo object parses the filename from the path)
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

// Put method returns an FtpFile object containing information about the file transfer
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

try
{
    // Attempt to store the file (The FileInfo object parses the filename from the path)
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


ServerPort Property

Ftp.ServerPort Property

Gets or sets the FTP server port.

[Visual Basic]
Public Property ServerPort As Integer
[C#]
public int ServerPort { get; set; }
[C++]
public: __property int get_ServerPort();
public: __property void set_ServerPort(int );
[JScript]
public function get ServerPort() : int
public function set ServerPort(int);

Property Value

An integer value representing the port of the FTP resource to connect to. Defaults to 21.

Remarks

Used to identify the FTP resource port, which is the "well-known" port 21 by convention. The object always checks this property, so you can change it at any time and subsequent sessions will be automatically established with the correct port.

If either the Server, ServerPort, Username, or Password properties change, this will automatically be detected and login will automatically occur using the new data specified.

Most FTP servers operate at the well known port of "21". However, often a FTP server is forced to operate at a non-standard port. In these cases, set the ServerPort property to the non-standard port.

Example

The following example demonstrates nonstandard use of the server/client properties.

[Visual Basic]
Ftp1.Server = "MyFTPServer"

' ServerPort defaults to 21, the well-known port for FTP control connection.
' This demonstrates changing the control port to a non-standard port.
Ftp1.ServerPort = 1121

Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set Client property to request a specific interface binding
Ftp1.Client = "111.111.111.111"

' Explicitly set a client control port. (This defaults to 0 - no preference).
Ftp1.ClientPort = 1122

' Set ClientDataPort. The server will attempt to connect to any port in the
' range 5000-5100 and stop attempting upon success.
Ftp1.ClientDataPort = "5000:5100"

' Begin a Put. The Ftp control will (attempt to) make the control connection on port 1121 (the non-standard port
' specified in the code above). When data is ready to be transferred, the data connection will take place on the
' first open port between the range specified (in this case 5000-5100).
Ftp1.Put("myfile.txt", "myfile.txt")

[C#]
ftp1.Server = "MyFTPServer";

// ServerPort defaults to 21, the well-known port for FTP control connection.
// This demonstrates changing the control port to a non-standard port.
ftp1.ServerPort = 1121;

ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set Client property to request a specific interface binding
ftp1.Client = "111.111.111.111";

// Explicitly set a client control port. (This defaults to 0 - no preference).
ftp1.ClientPort = 1122;

// The control will attempt to connect to any port in the
// range 5000-5100 and stop attempting upon success.
ftp1.ClientDataPort = "5000:5100";

// Begin a Put. The Ftp control will (attempt to) make the control connection on port 1121 (the non-standard port
// specified in the code above). When data is ready to be transferred, the data connection will take place on the
// first open port between the range specified (in this case 5000-5100).
ftp1.Put("myfile.txt", "myfile.txt");

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


StoreType Property

Ftp.StoreType Property

Gets or sets the type of store to use when the Put method or BeginPut method is called.

[Visual Basic]
Public Property StoreType As StoreType
[C#]
public StoreType StoreType { get; set; }
[C++]
public: __property StoreType get_StoreType();
public: __property void set_StoreType(StoreType );
[JScript]
public function get StoreType() : StoreType
public function set StoreType(StoreType);

Property Value

One of the StoreType values. The default value is StoreType.Replace.

Remarks

The default value (StoreType.Replace) is used by most applications, and is required for file transfer restarts. Use StoreType.Unique for storing files under unique names, and StoreType.Append for appending information.

When using StoreType.Unique, the name of the file will be returned in the reply. When using StoreType.Append, if the file does not exist on the server, it will simply be created.

Changing the StoreType property is useful in several scenarios, for example:

  • If your server does not support restarts, and you wish to simulate a restart, you can use StoreType.Append for adding the missing portion of any file.
  • StoreType.Replace can be used along with MPUT to synchronize folders on a local root with a remote root.
  • StoreType.Unique may be helpful for archival purposes.

Example

The following example demonstrates file synchronization between a local root and a remote root. First, filenames from both the local root and remote root are retrieved using ExpandLocalFiles and ExpandRemoteFiles. Then extraneous files are deleted from the server. Then StoreType is set to Replace to assure that the files on the client will replace those on the server. Finally all files on the local root are put to the server.

[Visual Basic]
Private Sub SynchronizeFiles(ByVal LocalRoot As String, ByVal RemoteRoot As String)

' This sub demonstrates synchronization of files between a local root
' and a root on the FTP server, to get all files on the FTP Server to
' be the same as on the local root

' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Get listing of local files
Dim lFiles() As String
lFiles = Ftp1.ExpandLocalFiles(LocalRoot + "*", False)

' Get a listing of remote files
Dim rFiles() As String
rFiles = Ftp1.ExpandRemoteFiles(RemoteRoot + "*", False)

Dim found As Boolean
Dim i As Integer

' Iterate though list of files on the server and compare to local files.
' If it does not exist locally, delete it
For i = 0 To rFiles.Length - 1

   found = False
   Dim j As Integer

   For j = 0 To lFiles.Length - 1

      ' Create FileInfo objects to parse filename
      Dim rFileInfo As New System.IO.FileInfo(rFiles(i))
      Dim lFileInfo As New System.IO.FileInfo(lFiles(i))

      ' Compare file names
      If (rFileInfo.Name = lFileInfo.Name) Then
         found = True
         Exit For
      End If
   Next

   If Not found Then
      Debug.WriteLine("Deleting " + rFiles(i) + " from server")
      Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Delete, rFiles(i))
   End If
Next

' Now MPUT all files in LocalRoot and both directories are synched

' First, make sure old files are replaced
Ftp1.StoreType = Dart.PowerTCP.Ftp.StoreType.Replace

' Then MPUT
Debug.WriteLine("Uploading all files")
Ftp1.Put(LocalRoot, "*", RemoteRoot, False)
Debug.WriteLine(LocalRoot + " and " + RemoteRoot + " are synched")

' Close the connection
Ftp1.Close()

End Sub

[C#]
private void SynchronizeFiles(string LocalRoot, string RemoteRoot)
{
    // This sub demonstrates synchronization of files between a local root
    // and a root on the FTP server, to get all files on the FTP Server to
    // be the same as on the local root

    // Set server and user properties. This will allow calling of other
    // Ftp Component methods with the log in taking place "behind the scenes"
    ftp1.Server = "MyFTPServer";
    ftp1.Username = "blah";
    ftp1.Password = "mypass";

    // Get list of local files
    string[] lfiles = ftp1.ExpandLocalFiles(LocalRoot + "*", false);

    // Get list of remote files
    string[] rfiles = ftp1.ExpandRemoteFiles(RemoteRoot + "*", false);

    bool found;

    // Iterate though list of files on the server and compare to local files.
    // If it does not exist locally, delete it
    for(int i = 0; i < lfiles.Length; i++)
    {
        found = false;
        for(int j = 0; j < lfiles.Length; j++)
        {
            // Compare filenames
            if(new System.IO.FileInfo(rfiles[i]).Name == new System.IO.FileInfo(lfiles[j]).Name)
            {
                found = true;
                break;
            }
        }

        if(!found) // Delete the file from the server.
        {
            Debug.WriteLine("Deleting " + rfiles[i] + " from server");
            ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Delete, rfiles[i]);
        }
    }

    // Now just MPUT all files in the local root and everything is synched.

    // First, make sure old files are replaced
    ftp1.StoreType = Dart.PowerTCP.Ftp.StoreType.Replace;

    // Then MPUT
    Debug.WriteLine("Uploading all files");
    ftp1.Put(LocalRoot, "*", RemoteRoot, false);
    Debug.WriteLine(LocalRoot + " and " + RemoteRoot + " are synched.");

    // Close connection
    ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


SynchronizingObject Property

Ftp.SynchronizingObject Property

Set this object to automatically control thread marshalling between worker threads and the main UI thread.

[Visual Basic]
Public Property SynchronizingObject As ISynchronizeInvoke
[C#]
public ISynchronizeInvoke SynchronizingObject { get; set; }
[C++]
public: __property ISynchronizeInvoke* get_SynchronizingObject();
public: __property void set_SynchronizingObject(ISynchronizeInvoke* );
[JScript]
public function get SynchronizingObject() : ISynchronizeInvoke
public function set SynchronizingObject(ISynchronizeInvoke);

Property Value

If used, the main UI thread object; null if unused.

Remarks

Any application that (1) uses multithreading (for example, an application which uses an asynchronous BeginXXX method) and (2) must update a shared UI element on the main UI thread (such as a ListView object) from one of these worker threads must set this property to the value of the main UI thread object. If the application meets both of these requirements and this property is NOT set, you may see strange behavior in your application (such as strange exceptions or improper UI element values).

If you do not know whether or not you need to use this property, simply take the failsafe approach when programming Windows applications and always set this property to the Main Form object. If any thread marshalling has to occur between a worker thread and the UI thread, it will occur automatically.

Provides data for the CollectionChanged event. NOTE for server implementations: If you are using a PowerTCP server component to build a server application, you do not want to set this property (as it will cause the server application to become single-threaded). Instead, you want to use the Control.BeginInvoke method to thread-marshall to the main UI thread (see any of the installed sample server applications for an example of this).

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Timeout Property

Ftp.Timeout Property

Specifies the maximum number of milliseconds to wait for responses to commands or time between data buffer transfers.

[Visual Basic]
Public Property Timeout As Integer
[C#]
public int Timeout { get; set; }
[C++]
public: __property int get_Timeout();
public: __property void set_Timeout(int );
[JScript]
public function get Timeout() : int
public function set Timeout(int);

Property Value

An integer specifying the maximum number of milliseconds to wait for responses to commands.

Remarks

After connecting to a server, this value is used to establish the period of time to wait for server responses. During data transfer operations, a SocketException will be thrown if any data buffer transfer operation does not complete within the timeout period.

Example

The following example demonstrates setting the Timeout property to detect when file transfer fails (for example, if the network connection is terminated).

[Visual Basic]
' Set timeout to 5 seconds
Ftp1.Timeout = 5000

Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Try
   ' When retrieving the file, if no response is received within 5 seconds
   ' a SocketException will be thrown
   Ftp1.Get("thefile.txt", "thefile.txt")
Catch ex as System.Net.Sockets.SocketException
   Debug.WriteLine("A socket exception has occurred: " + ex.Message)
   Return
Catch ex as Exception
   Debug.WriteLine("An exception occurred: " + ex.Message)
   Return
End Try

Debug.WriteLine("File successfully retrieved")

' Close the connection
Ftp1.Close()

[C#]
// Set timeout to 5 seconds
ftp1.Timeout = 5000;

ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

try
{
    // When retrieving the file, if no response is received within 5 seconds
    // a SocketException will be thrown
    ftp1.Get("thefile.txt", "thefile.txt");
}
catch(System.Net.Sockets.SocketException ex)
{
    Debug.WriteLine("A socket exception has occurred: " + ex.Message);
    return;
}
catch(Exception ex)
{
    Debug.WriteLine("An exception occurred: " + ex.Message);
    return;
}
Debug.WriteLine("File successfully retrieved");

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


UseAuthentication Property

Ftp.UseAuthentication Property

Gets or sets a value that determines if certificate authentication is used.

[Visual Basic]
Public Property UseAuthentication As Boolean
[C#]
public bool UseAuthentication { get; set; }
[C++]
public: __property bool get_UseAuthentication();
public: __property void set_UseAuthentication(bool );
[JScript]
public function get UseAuthentication() : bool
public function set UseAuthentication(bool);

Property Value

A Boolean value which determines if certificate authentication is used. Defaults to true.

Remarks

If set to true, you must control the acceptance/denial of certificates in the CertificateReceived event. If set to false, all certificates will be accepted no matter if they are valid or invalid.

Example

The following example demonstrates receiving a remote certificate.

[Visual Basic]
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Use Implicit Secure FTP
        Ftp1.Security = Security.Implicit

        'Do not ignore problems with remote certificates
        Ftp1.UseAuthentication = True

        'Login and get working directory
        Ftp1.Server = "myServer"
        Ftp1.Username = "myUser"
        Ftp1.Password = "myPassword"
        Ftp1.Invoke(FtpCommand.PrintDir)
    End Sub

    Private Sub Ftp1_CertificateReceived(ByVal sender As Object, ByVal e As CertificateReceivedEventArgs) Handles Ftp1.CertificateReceived
        'Fires during SSL handshake when server presents its certificate
        Dim msg As String = "The server could not be validated for the following reason(s):"
        e.Accept = True

        'Security checks
        If (Not e.TrustedRoot) Then
            msg = msg + vbCrLf + "    -The certificate CA was not trusted"
            e.Accept = False
        End If
        If (Not e.ValidName) Then
            msg = msg + vbCrLf + "    -The certificate name was invalid"
            e.Accept = False
        End If
        If (Not e.ValidDate) Then
            msg = msg + vbCrLf + "   -The certificate date was invalid"
            e.Accept = False
        End If

        'If Validation failed, show message to user
        If (e.Accept = False) Then
            msg = msg + vbCrLf + vbCrLf + "Do you wish to override the security check?"
            If (MessageBox.Show(msg, "Security Alert: Server could not be validated", _
             MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = DialogResult.Yes) Then e.Accept = True
        End If
    End Sub

[C#]
private void button1_Click(object sender, System.EventArgs e)
{
    //Use Implicit Secure FTP
    ftp1.Security = Security.Implicit;

    //Do not ignore problems with remote certificates
    ftp1.UseAuthentication = true;

    //Login and get working directory
    ftp1.Server = "myServer";
    ftp1.Username = "myUser";
    ftp1.Password = "myPassword";
    ftp1.Invoke(FtpCommand.PrintDir);
}

private void ftp1_CertificateReceived(object sender, CertificateReceivedEventArgs e)
{
    //Fires during SSL handshake when server presents its certificate
    string msg = "The server could not be validated for the following reason(s):";
    e.Accept = true;

    //Security checks
    if (!e.TrustedRoot)
    {
        msg = msg + "\r\n    -The certificate CA was not trusted";
        e.Accept = false;
    }
    if (!e.ValidName)
    {
        msg = msg + "\r\n    -The certificate name was invalid";
        e.Accept = false;
    }
    if (!e.ValidDate)
    {
        msg = msg + "\r\n    -The certificate date was invalid";
        e.Accept = false;
    }

    //If Validation failed, show message to user
    if (e.Accept == false)
    {
        msg = msg + "\r\n\r\nDo you wish to override the security check?";
        if (MessageBox.Show(msg, "Security Alert: Server could not be validated",
            MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            e.Accept = true;
    }
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


UseControlAddressForPassive Property

Ftp.UseControlAddressForPassive Property

Gets or sets or a value that determines what server address should be used when doing a Passive data connection.

[Visual Basic]
Public Property UseControlAddressForPassive As Boolean
[C#]
public bool UseControlAddressForPassive { get; set; }
[C++]
public: __property bool get_UseControlAddressForPassive();
public: __property void set_UseControlAddressForPassive(bool );
[JScript]
public function get UseControlAddressForPassive() : bool
public function set UseControlAddressForPassive(bool);

Property Value

True if the control connection address should be used for Passive data connections, false otherwise. Defaults to true.

Remarks

When a Passive file transfer is desired, the server's response to the PASV command will indicate the address and port the client should connect to. This is almost always the same address being used by the control connection, so using this property's default value of true will usually work correctly. If your server is using a different address for the data connection, just set this property to false to use this address instead.

This property defaults to true because there are scenarios under which the client must connect to an intermediate firewall instead of directly to the server. Under these conditions, if the control connection is encrypted or the firewall does not property modify the server's response to the PASV command, then the client will connect to the same address as the control connection (which will typically allow proper operation).

FTP servers have evolved to be very configurable (for security reasons). Please check our support forum for addition information.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


UseIpSync Property

Ftp.UseIpSync Property

Indicates whether 'Interrupt Process and Synch' bytes are sent with the ABOR command.

[Visual Basic]
Public Property UseIpSync As Boolean
[C#]
public bool UseIpSync { get; set; }
[C++]
public: __property bool get_UseIpSync();
public: __property void set_UseIpSync(bool );
[JScript]
public function get UseIpSync() : bool
public function set UseIpSync(bool);

Property Value

True if Interrupt Process and Synch special action is taken, false otherwise. Default is false.

Remarks

The default value is false. Also, the IP/SYNC bytes are never sent to proxies or over a secure channel.

When receiving a file or a listing, and AbortTransfer() is used to abort the transfer, some servers require the IP/SYNC signal (4 bytes) be sent with the ABOR. This behavior causes unintended side-effects when Windows Firewall is in use. By setting this property to true, direct connections to HP/UX servers and other specific FTP servers will operate better when the ABOR command is sent.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Username Property

Ftp.Username Property

Gets or sets the Username used during session login.

[Visual Basic]
Public Property Username As String
[C#]
public string Username { get; set; }
[C++]
public: __property String* get_Username();
public: __property void set_Username(String* );
[JScript]
public function get Username() : String
public function set Username(String);

Property Value

A string value representing the Username to be issued during session login.

Remarks

The value of this property is automatically sent during session login (with the USER command).

The Ftp component was designed to automatically log in to the server when any communication with the server needs to take place. In order for this to occur the Username, Password, and Server properties all have to be set to valid values. Once this has been done, the user will be automatically logged in transparently. If either the Server, ServerPort, Username, or Password properties change, this will automatically be detected and login will automatically occur using the new data specified. It is recommended to use this method of logging into an FTP server over using the RawConnect method, which is reserved for special connection cases not defined in the FTP RFC.

For more information about logging in and out, see the topic Session Management.

You must set the Username property if you wish to connect to any server that requires authentication. If your application requires authentication communication that is NOT defined in the RFC spec, use the RawConnect method to connect to the server, then use the Invoke or BeginInvoke methods to send your login information.

Example

The following example demonstrates simple use of the client/server properties in storing a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToStore As String = "c:\FtpTest\mynewfile.bmp"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file transfer
Dim file As Dart.PowerTCP.Ftp.FtpFile
Debug.WriteLine("Attempting to store file " + FileToStore)

Try
   ' Attempt to store the file (The FileInfo object parses the filename from the path)
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

// Put method returns an FtpFile object containing information about the file transfer
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

try
{
    // Attempt to store the file (The FileInfo object parses the filename from the path)
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


UseSslShutdown Property

Ftp.UseSslShutdown Property

Controls whether or not shut-down bytes are sent to the server when the connection is closed.

[Visual Basic]
Public Property UseSslShutdown As Boolean
[C#]
public bool UseSslShutdown { get; set; }
[C++]
public: __property bool get_UseSslShutdown();
public: __property void set_UseSslShutdown(bool );
[JScript]
public function get UseSslShutdown() : bool
public function set UseSslShutdown(bool);

Property Value

True if shut-down bytes are to be sent to the server; false otherwise. The default value is true.

Remarks

When the Object.Close method is used to close down a secure connection, the component will send out shut-down bytes to attempt to gracefully shut down the connection. However, some servers do not expect these shut-down bytes and, as a result, the connection can be improperly closed. If this is the case, set this property to false and no shut-down bytes will be sent when the connection is closed.

Example

The following example demonstrates accessing the exposed TCP connection.

[Visual Basic]
Private Sub DisplayConnectionInfo()
   ' Check current connection state. If connected display info about the connection.
   If Ftp1.Connected Then
      label1.Text = "Connected to " + Ftp1.Connection.RemoteEndPoint.Address.ToString()
   Else
      label1.Text = "Not Connected"
   End If
End Sub

[C#]
private void DisplayConnectionInfo()
{
   // Check current connection state. If connected display info about the connection.
   if(ftp1.Connected)
      label1.Text = "Connected to " + ftp1.Connection.RemoteEndPoint.Address.ToString();
   else
      label1.Text = "Not connected";
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Ftp Methods

The methods of the Ftp class are listed below. For a complete list of Ftp class members, see the Ftp Members topic.

Public Instance Methods

Abort | Abruptly close both the control and data connection.
AbortTransfer | Abort the current file transfer operation.
BeginDelete | Deletes a file or directory tree asynchronously.
BeginGet | Overloaded. Get a single file from the server asynchronously and store it in a local file.
BeginInvoke | Invoke an FTP command (with a parameter) asynchronously.
BeginList | Get a file listing from the server asynchronously.
BeginPut | Overloaded. Put multiple files to the server asynchronously and store them in the root specified.
Close | Wait for all activity to complete and gracefully close the control connection.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Delete | Overloaded. Deletes a file or directory tree synchronously.
Dispose (inherited from Component) | Releases all resources used by the Component.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
ExpandLocalFiles | Gets a string array of local file pathnames that match the wildcard search pattern.
ExpandRemoteFiles | Gets a string array of remote file pathnames that match the wildcard search pattern.
Get | Overloaded. Get a single file from the server synchronously.
GetDirectory | Gets the server's working directory.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetSize | Gets the size of any file.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
Invoke | Overloaded. Send an FTP command (with a command modifier) synchronously.
List | Retrieve a file listing from the server synchronously.
Put | Overloaded. Store a single file to the server synchronously.
RawConnect | Optional method you can use if you need to connect to an FTP server that expects a login sequence that is non-standard.
Rename | Rename a file on the server.
SendCommand | Send an FTP command synchronously.
ToString (inherited from Component) | Overridden.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Abort Method

Ftp.Abort Method

Abruptly close both the control and data connection.

[Visual Basic]
Public Sub Abort()
[C#]
public void Abort();
[C++]
public: void Abort();
[JScript]
public function Abort();

Remarks

Use this method only when all connections from the server must be immediately closed without waiting for any response from the server. Use the Close method to gracefully close the connection by issuing the "QUIT" command. Use the AbortTransfer method to abort any data transfer while maintaining the control connection.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


AbortTransfer Method

Ftp.AbortTransfer Method

Abort the current file transfer operation.

[Visual Basic]
Public Sub AbortTransfer()
[C#]
public void AbortTransfer();
[C++]
public: void AbortTransfer();
[JScript]
public function AbortTransfer();

Remarks

When data is being transferred, calling this method causes the object to attempt to abort the data transfer gracefully. The control connection will not be aborted. If the transfer aborts successfully, the method will return an FtpFile object. To check the success of an AbortTransfer operation, check the FtpFile object returned from the method. If Position does not equal Length, then the file transfer was aborted. If the operation aborted is a multiple file transfer, an FtpFile will returned for all files involved with the transfer, both successfully transferred, partially transferred, and not transferred. To distinguish between the three, check the Length and Position properties:

  • If the file was transferred successfully, Position will equal FtpFile.Length.
  • If the file was partially transferred, Position will be less than FtpFile.Length.
  • If the file was not transferred, Position will be -1.

The AbortTransfer method can also be used to abort other processes. For example, this method can be used to abort lengthy file deletion processes resulting from use of Delete or BeginDelete.

This method is useful if the user simply wishes to abort the file transfer, but would like to maintain the current session.

This method differs from the Abort method in that the Abort method abruptly closes BOTH the control and data connection, where AbortTransfer only closes the data connection.

Example

The following example demonstrates

[Visual Basic]
Private Sub ButtonPutFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    ' Set server and user properties. This will allow calling of other
    ' Ftp Component methods with the log in/log out taking place "behind the scenes"
    Ftp1.Server = "MyFTPServer"
    Ftp1.Username = "blah"
    Ftp1.Password = "MyPass"

    ' Make sure DoEvents is true so UI events will be processed.
    Ftp1.DoEvents = True

    ' Put method returns an FtpFile object
    Dim file As Dart.PowerTCP.Ftp.FtpFile

    ' File is an image
    Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

    Try

       ' Begin a transfer, the user can click a button which calls Ftp.AbortTransfer.
       ' If this happens, the transfer should stop and return an FtpFile object.
       file = Ftp1.Put("C:\Test\Test.bmp", "Test.bmp")
    Catch ex As Exception
        Debug.WriteLine("Error: " + ex.Message)
        Exit Sub
    End Try

    ' Success, the file was either successfully transferred, or the transfer
    ' was successfully aborted. Find out which occurred.
    If file.Position = file.Length Then
       ' Transfer not aborted.
       Debug.WriteLine("File successfully transferred.")
       Debug.WriteLine("Name of file on server: " + file.RemoteFileName)
    Else
       ' Transfer was aborted
       Debug.WriteLine("File transfer aborted")
       Debug.WriteLine("Bytes transferred: " + file.Count)
    End If
End Sub

Private Sub ButtonAbortTransfer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
   Ftp1.AbortTransfer()
End Sub

[C#]
private void buttonPutFile_Click(object sender, System.EventArgs e)
{
    // Set server and user properties. This will allow calling of other
    // Ftp Component methods with the log in/log out taking place "behind the scenes"
    ftp1.Server = "MyFTPServer";
    ftp1.Username = "blah";
    ftp1.Password = "MyPass";

    // Make sure DoEvents is true so UI events will be processed.
    ftp1.DoEvents = true;

    // Put method returns an FtpFile object
    Dart.PowerTCP.Ftp.FtpFile file;

    // File is an image
    ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

    // Begin a transfer, the user can click a button which calls Ftp.AbortTransfer.
    // If this happens, the transfer should stop and return an FtpFile object.
    try
    {
       file = ftp1.Put("C:\\Test\\test.bmp", "test.bmp");
    }
    catch(Exception ex)
    {
       Debug.WriteLine("Error: " + ex.Message);
       return;
    }

    // Success, the file was either successfully transferred, or the transfer
    // was successfully aborted. Find out which occurred.
    if(file.Position == file.Length)
    {
       // Transfer not aborted.
       Debug.WriteLine("File successfully transferred.");
       Debug.WriteLine("Name of file on server: " + file.RemoteFileName);
    }
    else
    {
       // Transfer was aborted
       Debug.WriteLine("File transfer aborted");
       Debug.WriteLine("Bytes transferred: " + file.Count);
    }

}

private void buttonAbort_Click(object sender, System.EventArgs e)
{
    // If DoEvents is true, this button we be able to be clicked, aborting the transfer
    ftp1.AbortTransfer();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


BeginDelete Method

Ftp.BeginDelete Method

Deletes a file or directory tree asynchronously.

[Visual Basic]
Public Function BeginDelete( _
   ByVal searchPattern As String, _
   ByVal subDirectories As Boolean, _
   ByVal removeEmptyDirectories As Boolean, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginDelete(
   string searchPattern,
   bool subDirectories,
   bool removeEmptyDirectories,
   object state
);
[C++]
public: IAsyncResult* BeginDelete(
   String* searchPattern,
   bool subDirectories,
   bool removeEmptyDirectories,
   Object* state
);
[JScript]
public function BeginDelete(
   String searchPattern,
   bool subDirectories,
   bool removeEmptyDirectories,
   Object state
): IAsyncResult;

Parameters

searchPattern
May be a pathname (with or without wildcards) or a directory (indicated by a trailing slash).
subDirectories
Use true to indicate sub-directories should be searched for files to delete.
removeEmptyDirectories
Use true to indicate that directories that do not contain other directories or files should be removed.
state
User state information.

Remarks

This method deletes a file, multiple files, or directories from the server asynchronously. Upon completion the EndDelete event will be raised. A FileEventArgs object will be passed into this event, containing data about the files deleted. The only data contained within this object should be the File.RemoteFileName, containing the names of the files deleted, and File.Status, which should equal DeleteCompleted. All other members of this object should be at their default values.

This method provides a high-level alternative to Ftp.BeginInvoke(Command.Delete). It also expands upon this method by providing support for the deletion of multiple files and directory trees with a single method call.

If you are using the Ftp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the FileEventHandler delegate. See the topic Using Events When Using The Ftp Component As A Reference for more information.

The object state is useful for any kind of state information you would like accessible in the EndDelete event. Since the method is "disconnected" from the calling code and returns to the calling thread elsewhere, you may wish to pass an object/variable as state to be retrieved and used in the event handler.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

To perform this method synchronously, see Delete.

Use the AbortTransfer method to abort the deletion process while maintaining the control connection.

The following table shows some examples of wildcards:

Wildcard | Meaning
* | Delete all files in the directory (or subdirectories).
*.* | Delete all files in the directory (or subdirectories) that have a "." in the filename.
*.txt | Delete all files in the directory (or subdirectories) that end with ".txt".
Test* | Delete all files in the directory (or subdirectories) that start with "Test".
*Test* | Delete all files in the directory (or subdirectories) that contain "Test" in the filename.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.
NotSupportedException | The path format is not supported.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


BeginGet Method

Ftp.BeginGet Method

Get a stream asynchronously that can be used to read the FTP data connection.

Overload List

Get a stream asynchronously that can be used to read the FTP data connection.

[Visual Basic] Public Function BeginGet(ByVal String,ByVal Long,ByVal Object) As IAsyncResult
[C#] public IAsyncResult BeginGet(string,long,object);
[C++] public: IAsyncResult* BeginGet(String*,__int64,Object*);
[JScript] public function BeginGet(String,long,Object): IAsyncResult;

Get a file from the server asynchronously as a Stream object.

[Visual Basic] Public Function BeginGet(ByVal String,ByVal Stream,ByVal Object) As IAsyncResult
[C#] public IAsyncResult BeginGet(string,Stream,object);
[C++] public: IAsyncResult* BeginGet(String*,Stream*,Object*);
[JScript] public function BeginGet(String,Stream,Object): IAsyncResult;

Get a single file from the server asynchronously and store it in a local file.

[Visual Basic] Public Function BeginGet(ByVal String,ByVal String,ByVal Object) As IAsyncResult
[C#] public IAsyncResult BeginGet(string,string,object);
[C++] public: IAsyncResult* BeginGet(String*,String*,Object*);
[JScript] public function BeginGet(String,String,Object): IAsyncResult;

Get multiple files from the server asynchronously and store them in the local root directory specified.

[Visual Basic] Public Function BeginGet(ByVal String,ByVal String,ByVal String,ByVal Boolean,ByVal Boolean,ByVal Object) As IAsyncResult
[C#] public IAsyncResult BeginGet(string,string,string,bool,bool,object);
[C++] public: IAsyncResult* BeginGet(String*,String*,String*,bool,bool,Object*);
[JScript] public function BeginGet(String,String,String,bool,bool,Object): IAsyncResult;

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


BeginGet Method (String, Int64, Object)

Ftp.BeginGet Method (String, Int64, Object)

Get a stream asynchronously that can be used to read the FTP data connection.

[Visual Basic]
Public Function BeginGet( _
   ByVal remoteFileName As String, _
   ByVal restartMarker As Long, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginGet(
   string remoteFileName,
   long restartMarker,
   object state
);
[C++]
public: IAsyncResult* BeginGet(
   String* remoteFileName,
   __int64 restartMarker,
   Object* state
);
[JScript]
public function BeginGet(
   String remoteFileName,
   long restartMarker,
   Object state
): IAsyncResult;

Parameters

remoteFileName
Source pathname of the file on the server.
restartMarker
Restart location within file on the server. 0 is normally used.
state
User state information.

Remarks

This method begins to asynchronously get a stream that can be used to read the FTP data connection. Upon completion the EndGet event will be raised. A FileEventArgs object will be passed into this event, containing data about the transfer. This FileEventArgs object will contain a SegmentedStream object (Stream) which can be used to read the data connection. Simply call Read or BeginRead to read directly from the data stream. Zero bytes will be returned when reading is complete. See the topic Using Events Within The Visual Studio .NET Environment for more information on using events.

If you are using the Ftp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the FileEventHandler delegate. See the topic Using Events When Using The Ftp Component As A Reference for more information.

Since there is no local file to test for an automatic restart, you can specify a restart marker location within the remote file, and the stream will start at that byte offset location within the remote file. Use this method when you want to read the stream within your application.

The object state is useful for any kind of state information you would like accessible in the FtpEndGet event. Since the method is "disconnected" from the calling code and returns to the main thread elsewhere, you may wish to pass an object/variable as state to be retrieved and used in the event handler.

To synchronously get a stream that can be used to read the FTP data connection use Get.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

For more information on reading from the data connection asynchronously, see the topic Accessing The Data Connection Asynchronously For Reading.

Use this method to transparently open a stream to the data connection that can be used to read data. For example, you may wish to only transfer n bytes from the server (perhaps in the case where you are dealing with very large files). Use this method to read the data you want from the data connection stream, then use the AbortTransfer method to close the stream.

This method differs from the Ftp.BeginGet(String, Stream, Object) method in that Ftp.BeginGet(String, Stream, Object) is used to retrieve a file as a filled stream, so don't use this method unless you would like the complete file returned in your application.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response received from server.
InvalidOperationException | BeginGet used without providing an EndGet event handler.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument is null

Example

The following example demonstrates an asynchronous BeginGet for a single file, with that file being returned as a stream that can be used to read the FTP data connection in the EndGet event. In this example the user-defined method GetTextFilePreview accepts a file and the amount of characters to preview. In the EndGet event, the amount of characters to preview is read from the data connection and displayed.

[Visual Basic]
' This user-defined method is used to generate a preview of text files residing on the FTP Server. The user enters the
' FileName of the file on the server that they would like a preview of and the number of characters to preview. BeginGet is
' called with the FileName and CharactersToPreview (as the object) being passed in. The EndGet event will fire when the
' stream has been opened and is ready for reading.

Private Sub GetTextPreview(ByVal FileName As String, ByVal CharactersToPreview As Long)

   ' Set server and user properties. This will allow calling of other
   ' Ftp Component methods with the log in taking place "behind the scenes"
   Ftp1.Server = "MyFTPServer"
   Ftp1.Username = "blah"
   Ftp1.Password = "mypass"

   ' Begin an asynchronous Get. This also demonstrates using the third parameter (object State) to pass the
   ' number of characters to preview. This variable will be accessible in the EndGet Event

   Ftp1.BeginGet(FileName, 0, CharactersToPreview)

End Sub

' When the BeginGet operation has completed, the EndGet Event will fire.
Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

   Debug.WriteLine("Attempting to read from data stream")

   ' If an error occurred, it would be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then
      'Retrieve the number of characters to preview from the object State.
      Dim AmountOfChars As Integer = Convert.ToInt32(e.State)

      ' Create a byte array the size of the amount of characters to preview.
      Dim data(AmountOfChars) As Byte

      ' Read the amount of characters to preview from the stream
      e.Stream.Read(data, 0, AmountOfChars)

      e.Stream.Close()

      ' Close the stream
      Ftp1.AbortTransfer()

      ' Display the preview characters
      TextBox1.Text = System.Text.Encoding.ASCII.GetString(data)
   Else
      Debug.WriteLine("Error: " + e.Exception.ToString())
   End If

   ' Close the connection
   Ftp1.Close()

End Sub

[C#]
/*
/*
This user-defined method is used to generate a preview of text files residing on the FTP Server.
The user enters the FileName of the file on the server that they would like a preview of and the
number of characters to preview. BeginGet is called with the FileName and CharactersToPreview
(as the object) being passed in. The EndGet event will fire when the stream has been opened and is
ready for reading.
*/

private void GetTextFilePreview(string FileName, long CharactersToPreview)
{
    // Set server and user properties. This will allow calling of other
    // Ftp Component methods with the log in taking place "behind the scenes"
    ftp1.Server = "MyFTPServer";
    ftp1.Username = "blah";
    ftp1.Password = "mypass";

    // Begin an asynchronous Get. This also demonstrates using the third parameter (object State) to pass the
    // number of characters to preview. This variable will be accessible in the EndGet Event
    ftp1.BeginGet(FileName, 0, CharactersToPreview);
}

// When the BeginGet operation has completed, the EndGet Event will fire.
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
    Debug.WriteLine("Attempting to read from data stream");

    // If an error occurred, it would be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
       int AmountOfChars;

       // Retrieve the number of characters to preview from the object State.
       AmountOfChars = Convert.ToInt32(e.State);

       // Create a byte array the size of the amount of characters to preview.
       byte[] data = new byte[AmountOfChars];

       // Read the amount of characters to preview from the stream
       e.Stream.Read(data, 0, AmountOfChars);

       // Close the stream
       ftp1.AbortTransfer();

       // Display the preview characters.
       textBox1.Text = System.Text.Encoding.ASCII.GetString(data);
    }
    else
    {
       Debug.WriteLine("Error: " + e.Exception.ToString());
    }

    // Close the connection
    ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.BeginGet Overload List


BeginGet Method (String, Stream, Object)

Ftp.BeginGet Method (String, Stream, Object)

Get a file from the server asynchronously as a Stream object.

[Visual Basic]
Public Function BeginGet( _
   ByVal remoteFileName As String, _
   ByVal localStream As Stream, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginGet(
   string remoteFileName,
   Stream localStream,
   object state
);
[C++]
public: IAsyncResult* BeginGet(
   String* remoteFileName,
   Stream* localStream,
   Object* state
);
[JScript]
public function BeginGet(
   String remoteFileName,
   Stream localStream,
   Object state
): IAsyncResult;

Parameters

remoteFileName
Source pathname of the file on the server.
localStream
Initialized destination stream for the file.
state
User state information.

Remarks

This method begins to asynchronously get a file as a Stream object. Upon completion the EndGet event will be raised. A FileEventArgs object will be passed into this event, containing data about the transfer. For example, the FileEventArgs will contain an FtpFile object containing a Stream object which contains the file requested. See the topic Using Events Within The Visual Studio .NET Environment for more information on using events.

If you are using the Ftp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the FileEventHandler delegate. See the topic Using Events When Using The Ftp Component As A Reference for more information.

The object state is useful for any kind of state information you would like accessible in the EndGet event. Since the method is "disconnected" from the calling code and returns to the calling thread elsewhere, you may wish to pass an object/variable as state to be retrieved and used in the event handler.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

For more information on asynchronous stream transfer, see the topic Transferring Streams Asynchronously Overview (Advanced Users).

To get a file and store it in a Stream object synchronously use the Get method.

This method differs from the Ftp.BeginGet(String, Int64, Object) method in that Ftp.BeginGet(String, Int64, Object) is used to read directly from the open data connection.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response received from server.
InvalidOperationException | BeginGet used without providing an EndGet event handler.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ObjectDisposedException | Cannot access a closed stream.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.

Example

The following example demonstrates an asynchronous BeginGet for a single file, with that file being returned as a stream in the EndGet event.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Create stream to pass into BeginGet, it will be returned in the
' EndGet event filled with data from the requested file.
Dim stream 1 as new System.IO.MemoryStream()

' Call BeginGet, passing in the MemoryStream.
Ftp1.BeginGet("myfile.txt", stream1, Nothing)

' Display message, because BeginGet is asynchronous, this will be immediately executed.
Debug.WriteLine("Retrieving file as stream")

' When the BeginGet operation has completed, the EndGet Event will fire.
Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

   ' If an error occurred, it would be returned in the event. Be sure to
   ' check for it

   If e.Exception Is Nothing Then
      ' Report success
      Debug.WriteLine("Get complete")

      ' Create byte array to read data into
      Dim data(e.Stream.Length) As Byte

      ' Read data into byte array
      e.Stream.Position = 0
      Dim l As Integer = e.Stream.Read(data, 0, e.Stream.Length)

      ' Display data in a text box
      txtFile.Text = System.Text.ASCIIEncoding.ASCII.GetString(data)
      Debug.WriteLine(l.ToString() + " bytes transferred")
   Else
      Debug.WriteLine("Error: " + e.Exception.ToString())
   End If

   ' Close the connection
   Ftp1.Close()

End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Create stream to pass into BeginGet, it will be returned in the
// EndGet event filled with data from the requested file.
System.IO.MemoryStream stream1 = new System.IO.MemoryStream();

// Call BeginGet, passing in the MemoryStream.
ftp1.BeginGet("myfile.txt", stream1, null);

// Since BeginGet is asynchronous, this line will be immediatley executed.
Debug.WriteLine("Retrieving file as stream.");

// When the BeginGet operation has completed, the EndGet Event will fire.
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{

    // If an error occurred, it would be returned in the event. Be sure to
    // check for it

    if(e.Exception == null)
    {
       // Report success
       Debug.WriteLine("Get complete");

       // Create new byte array to read data into
       byte[] data = new byte[e.Stream.Length];

       // Read data into byte array
       e.Stream.Position = 0;
       int l = e.Stream.Read(data, 0, (int)e.Stream.Length);

       // Display data in text box
       textBox1.Text = System.Text.ASCIIEncoding.ASCII.GetString(data);
       Debug.WriteLine(l.ToString() + " bytes transferred");
    }
    else
    {
        Debug.WriteLine("Error: " + ex.Message);
    }

    // Close the connection
    ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.BeginGet Overload List


BeginGet Method (String, String, Object)

Ftp.BeginGet Method (String, String, Object)

Get a single file from the server asynchronously and store it in a local file.

[Visual Basic]
Public Function BeginGet( _
   ByVal remoteFileName As String, _
   ByVal localFileName As String, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginGet(
   string remoteFileName,
   string localFileName,
   object state
);
[C++]
public: IAsyncResult* BeginGet(
   String* remoteFileName,
   String* localFileName,
   Object* state
);
[JScript]
public function BeginGet(
   String remoteFileName,
   String localFileName,
   Object state
): IAsyncResult;

Parameters

remoteFileName
Source pathname of the file on the server.
localFileName
Destination pathname for the file.
state
User state information.

Remarks

This method begins to asynchronously get a single file. Upon completion the EndGet event will be raised. A FileEventArgs object will be passed into this event, containing data about the transfer. For example, the FileEventArgs will contain an FtpFile object that containing such data as the file names on the local and remote machine. See the topic Using Events Within The Visual Studio .NET Environment for more information on using events.

If you are using the Ftp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the FileEventHandler delegate. See the topic Using Events When Using The Ftp Component As A Reference for more information.

The object state is useful for any kind of state information you would like accessible in the EndGet event. Since the method is "disconnected" from the calling code and returns to the calling thread elsewhere, you may wish to pass an object/variable as state to be retrieved and used in the event handler.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

For more information on asynchronous file transfer, see the topic Retrieving Files Asynchronously Overview (Advanced Users).

To get a file synchronously use the Get method.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response received from server.
InvalidOperationException | BeginGet used without providing an EndGet event handler.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.

Example

The following example demonstrates how to asynchronously retrieve a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToGet As String = "test.txt"

' Call BeginGet, this will begin an asynchronous Get. Upon completion the EndGet Event will be fired.
Ftp1.BeginGet(FileToGet, "RetrievedFile.txt", Nothing)

' Display message, because BeginGet is asynchronous, this will be immediately executed.
Debug.WriteLine("Retrieving " + FileToGet)

' When the BeginGet operation has completed, the EndGet Event will fire.

Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

    ' If an error occurred, it would be returned in the event. Be sure to check for it.
    If e.Exception Is Nothing Then
       Debug.WriteLine("Get completed for file " + file.RemoteFileName)
    Else
       Debug.WriteLine("Error: " + e.Exception.ToString())
    End If

   ' Close the connection
   Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToGet = "test.txt";

// Call BeginGet, this will begin an asynchronous Get. Upon completion the EndGet Event will be fired.
ftp1.BeginGet(FileToGet, Application.StartupPath + "\\" + new System.IO.FileInfo(FileToGet).Name, null);

// Display message, because BeginGet is asynchronous, this will be immediately executed.
Debug.WriteLine("Retrieving " + FileToGet);

// When the BeginGet operation has completed, the EndGet Event will fire.
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{

    // If an error occurred, it would be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
       Debug.WriteLine("Get completed for file " + file.RemoteFileName);
    }
    else
    {
       Debug.WriteLine("Error: " + e.Exception.ToString());
    }

    // Close the connection
    ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.BeginGet Overload List


BeginGet Method (String, String, String, Boolean, Boolean, Object)

Ftp.BeginGet Method (String, String, String, Boolean, Boolean, Object)

Get multiple files from the server asynchronously and store them in the local root directory specified.

[Visual Basic]
Public Function BeginGet( _
   ByVal remoteRoot As String, _
   ByVal searchPattern As String, _
   ByVal localRoot As String, _
   ByVal subDirectories As Boolean, _
   ByVal synchronize As Boolean, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginGet(
   string remoteRoot,
   string searchPattern,
   string localRoot,
   bool subDirectories,
   bool synchronize,
   object state
);
[C++]
public: IAsyncResult* BeginGet(
   String* remoteRoot,
   String* searchPattern,
   String* localRoot,
   bool subDirectories,
   bool synchronize,
   Object* state
);
[JScript]
public function BeginGet(
   String remoteRoot,
   String searchPattern,
   String localRoot,
   bool subDirectories,
   bool synchronize,
   Object state
): IAsyncResult;

Parameters

remoteRoot
Root directory on the server.
searchPattern
Wildcard search pattern of files to get; may include a path.
localRoot
Destination root directory on the client.
subDirectories
true if sub-directories should be recursively copied.
synchronize
true if files of the same size that already exist locally should not be copied.
state
User state information.

Remarks

This method begins to asynchronously retrieve multiple files. Upon completion the EndGet event will be raised. A FileEventArgs object will be passed into this event, containing data about the transfer. For example, the FileEventArgs will contain an array of FtpFile objects that containing filenames of the local and remote files for all files transferred. See the topic Using Events Within The Visual Studio .NET Environment for more information on using events.

If you are using the Ftp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the FileEventHandler delegate. See the topic Using Events When Using The Ftp Component As A Reference for more information.

The object state is useful for any kind of state information that you would like accessible in the EndGet event. Since the method is "disconnected" from the calling code and returns to the main thread elsewhere, you may wish to pass an object/variable as state to be retrieved and used in the event handler.

For more information on implementing and handling events using products in PowerTCP.NET, see the topic, Using Events In PowerTCP.

For more information on asynchronous file transfer, see the topic Retrieving Files Asynchronously Overview (Advanced Users).

To get multiple files synchronously use Get.

If localRoot exists, the files will be saved to the directory path specified. If it does not exist, the directory will be created.

The Ftp.BeginGet method gets all files specified in remoteRoot (and subdirectories if subDirectories is true) that meet the wildcard requirement specified in searchPattern. The following table shows some examples of wildcards:

Wildcard | Meaning
* | Get all files in the directory.
*.* | Get all files in the directory that have a "." in the filename.
*.txt | Get all files in the directory that end with ".txt".
Test* | Get all files in the directory that start with "Test".
*Test* | Get all files in the directory that contain "Test" in the filename.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response received from server.
InvalidOperationException | BeginGet used without providing an EndGet event handler.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.
NotSupportedException | The path format is not supported.

Example

The following example demonstrates how to asynchronously retrieve multiple files.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Call BeginGet, this will begin an asynchronous Get. Upon completion the EndGet Event will be fired.
Ftp1.BeginGet("mydir", "*", Application.StartupPath + "/", false, Nothing)

' Display message, because BeginGet is asynchronous, this will be immediately executed.
Debug.WriteLine("Retrieving all files in mydir")

' When the BeginGet operation has completed, the EndGet Event will fire.

Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

   ' If an error occurred, it would be returned in the event. Be sure to =check for it.
   If e.Exception Is Nothing Then

       Dim file As Dart.PowerTCP.Ftp.FtpFile

      ' Iterate through files collection and display info. This will contain a File object
      ' for each file retrieved.
      For Each file In e.Files
         Debug.WriteLine("Get completed for " + file.RemoteFileName)
      Next
   Else
      Debug.WriteLine("Error: " + e.Exception.ToString())
   End If
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Call BeginGet for all files in the directory "mydir", this will begin an asynchronous MGet. Upon completion
// the EndGet Event will be fired.
ftp1.BeginGet("mydir", "*", Application.StartupPath + "//", false, null);

// Display message, because BeginGet is asynchronous, this will be immediately executed.
Debug.WriteLine("Retrieving all files in mydir");

// When the BeginGet operation has completed, the EndGet Event will fire.
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{

    // If an error occurred, it would be returned in the event. Be sure to check for it
    if(e.Exception == null)
    {
        // Iterate through files collection and display info. This will contain a File object
        // for each file retrieved.
        foreach(Dart.PowerTCP.Ftp.FtpFile file in e.Files)
            Debug.WriteLine("Get completed for file " + file.RemoteFileName);
    }
    else
    {
        Debug.WriteLine("Error: " + e.Exception.ToString());
    }
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.BeginGet Overload List


BeginInvoke Method

Ftp.BeginInvoke Method

Invoke an FTP command (with a parameter) asynchronously.

[Visual Basic]
Public Function BeginInvoke( _
   ByVal command As FtpCommand, _
   ByVal modifier As String, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginInvoke(
   FtpCommand command,
   string modifier,
   object state
);
[C++]
public: IAsyncResult* BeginInvoke(
   FtpCommand command,
   String* modifier,
   Object* state
);
[JScript]
public function BeginInvoke(
   FtpCommand command,
   String modifier,
   Object state
): IAsyncResult;

Parameters

command
FTP command to send.
modifier
Command modifier appended to command.
state
User state information.

Remarks

This method begins to asynchronously send a low-level FTP command to your server. Upon completion the EndInvoke event will be raised. An InvokeEventArgs object will be passed into this event, containing data about the command sent and the response received. See the topic Using Events Within The Visual Studio .NET Environment for more information on using events.

If you are using the Ftp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the InvokeEventHandler delegate. See the topic Using Events When Using The Ftp Component As A Reference for more information.

If you wish to send your own command, use FtpCommand.Null, and specify your entire command as the modifier. An example would be BeginInvoke(FtpCommand.Null, "MYCOMMAND file1.txt", null).

The object state is useful for any kind of state information you would like accessible in the EndInvoke event. Since the method is "disconnected" from the calling code and returns to the main thread elsewhere, you may wish to pass an object/variable as state to be retrieved and used in the event handler.

To invoke an FTP command synchronously use Invoke.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

For more information on asynchronously sending commands, see the topic Sending Commands Asynchronously.

Use this method to send a command with a parameter to the server (for example, HELP or CWD). This method can also be used to send commands without a parameter (for example PWD or QUIT) by specifying the FtpCommand as the first parameter and null as the second parameter.

As an example, use this method if you want to send an asynchronous "HELP" request to the server. FtpCommand.Help would be used as the command parameter and the item that you want help on would be used as the modifier parameter. In this case the EndInvoke event will not be raised until the response is received from the server.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response received from server.
InvalidOperationException | BeginInvoke used without providing an EndInvoke event handler.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).

Example

The following example demonstrates using BeginInvoke to issue a command (in this case, DELE) asynchronously.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Issue delete command asynchronously, specifying the file to delete as the second parameter,
' upon completion the EndInvoke Event will be fired.
Ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.Delete, "zzz.txt", Nothing)

' When the BeginInvoke operation has completed, the EndInvoke Event will fire.
Private Sub Ftp1_EndInvoke(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.InvokeEventArgs) Handles Ftp1.EndInvoke

   ' If an error occurred during the asynchronous method, it would
   ' be returned in the event. Be sure to check for it
   If e.Exception Is Nothing Then
      Debug.WriteLine("Command issued " + e.Request)
      Debug.WriteLine("Response code received " + e.Response.Code.ToString())
      Debug.WriteLine("Response text received " + e.Response.Text)
   Else
      Debug.WriteLine("Error: " + e.Exception.Message)
   End If

End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Issue delete command asynchronously, specifying the file to delete as the second parameter,
// upon completion the EndInvoke Event will be fired.
ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.Delete, "filetodelete.txt", null);

// When the BeginInvoke operation has completed, the EndInvoke Event will fire.
private void ftp1_EndInvoke(object sender, Dart.PowerTCP.Ftp.InvokeEventArgs e)
{
    // If an error occurred during the asynchronous operation, it
    // would be returned in the event. Be sure to check for it
    if(e.Exception == null)
    {
        Debug.WriteLine("Command issued " + e.Request);
        Debug.WriteLine("Response code received " + e.Response.Code);
        Debug.WriteLine("Response text received " + e.Response.Text);
    }
    else
    {
        Debug.WriteLine("Error: " + e.Exception.Message);
    }
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


BeginList Method

Ftp.BeginList Method

Get a file listing from the server asynchronously.

[Visual Basic]
Public Function BeginList( _
   ByVal searchPattern As String, _
   ByVal full As Boolean, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginList(
   string searchPattern,
   bool full,
   object state
);
[C++]
public: IAsyncResult* BeginList(
   String* searchPattern,
   bool full,
   Object* state
);
[JScript]
public function BeginList(
   String searchPattern,
   bool full,
   Object state
): IAsyncResult;

Parameters

searchPattern
Filename for the listing, which may include wildcards.
full
true for a full listing, or false for a named list.
state
User state information.

Remarks

This method begins to asynchronously retrieve a listing. Upon completion the EndList event will be raised. A ListEventArgs object will be passed into this event, containing a Listing object which encapsulates an FTP Listing. See the topic Using Events Within The Visual Studio .NET Environment for more information on using events.

If you are using the Ftp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the ListEventHandler delegate. See the topic Using Events When Using The Ftp Component As A Reference for more information.

Specify a full listing for complete listing information, but if the server's listing format is not recognized as standard UNIX or DOS, you will have to parse out each line yourself. Use an abbreviated name list if you only need filename information.

The object state is useful for any kind of state information. Since the method is "disconnected" from the calling code and returns to the calling thread elsewhere, you may wish to pass an object/variable as state to be retrieved and used in the event handler.

To get a listing synchronously use List.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response received from server.
InvalidOperationException | BeginList used without providing an EndList event handler.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).

Example

The following example demonstrates using BeginList to retrieve a Listing asynchronously.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Get a listing for all text files in home/test. Upon completion the EndList
' event will fire, with the Listing passed in as an arg
 Ftp1.BeginList("/home/test/*.txt", True, Nothing)

' Because BeginList is asynchronous, this line will be immediately executed.
Debug.WriteLine("Retrieving Listing")

' When the BeginList operation has completed, the EndList Event will fire.
Private Sub Ftp1_EndList(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ListEventArgs) Handles Ftp1.EndList

   ' If an error occurred during the asynchronous method, it would be
   ' returned in the event. Be sure to check for it.
   if e.Exception Is Nothing Then

      ' Retrieve listing and display

      ' Begin setting up the ListView (listView1 is a standard ListView object) display

      ' Show gridlines.
      ListView1.GridLines = True

      ' Set View to Details
      ListView1.View = View.Details

      ' Add column headings for file name, size, and date.
      ListView1.Columns.Add("File Name", 100, HorizontalAlignment.Left)
      ListView1.Columns.Add("File Size", 100, HorizontalAlignment.Left)
      ListView1.Columns.Add("File Timestamp", 100, HorizontalAlignment.Left)

      ' Iterate through the listing, adding a row to the ListBox for each
      Dim le As Dart.PowerTCP.Ftp.ListEntry
      For Each le In e.Listing
         Dim cols() As String = {le.Name, le.Size.ToString(), le.TimeStamp}
         ListView1.Items.Add(New ListViewItem(cols))
      Next
  Else
     Debug.WriteLine(e.Exception.Message)
  End If

  ' Close the connection
  Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Get a listing for all text files in home/test. Upon completion the EndList
// event will fire, with the Listing passed in as an arg
ftp1.BeginList("/home/test/*.txt", true, null);

// Because BeginList is asynchronous, this line will be immediately executed.
Debug.WriteLine("Retrieving listing");

// When the BeginList operation has completed, the EndList Event will fire.

private void ftp1_EndList(object sender, Dart.PowerTCP.Ftp.ListEventArgs e)
{
    // If an error occurred during the asynchronous method, it would
    // be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
       // Retrieve listing and display

       // Begin setting up the ListView (listView1 is a standard ListView object) display

       // Show gridlines.
       listView1.GridLines = true;

       // Set View to Details
       listView1.View = View.Details;

       // Add column headings for file name, size, and date.
       listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
       listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
       listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

       // Iterate through the listing, adding a row to the ListBox for each
       foreach(Dart.PowerTCP.Ftp.ListEntry le in e.Listing)
       {
          string[] cols = {le.Name, le.Size.ToString(), le.TimeStamp};
          listView1.Items.Add(new ListViewItem(cols));
       }
    }
    else
    {
        Debug.WriteLine("Error: " + ex.Message);
    }

    // Close the connection
    ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


BeginPut Method

Ftp.BeginPut Method

Store a file to the FTP server asynchronously using a stream.

Overload List

Store a file to the FTP server asynchronously using a stream.

[Visual Basic] Public Function BeginPut(ByVal Stream,ByVal String,ByVal Object) As IAsyncResult
[C#] public IAsyncResult BeginPut(Stream,string,object);
[C++] public: IAsyncResult* BeginPut(Stream*,String*,Object*);
[JScript] public function BeginPut(Stream,String,Object): IAsyncResult;

Get a stream asynchronously that can be used to write to the FTP data connection.

[Visual Basic] Public Function BeginPut(ByVal String,ByVal Long,ByVal Object) As IAsyncResult
[C#] public IAsyncResult BeginPut(string,long,object);
[C++] public: IAsyncResult* BeginPut(String*,__int64,Object*);
[JScript] public function BeginPut(String,long,Object): IAsyncResult;

Store a single file to the FTP server asynchronously.

[Visual Basic] Public Function BeginPut(ByVal String,ByVal String,ByVal Object) As IAsyncResult
[C#] public IAsyncResult BeginPut(string,string,object);
[C++] public: IAsyncResult* BeginPut(String*,String*,Object*);
[JScript] public function BeginPut(String,String,Object): IAsyncResult;

Put multiple files to the server asynchronously and store them in the root specified.

[Visual Basic] Public Function BeginPut(ByVal String,ByVal String,ByVal String,ByVal Boolean,ByVal Boolean,ByVal Object) As IAsyncResult
[C#] public IAsyncResult BeginPut(string,string,string,bool,bool,object);
[C++] public: IAsyncResult* BeginPut(String*,String*,String*,bool,bool,Object*);
[JScript] public function BeginPut(String,String,String,bool,bool,Object): IAsyncResult;

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


BeginPut Method (Stream, String, Object)

Ftp.BeginPut Method (Stream, String, Object)

Store a file to the FTP server asynchronously using a stream.

[Visual Basic]
Public Function BeginPut( _
   ByVal localStream As Stream, _
   ByVal remoteFileName As String, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginPut(
   Stream localStream,
   string remoteFileName,
   object state
);
[C++]
public: IAsyncResult* BeginPut(
   Stream* localStream,
   String* remoteFileName,
   Object* state
);
[JScript]
public function BeginPut(
   Stream localStream,
   String remoteFileName,
   Object state
): IAsyncResult;

Parameters

localStream
Source stream for the file.
remoteFileName
Destination pathname for the file on the server.
state
User state information.

Remarks

This method begins to asynchronously store a Stream object as a file on the server. Upon completion the EndPut event will be raised. A FileEventArgs object will be passed into this event, containing data about the transfer. For example, the FileEventArgs will contain an FtpFile object containing a Stream object which includes the file requested. See the topic Using Events Within The Visual Studio .NET Environment for more information on using events.

If you are using the Ftp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the FileEventHandler delegate. See the topic Using Events When Using The Ftp Component As A Reference for more information.

The object state is useful for any kind of state information you would like accessible in the EndPut event. Since the method is "disconnected" from the calling code and returns to the calling thread elsewhere, you may wish to pass an object/variable as state to be retrieved and used in the event handler.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

For more information on asynchronous stream transfer, see the topic Storing A Stream As A File Asynchronously.

To put a file on the server synchronously using a stream use the Put method.

This method differs from the Ftp.BeginPut(String, Int64, Object) method in that Ftp.BeginPut(String, Int64, Object) is used to write to the open data connection.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response received from server.
InvalidOperationException | BeginPut used without providing an EndPut event handler.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ObjectDisposedException | Cannot access a closed stream.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.

Example

The following example demonstrates using BeginPut to put a stream to the server.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in out taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Create a MemoryStream to hold data to be stored on the server
Dim stream1 As New System.IO.MemoryStream()

' Create a byte array containing the data to be written to the stream
Dim data() As Byte = System.Text.Encoding.ASCII.GetBytes("Data to be written to the stream")

' Write to the stream
stream1.Write(data, 0, data.Length)

' Store the data on the server under the name "stream.txt". Upon completion the
' EndPut event will fire.
 Ftp1.BeginPut(stream1, "stream.txt", Nothing)

' Since BeginPut is asynchronous, this line of code will be immediately executed.
Debug.WriteLine("Put stream executing")

' When the BeginPut operation has completed, the EndPut Event will fire.
Private Sub Ftp1_EndPut(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndPut

   ' If an error occurred during the asynchronous operation, it would be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then
      ' Display the information about the newly Put stream
      Debug.WriteLine(e.File.RemoteFileName + " created on server")
   Else
      Debug.WriteLine("Error: " + e.Exception.Message)
   End If

   ' Close the connection
   Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Create a MemoryStream to hold data to be stored on the server
System.IO.MemoryStream stream1 = new System.IO.MemoryStream();

// Create a byte array containing the data to be written to the stream
byte[] data = System.Text.Encoding.ASCII.GetBytes("Data to be written to the stream");

// Write to the stream
stream1.Write(data, 0, data.Length);

// Store the data on the server under the name "stream.txt". Upon completion the
// EndPut event will fire.
ftp1.BeginPut(stream1, "stream.txt", null);

// Since BeginPut is asynchronous, this line of code will be immediately executed.
Debug.WriteLine("Put stream executing");

// When the BeginPut operation has completed, the EndPut Event will fire.
private void ftp1_EndPut(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{

    // If an error occurred during the asynchronous operation, it would
    // be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
        // Display the information about the newly Put stream
        Debug.WriteLine(e.File.RemoteFileName + " created on server");
    }
    else
    {
        Debug.WriteLine("Error: " + e.Exception.Message);
    }

    // Close the connection
    ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.BeginPut Overload List


BeginPut Method (String, Int64, Object)

Ftp.BeginPut Method (String, Int64, Object)

Get a stream asynchronously that can be used to write to the FTP data connection.

[Visual Basic]
Public Function BeginPut( _
   ByVal remoteFileName As String, _
   ByVal restartMarker As Long, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginPut(
   string remoteFileName,
   long restartMarker,
   object state
);
[C++]
public: IAsyncResult* BeginPut(
   String* remoteFileName,
   __int64 restartMarker,
   Object* state
);
[JScript]
public function BeginPut(
   String remoteFileName,
   long restartMarker,
   Object state
): IAsyncResult;

Parameters

remoteFileName
Destination pathname for the file on the server.
restartMarker
Restart location within file on the server. 0 is normally used.
state
User state information.

Remarks

This method begins to asynchronously get a stream that can be used to write to the FTP data connection. Upon completion the EndPut event will be raised. A FileEventArgs object will be passed into this event, containing data about the transfer. For example, the FileEventArgs will contain an FtpFile object that includes data about the transfer on both the server and client. See the topic Using Events Within The Visual Studio .NET Environment for more information on using events.

If you are using the Ftp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the FileEventHandler delegate. See the topic Using Events When Using The Ftp Component As A Reference for more information.

Since there is no local file to test for an automatic restart, you can specify a restart marker location within the remote file, and the stream will start writing at that byte offset location within the remote file.

The object state is useful for any kind of state information. Since the method is "disconnected" from the calling code and returns to the calling thread elsewhere, you may wish to pass an object/variable as state to be retrieved and used in the event handler.

To synchronously get a stream that can be used to write to the FTP data connection use Put.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

For more information on writing to the data connection asynchronously, see the topic Accessing The Data Connection Asynchronously For Writing.

This method differs from the Ftp.BeginPut(String, Stream, Object) method in that Ftp.BeginPut(String, Stream, Object) is used to store a stream as a file that will be created on the server.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response received from server.
InvalidOperationException | BeginPut used without providing an EndPut event handler.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.

Example

The following example demonstrates using BeginPut to write to the data stream.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Call BeginPut, A file called "mynewstream.txt" will be created on the server
' When execution returns in the EndPut event a data connection will be opened to the server.
' Data can be written to the "mynewstream.txt" file in this event.
Ftp1.BeginPut("mynewstream.txt", 0, Nothing)

' Report to user
Debug.WriteLine("Opening data stream")

' When the BeginPut operation has completed, the EndPut Event will fire.
Private Sub Ftp1_EndPut(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndPut

    ' If an error occurred during the asynchronous method, it would
    ' be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then

      ' Display message to user
      Debug.WriteLine("Attempting to write to stream")

      ' Write text
      e.Stream.Write("Some text ")

      ' Write more text
      e.Stream.Write("Some more text ")

      ' Write more text
      e.Stream.Write("This is the end.)

      ' Close the stream
      e.Stream.Close()

      Debug.WriteLine("Done writing. Stream closed.")

   Else
      Debug.WriteLine("Error: " + e.Exception.Message)
   End If

   ' Close the connection
   Ftp1.Close()

End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Call BeginPut, A file called "mynewstream.txt" will be created on the server
// When execution returns in the EndPut event a data connection will be opened to the server.
// Data can be written to the "mynewstream.txt" file in this event.
ftp1.BeginPut("mynewstream.txt", 0, null);

// Report to user
Debug.WriteLine("Opening data stream");

// When the BeginPut operation has completed, the EndPut Event will fire.
private void ftp1_EndPut(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
    // Display message to user
    Debug.WriteLine("Writing to stream");

    // If an error occurred during the asynchronous method, it would
    // be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
        // Write data
        e.Stream.Write("Some text ");

       // Write this text
       e.Stream.Write("Some more text ");

       // Write this text
       e.Stream.Write("This is the end");

       // Close the stream
       e.Stream.Close();

       Debug.WriteLine("Done writing. Stream closed.");
    }
    else
    {
       Debug.WriteLine("Error: " + e.Exception.Message");
    }
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.BeginPut Overload List


BeginPut Method (String, String, Object)

Ftp.BeginPut Method (String, String, Object)

Store a single file to the FTP server asynchronously.

[Visual Basic]
Public Function BeginPut( _
   ByVal localFileName As String, _
   ByVal remoteFileName As String, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginPut(
   string localFileName,
   string remoteFileName,
   object state
);
[C++]
public: IAsyncResult* BeginPut(
   String* localFileName,
   String* remoteFileName,
   Object* state
);
[JScript]
public function BeginPut(
   String localFileName,
   String remoteFileName,
   Object state
): IAsyncResult;

Parameters

localFileName
Source pathname of the local file to transfer.
remoteFileName
Destination pathname for the remote file on the server.
state
User state information.

Remarks

This method begins to asynchronously store a single file. Upon completion the EndPut event will be raised. A FileEventArgs object will be passed into this event, containing data about the transfer. For example, the FileEventArgs will contain an FtpFile object that includes such data as the file names on the local and remote machine. See the topic Using Events Within The Visual Studio .NET Environment for more information on using events.

If you are using the Ftp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the FileEventHandler delegate. See the topic Using Events When Using The Ftp Component As A Reference for more information.

The object state is useful for any kind of state information you would like accessible in the EndPut event. Since the method is "disconnected" from the calling code and returns to the calling thread elsewhere, you may wish to pass an object/variable as state to be retrieved and used in the event handler.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

For more information on asynchronous file transfer, see the topic Storing Files Asynchronously Overview (Advanced Users).

To put a file on the server synchronously use the Put method.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response received from server.
InvalidOperationException | BeginPut used without providing an EndPut event handler.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.

Example

The following example demonstrates using BeginPut to Put a file to the server asynchronously

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToPut As String = "c:\FtpTest\doc.txt"

' Call BeginPut for the specified file, this will begin an asynchronous Put. Upon completion
' the EndPut Event will be fired. (The FileInfo object parses the name from the path).
Ftp1.BeginPut(FileToPut, New IO.FileInfo(FileToPut).Name, Nothing)

'Report to user. Since BeginPut is asynchronous, this line will be immediately executed
Debug.WriteLine("Storing file")

' When the BeginPut operation has completed, the EndPut Event will fire.
Private Sub Ftp1_EndPut(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndPut

   Dim file As Dart.PowerTCP.Ftp.FtpFile

   ' If an error occurred, it would be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then
      Debug.WriteLine("Successfully Put " + file.LocalFileName)
   Else
      Debug.WriteLine("Error: " + e.Exception.ToString())
   End If

   ' Close the connection
   Ftp1.Close()

End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToPut = "c:\\FtpTest\\MyFile.bmp";

// Call BeginPut for the specified file, this will begin an asynchronous Put. Upon completion
// the EndPut Event will be fired. (The FileInfo object parses the filename from the path).
ftp1.BeginPut(FileToPut, new System.IO.FileInfo(FileToPut).Name, null);

// Report to user. Since BeginPut is asynchronous, this line will be immediately executed.
Debug.WriteLine("Storing file");

// When the BeginPut operation has completed, the EndPut Event will fire.
private void ftp1_EndPut(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{

   // If an error occurred, it would be returned in the event. Be sure to check for it.
   if(e.Exception == null)
   {
      Debug.WriteLine("Successfully put " + file.LocalFileName);
   }
   else
   {
      Debug.WriteLine("Error: " + e.Exception.ToString())
   }

   // Close the connection
   ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.BeginPut Overload List


BeginPut Method (String, String, String, Boolean, Boolean, Object)

Ftp.BeginPut Method (String, String, String, Boolean, Boolean, Object)

Put multiple files to the server asynchronously and store them in the root specified.

[Visual Basic]
Public Function BeginPut( _
   ByVal localRoot As String, _
   ByVal searchPattern As String, _
   ByVal remoteRoot As String, _
   ByVal subDirectories As Boolean, _
   ByVal synchronize As Boolean, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginPut(
   string localRoot,
   string searchPattern,
   string remoteRoot,
   bool subDirectories,
   bool synchronize,
   object state
);
[C++]
public: IAsyncResult* BeginPut(
   String* localRoot,
   String* searchPattern,
   String* remoteRoot,
   bool subDirectories,
   bool synchronize,
   Object* state
);
[JScript]
public function BeginPut(
   String localRoot,
   String searchPattern,
   String remoteRoot,
   bool subDirectories,
   bool synchronize,
   Object state
): IAsyncResult;

Parameters

localRoot
Source root directory on the client.
searchPattern
Wildcard search pattern of files to put; may include path.
remoteRoot
Destination root directory on the server.
subDirectories
true if sub-directories should be recursively copied.
synchronize
true if files of the same size that already exist remotely should not be copied.
state
User state information.

Remarks

This method begins to asynchronously store multiple files. Upon completion the EndPut event will be raised. A FileEventArgs object will be passed into this event, containing data about the transfer. For example, the FileEventArgs will include an array of FtpFile objects that contain the filenames of the local and remote files for all files transferred. See the topic Using Events Within The Visual Studio .NET Environment for more information on using events.

If you are using the Ftp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the FileEventHandler delegate. See the topic Using Events When Using The Ftp Component As A Reference for more information.

The object state is useful for any kind of state information you would like accessible in the EndPut event. Since the method is "disconnected" from the calling code and returns to the calling thread elsewhere, you may wish to pass an object/variable as state to be retrieved and used in the event handler.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

For more information on asynchronous file transfer, see the topic Storing Files Asynchronously Overview (Advanced Users).

To store multiple files synchronously use the Put method.

The BeginPut method stores all files in the specified localRoot (and subdirectories if subDirectories is true) that meet the wildcard requirement specified in searchPattern. The following table shows some examples of wildcards:

Wildcard | Meaning
* | Get all files in the directory.
*.* | Get all files in the directory that have a "." in the filename.
*.txt | Get all files in the directory that end with ".txt".
Test* | Get all files in the directory that start with "Test".
*Test* | Get all files in the directory that contain "Test" in the filename.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response received from server.
InvalidOperationException | BeginPut used without providing an EndPut event handler.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.
NotSupportedException | The path format is not supported.

Example

The following example demonstrates using BeginPut to Put multiple files to the server asynchronously.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Call BeginPut all files in "C:\Test", this will begin an asynchronous Put. Upon completion
' the EndPut Event will be fired.
Ftp1.BeginPut("C:\Test", "*", "", False, Nothing)

' Report to user. Since BeginPut is asynchronous, this line will be immediately executed.
Debug.WriteLine("MPUT Executing")

' When the BeginPut operation has completed, the EndPut Event will fire.
Private Sub Ftp1_EndPut(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndPut

   ' If an error occurred, it would be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then

      ' Iterate through files collection and display info about each file transferred.
      Dim file As Dart.PowerTCP.Ftp.FtpFile
      For Each file In e.Files
         Debug.WriteLine("Successfully Put " + file.LocalFileName)
      Next
   Else
      Debug.WriteLine("Error: " + e.Exception.Message);
   End If

   ' Close the connection
   Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Call BeginPut all files in "C:\Test", this will begin an asynchronous Put. Upon completion
// the EndPut Event will be fired.
ftp1.BeginPut("C:\\Test", "*", "/home/test/mydir", false, null);

// Report to user. Since BeginPut is asynchronous, this line will be immediately executed.
Debug.WriteLine("MPUT Executing");

// When the BeginPut operation has completed, the EndPut Event will fire.
private void ftp1_EndPut(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{

    // If an error occurred, it would be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
        // Iterate through files collection and display info for each file transferred.
        foreach(Dart.PowerTCP.Ftp.FtpFile file in e.Files)
            Debug.WriteLine("Successfully put " + file.LocalFileName);
    }
    else
    {
        Debug.WriteLine("Error: " + e.Exception.Message);
    }

    // Close the connection
    ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.BeginPut Overload List


Close Method

Ftp.Close Method

Wait for all activity to complete and gracefully close the control connection.

[Visual Basic]
Public Function Close() As Invoke
[C#]
public Invoke Close();
[C++]
public: Invoke* Close();
[JScript]
public function Close(): Invoke;

Return Value

An FtpInvoke object describing the request/response. If connected, the FtpInvoke object will contain the "QUIT" request and the server's goodbye message. If not connected, the FtpInvoke object will not have any content.

Remarks

FTP communication occurs using two connections, a control connection which is used for logging in and sending commands, and a data connection which is used for transferring files and listings. Use this method to terminate the control connection. This method should be considered the intended means of ending an FTP Session. It differs from the AbortTransfer method and Abort method in that the AbortTransfer method is used to close the data connection during a file transfer while maintaining the control connection and the Abort method is used to abruptly close both connections and release all resources associated with the Ftp component.

If a transfer is in progress, it will continue until finished, after which a "QUIT" message is sent and the method returns after the control connection is closed by the server. This method uses Ftp.Invoke(FtpCommand.Quit) and waits until the server has closed the connection. To perform this operation asynchronously, use BeginInvoke(FtpCommand.Quit, null).

Example

The following example demonstrates closing a connection.

[Visual Basic]
' First, check to see if currently connected
If Ftp1.Connected Then

   ' Close method returns an Invoke object
   Dim invoke As Dart.PowerTCP.Ftp.Invoke

   ' Attempt to close the connection by using the Close method
   Try
      invoke = Ftp1.Close()
   Catch ex As Exception
      ' An error occurred during the close attempt
      Debug.WriteLine(ex.Message)
   End Try

   If Ftp1.Connected Then
      ' For some reason the Close method did not work. Just perform a harsh abort
      Ftp1.Dispose()
      Debug.WriteLine("Unable to QUIT, connection aborted")
   Else
      Debug.WriteLine("Close successful.")
      Debug.WriteLine("Response Code From Server: " + invoke.Response.Code.ToString())
      Debug.WriteLine("Response Text From Server: " + invoke.Response.Text)
   End If

Else
   Debug.WriteLine("You are not connected")
End If

[C#]
// First, check to see if currently connected
if(ftp1.Connected)
{
    // Close method returns an Invoke object
    Dart.PowerTCP.Ftp.Invoke invoke;

    // Attempt to Close the connection by using the Close method
    try
    {
        invoke = ftp1.Close();
    }
    catch(Exception ex)
    {
        // An error occurred during the close attempt
        Debug.WriteLine(ex.Message);
    }
    if(ftp1.Connected)
    {
        // For some reason the QUIT command did not work, just perform a "harsh" abort
        ftp1.Dispose();
        Debug.WriteLine("Unable to QUIT, connection aborted");
    }
    else
    {
      Debug.WriteLine("Close successful.");
      Debug.WriteLine("Response Code From Server: " + invoke.Response.Code.ToString());
      Debug.WriteLine("Response Text From Server: " + invoke.Response.Text);
    }
}
else{Debug.WriteLine("You are not connected");}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Delete Method

Ftp.Delete Method

Deletes a file.

Overload List

Deletes a file.

[Visual Basic] Public Function Delete(ByVal String) As FtpFile
[C#] public FtpFile Delete(string);
[C++] public: FtpFile* Delete(String*);
[JScript] public function Delete(String): FtpFile;

Deletes a file or directory tree synchronously.

[Visual Basic] Public Function Delete(ByVal String,ByVal Boolean,ByVal Boolean) As FtpFile()
[C#] public FtpFile[] Delete(string,bool,bool);
[C++] public: FtpFile* Delete(String*,bool,bool) __gc[];
[JScript] public function Delete(String,bool,bool): FtpFile[];

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Delete Method (String)

Ftp.Delete Method (String)

Deletes a file.

[Visual Basic]
Public Function Delete( _
   ByVal fileName As String _
) As FtpFile
[C#]
public FtpFile Delete(
   string fileName
);
[C++]
public: FtpFile* Delete(
   String* fileName
);
[JScript]
public function Delete(
   String fileName
): FtpFile;

Parameters

fileName
Specifies the file to delete.

Return Value

An FtpFile instance that describe the deletion.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.
NotSupportedException | The path format is not supported.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.Delete Overload List


Delete Method (String, Boolean, Boolean)

Ftp.Delete Method (String, Boolean, Boolean)

Deletes a file or directory tree synchronously.

[Visual Basic]
Public Function Delete( _
   ByVal searchPattern As String, _
   ByVal subDirectories As Boolean, _
   ByVal removeEmptyDirectories As Boolean _
) As FtpFile()
[C#]
public FtpFile[] Delete(
   string searchPattern,
   bool subDirectories,
   bool removeEmptyDirectories
);
[C++]
public: FtpFile* Delete(
   String* searchPattern,
   bool subDirectories,
   bool removeEmptyDirectories
)  __gc[];
[JScript]
public function Delete(
   String searchPattern,
   bool subDirectories,
   bool removeEmptyDirectories
): FtpFile[];

Parameters

searchPattern
May be a pathname (with or without wildcards) or a directory (indicated by a trailing slash).
subDirectories
Use true to indicate sub-directories should be searched for files to delete.
removeEmptyDirectories
Use true to indicate that directories that do not contain files should be removed.

Return Value

An array of FtpFile objects that describe the deletion.

Remarks

This method deletes a file, multiple files, or directories from the server synchronously. An array of FtpFile objects are returned from the method, containing data about files deleted. The only data contained within these objects should be the File.RemoteFileName, containing the names of the files deleted, and the File.Status, which should equal DeleteCompleted. All other members of this object should be at their default values.

This method provides a high-level alternative to Ftp.Invoke(Command.Delete). It also expands upon this method by providing support for the deletion of multiple files and directory trees with a single method call.

An empty return array indicates no deletes were attempted.

To perform this method asynchronously, see BeginDelete.

Use the AbortTransfer method to abort the deletion process while maintaining the control connection.

The following table shows some examples of wildcards:

Wildcard | Meaning
* | Delete all files in the directory (or subdirectories).
*.* | Delete all files in the directory (or subdirectories) that have a "." in the filename.
*.txt | Delete all files in the directory (or subdirectories) that end with ".txt".
Test* | Delete all files in the directory (or subdirectories) that start with "Test".
*Test* | Delete all files in the directory (or subdirectories) that contain "Test" in the filename.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.
NotSupportedException | The path format is not supported.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.Delete Overload List


ExpandLocalFiles Method

Ftp.ExpandLocalFiles Method

Gets a string array of local file pathnames that match the wildcard search pattern.

[Visual Basic]
Public Function ExpandLocalFiles( _
   ByVal searchPattern As String, _
   ByVal subDirectories As Boolean _
) As String()
[C#]
public string[] ExpandLocalFiles(
   string searchPattern,
   bool subDirectories
);
[C++]
public: String* ExpandLocalFiles(
   String* searchPattern,
   bool subDirectories
)  __gc[];
[JScript]
public function ExpandLocalFiles(
   String searchPattern,
   bool subDirectories
): String[];

Parameters

searchPattern
Wildcard search pattern of files to get; may include a path.
subDirectories
true if sub-directories should be recursively searched.

Return Value

A string array of local filenames.

Remarks

This method is exposed so you can easily test searchPattern syntax for the Put method and BeginPut method.

The following table shows some examples of wildcards:

Wildcard | Meaning
* | Get all files in the directory.
*.* | Get all files in the directory that have a "." in the filename.
*.txt | Get all files in the directory that end with ".txt".
Test* | Get all files in the directory that start with "Test".
*Test* | Get all files in the directory that contain "Test" in the filename.

This method is useful in several scenarios, for example:

  • Testing searchPattern syntax before transferring multiple files using Put or Ftp.BeginPut.
  • Retrieving a list of local and remote filenames for synchronization purposes.
  • Retrieving a list of local filenames to check for file retrieval success.

Exceptions

Exception Type | Condition
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.
NotSupportedException | The path format is not supported.

Example

The following example demonstrates file synchronization between a local root and a remote root. First, filenames from both the local root and remote root are retrieved using ExpandLocalFiles and ExpandRemoteFiles. Then extraneous files are deleted from the server. Then StoreType is set to Replace to assure that the files on the client will replace those on the server. Finally all files on the local root are put to the server.

[Visual Basic]
Private Sub SynchronizeFiles(ByVal LocalRoot As String, ByVal RemoteRoot As String)

' This sub demonstrates synchronization of files between a local root
' and a root on the FTP server, to get all files on the FTP Server to
' be the same as on the local root

' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Get listing of local files
Dim lFiles() As String
lFiles = Ftp1.ExpandLocalFiles(LocalRoot + "*", False)

' Get a listing of remote files
Dim rFiles() As String
rFiles = Ftp1.ExpandRemoteFiles(RemoteRoot + "*", False)

Dim found As Boolean
Dim i As Integer

' Iterate though list of files on the server and compare to local files.
' If it does not exist locally, delete it
For i = 0 To rFiles.Length - 1

   found = False
   Dim j As Integer

   For j = 0 To lFiles.Length - 1

      ' Create FileInfo objects to parse filename
      Dim rFileInfo As New System.IO.FileInfo(rFiles(i))
      Dim lFileInfo As New System.IO.FileInfo(lFiles(i))

      ' Compare file names
      If (rFileInfo.Name = lFileInfo.Name) Then
         found = True
         Exit For
      End If
   Next

   If Not found Then
      Debug.WriteLine("Deleting " + rFiles(i) + " from server")
      Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Delete, rFiles(i))
   End If
Next

' Now MPUT all files in LocalRoot and both directories are synched

' First, make sure old files are replaced
Ftp1.StoreType = Dart.PowerTCP.Ftp.StoreType.Replace

' Then MPUT
Debug.WriteLine("Uploading all files")
Ftp1.Put(LocalRoot, "*", RemoteRoot, False)
Debug.WriteLine(LocalRoot + " and " + RemoteRoot + " are synched")

' Close the connection
Ftp1.Close()

End Sub

[C#]
private void SynchronizeFiles(string LocalRoot, string RemoteRoot)
{
    // This sub demonstrates synchronization of files between a local root
    // and a root on the FTP server, to get all files on the FTP Server to
    // be the same as on the local root

    // Set server and user properties. This will allow calling of other
    // Ftp Component methods with the log in taking place "behind the scenes"
    ftp1.Server = "MyFTPServer";
    ftp1.Username = "blah";
    ftp1.Password = "mypass";

    // Get list of local files
    string[] lfiles = ftp1.ExpandLocalFiles(LocalRoot + "*", false);

    // Get list of remote files
    string[] rfiles = ftp1.ExpandRemoteFiles(RemoteRoot + "*", false);

    bool found;

    // Iterate though list of files on the server and compare to local files.
    // If it does not exist locally, delete it
    for(int i = 0; i < lfiles.Length; i++)
    {
        found = false;
        for(int j = 0; j < lfiles.Length; j++)
        {
            // Compare filenames
            if(new System.IO.FileInfo(rfiles[i]).Name == new System.IO.FileInfo(lfiles[j]).Name)
            {
                found = true;
                break;
            }
        }

        if(!found) // Delete the file from the server.
        {
            Debug.WriteLine("Deleting " + rfiles[i] + " from server");
            ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Delete, rfiles[i]);
        }
    }

    // Now just MPUT all files in the local root and everything is synched.

    // First, make sure old files are replaced
    ftp1.StoreType = Dart.PowerTCP.Ftp.StoreType.Replace;

    // Then MPUT
    Debug.WriteLine("Uploading all files");
    ftp1.Put(LocalRoot, "*", RemoteRoot, false);
    Debug.WriteLine(LocalRoot + " and " + RemoteRoot + " are synched.");

    // Close connection
    ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


ExpandRemoteFiles Method

Ftp.ExpandRemoteFiles Method

Gets a string array of remote file pathnames that match the wildcard search pattern.

[Visual Basic]
Public Function ExpandRemoteFiles( _
   ByVal searchPattern As String, _
   ByVal subDirectories As Boolean _
) As String()
[C#]
public string[] ExpandRemoteFiles(
   string searchPattern,
   bool subDirectories
);
[C++]
public: String* ExpandRemoteFiles(
   String* searchPattern,
   bool subDirectories
)  __gc[];
[JScript]
public function ExpandRemoteFiles(
   String searchPattern,
   bool subDirectories
): String[];

Parameters

searchPattern
Wildcard search pattern of files to get; may include a path.
subDirectories
true if sub-directories should be recursively searched.

Return Value

A string array of remote filenames.

Remarks

This method is exposed so you can easily test searchPattern syntax for the Get method and BeginGet method.

The following table shows some examples of wildcards:

Wildcard | Meaning
* | Get all files in the directory.
*.* | Get all files in the directory that have a "." in the filename.
*.txt | Get all files in the directory that end with ".txt".
Test* | Get all files in the directory that start with "Test".
*Test* | Get all files in the directory that contain "Test" in the filename.

This method is useful in several scenarios, for example:

  • Testing searchPattern syntax before transferring multiple files using Get or Ftp.BeginGet.
  • Retrieving a list of local and remote filenames for synchronization purposes.
  • Retrieving a list of remote filenames to check for file storage success.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.
NotSupportedException | The path format is not supported.

Example

The following example demonstrates file synchronization between a local root and a remote root. First, filenames from both the local root and remote root are retrieved using ExpandLocalFiles and ExpandRemoteFiles. Then extraneous files are deleted from the server. Then StoreType is set to Replace to assure that the files on the client will replace those on the server. Finally all files on the local root are put to the server.

[Visual Basic]
Private Sub SynchronizeFiles(ByVal LocalRoot As String, ByVal RemoteRoot As String)

' This sub demonstrates synchronization of files between a local root
' and a root on the FTP server, to get all files on the FTP Server to
' be the same as on the local root

' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Get listing of local files
Dim lFiles() As String
lFiles = Ftp1.ExpandLocalFiles(LocalRoot + "*", False)

' Get a listing of remote files
Dim rFiles() As String
rFiles = Ftp1.ExpandRemoteFiles(RemoteRoot + "*", False)

Dim found As Boolean
Dim i As Integer

' Iterate though list of files on the server and compare to local files.
' If it does not exist locally, delete it
For i = 0 To rFiles.Length - 1

   found = False
   Dim j As Integer

   For j = 0 To lFiles.Length - 1

      ' Create FileInfo objects to parse filename
      Dim rFileInfo As New System.IO.FileInfo(rFiles(i))
      Dim lFileInfo As New System.IO.FileInfo(lFiles(i))

      ' Compare file names
      If (rFileInfo.Name = lFileInfo.Name) Then
         found = True
         Exit For
      End If
   Next

   If Not found Then
      Debug.WriteLine("Deleting " + rFiles(i) + " from server")
      Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Delete, rFiles(i))
   End If
Next

' Now MPUT all files in LocalRoot and both directories are synched

' First, make sure old files are replaced
Ftp1.StoreType = Dart.PowerTCP.Ftp.StoreType.Replace

' Then MPUT
Debug.WriteLine("Uploading all files")
Ftp1.Put(LocalRoot, "*", RemoteRoot, False)
Debug.WriteLine(LocalRoot + " and " + RemoteRoot + " are synched")

' Close the connection
Ftp1.Close()

End Sub

[C#]
private void SynchronizeFiles(string LocalRoot, string RemoteRoot)
{
    // This sub demonstrates synchronization of files between a local root
    // and a root on the FTP server, to get all files on the FTP Server to
    // be the same as on the local root

    // Set server and user properties. This will allow calling of other
    // Ftp Component methods with the log in taking place "behind the scenes"
    ftp1.Server = "MyFTPServer";
    ftp1.Username = "blah";
    ftp1.Password = "mypass";

    // Get list of local files
    string[] lfiles = ftp1.ExpandLocalFiles(LocalRoot + "*", false);

    // Get list of remote files
    string[] rfiles = ftp1.ExpandRemoteFiles(RemoteRoot + "*", false);

    bool found;

    // Iterate though list of files on the server and compare to local files.
    // If it does not exist locally, delete it
    for(int i = 0; i < lfiles.Length; i++)
    {
        found = false;
        for(int j = 0; j < lfiles.Length; j++)
        {
            // Compare filenames
            if(new System.IO.FileInfo(rfiles[i]).Name == new System.IO.FileInfo(lfiles[j]).Name)
            {
                found = true;
                break;
            }
        }

        if(!found) // Delete the file from the server.
        {
            Debug.WriteLine("Deleting " + rfiles[i] + " from server");
            ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Delete, rfiles[i]);
        }
    }

    // Now just MPUT all files in the local root and everything is synched.

    // First, make sure old files are replaced
    ftp1.StoreType = Dart.PowerTCP.Ftp.StoreType.Replace;

    // Then MPUT
    Debug.WriteLine("Uploading all files");
    ftp1.Put(LocalRoot, "*", RemoteRoot, false);
    Debug.WriteLine(LocalRoot + " and " + RemoteRoot + " are synched.");

    // Close connection
    ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Get Method

Ftp.Get Method

Synchronously get a stream that can be used to read the FTP data connection.

Overload List

Synchronously get a stream that can be used to read the FTP data connection.

[Visual Basic] Public Function Get(ByVal String,ByVal Long) As SegmentedStream
[C#] public SegmentedStream Get(string,long);
[C++] public: SegmentedStream* Get(String*,__int64);
[JScript] public function Get(String,long): SegmentedStream;

Get a file from the FTP server synchronously, storing the retrieved data in a Stream object.

[Visual Basic] Public Function Get(ByVal String,ByVal Stream) As FtpFile
[C#] public FtpFile Get(string,Stream);
[C++] public: FtpFile* Get(String*,Stream*);
[JScript] public function Get(String,Stream): FtpFile;

Get a single file from the server synchronously.

[Visual Basic] Public Function Get(ByVal String,ByVal String) As FtpFile
[C#] public FtpFile Get(string,string);
[C++] public: FtpFile* Get(String*,String*);
[JScript] public function Get(String,String): FtpFile;

Get multiple files from the server synchronously.

[Visual Basic] Public Function Get(ByVal String,ByVal String,ByVal String,ByVal Boolean,ByVal Boolean) As FtpFile()
[C#] public FtpFile[] Get(string,string,string,bool,bool);
[C++] public: FtpFile* Get(String*,String*,String*,bool,bool) __gc[];
[JScript] public function Get(String,String,String,bool,bool): FtpFile[];

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Get Method (String, Int64)

Ftp.Get Method (String, Int64)

Synchronously get a stream that can be used to read the FTP data connection.

[Visual Basic]
Public Function Get( _
   ByVal remoteFileName As String, _
   ByVal restartMarker As Long _
) As SegmentedStream
[C#]
public SegmentedStream Get(
   string remoteFileName,
   long restartMarker
);
[C++]
public: SegmentedStream* Get(
   String* remoteFileName,
   __int64 restartMarker
);
[JScript]
public function Get(
   String remoteFileName,
   long restartMarker
): SegmentedStream;

Parameters

remoteFileName
Source pathname of the file on the server.
restartMarker
Restart location within file on the server.

Return Value

Instance of a SegmentedStream.

Remarks

This method synchronously gets a SegmentedStream that can be used to read the FTP data connection. Simply call Read or BeginRead to read directly from the data connection.

Since there is no local file to test for an automatic restart, you can specify a restart marker location within the remote file, and the stream will start at that byte offset location within the remote file.

To read from the data connection asynchronously, use BeginGet.

This method differs from the Ftp.Get(String, Stream) method in that Ftp.Get(String, Stream) is used to retrieve a file as a filled stream.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument is null

Example

The following example demonstrates reading from the data connection. In this example, a file of fixed records is read into a ListView. The file read is assumed to have records delimited by CRLF and fields delimited by commas.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in out taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set up ListView

' Show gridlines
ListView1.GridLines = True

' Set view to details
ListView1.View = View.Details

' Use Get to return a SegmentedStream. This is a data stream that can be used to read the data connection.
Dim stream1 As Dart.PowerTCP.Ftp.SegmentedStream

' Open a stream
Try
   stream1 = Ftp1.Get("records.txt", 0)
Catch ex As Exception
   Debug.WriteLine(ex.Message)
   Return
End Try

' Got this far, assume success
Dim offset As Integer = 0

' Keep reading until the end of the stream.
While (stream1.Available > 0)

   ' This variable is to write column headings on the first pass
   Dim firstline As Boolean = False

   ' Check offset to determine if this is the first line
   If (offset = 0) Then
      firstline = True
   Else
      firstline = False
   End If

   ' Create a byte array for this file no line will exceed 100 bytes
   ' so it is safe to declare a fixed size.
   Dim line(100) As Byte

   ' Create delimiter char[]. Data will be read from the stream until
   ' this is encountered
   Dim d() As Byte = {13, 10}

   ' Read a line
   offset = stream1.Read(line, d)

   ' The line should have comma-delimited fields. Split the line.
   Dim p() As Char = {","}

   Dim fields() As String
   fields = System.Text.Encoding.ASCII.GetString(line).Split(p)

   ' Check to see if it is the first line (the first line contains column
   ' headings) and create headings on the list view.

   If (firstline) Then
      Dim i As Integer
      For i = 0 To fields.Length - 1
         ListView1.Columns.Add(fields(i), 100, HorizontalAlignment.Left)
      Next
   Else
      ' If it is not the first line, simply add a new data row
      ListView1.Items.Add(New ListViewItem(fields))
   End If
End While

' Close the stream
stream1.Close()

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set up ListView

// Show gridlines.
listView1.GridLines = true;

// Set View to Details
listView1.View = View.Details;

// Use Get to return a SegmentedStream. This is a data stream that can be used to read the data connection.
Dart.PowerTCP.Ftp.SegmentedStream stream1;

// Open a stream
try
{
    stream1 = ftp1.Get("records.txt", 0);
}
catch(Exception ex)
{
    Debug.WriteLine(ex.Message);
    return;
}

// Got this far, assume success.
int offset = 0;

// Keep reading until the end of the stream.
while (stream1.Available > 0)
{

    // This is to write column headings on the first pass
    bool firstline = false;

    // Check offset to determine if this is the first line
    if(offset == 0)
        firstline = true;
    else
        firstline = false;

    // Create a byte array, for this file no line will exceed 100 bytes
    // so it is safe to declare a fixed size.
    byte[] line = new byte[100];

    // Create delimiter char[]. Data will be read from the stream until
    // this is encountered
    byte [] d = {13, 10};

    // Read a line
    offset = stream1.Read(line, d);

    // The line should have comma-delimited fields. Split the line.
    char[] p = {','};
    string[] fields = System.Text.Encoding.ASCII.GetString(line).Split(p);

    // Check to see if it is the first line (the first line contains column
    // headings) and create headings on the list view.
    if(firstline)
    {
        for(int i = 0; i < fields.Length; i++)
            listView1.Columns.Add(fields[i], 100, System.Windows.Forms.HorizontalAlignment.Left);
    }
        // If it is not firstline, simply create a new data row.
    else
    {
        listView1.Items.Add(new ListViewItem(fields));
    }
}

// Close the stream
stream1.Close();

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.Get Overload List


Get Method (String, Stream)

Ftp.Get Method (String, Stream)

Get a file from the FTP server synchronously, storing the retrieved data in a Stream object.

[Visual Basic]
Public Function Get( _
   ByVal remoteFileName As String, _
   ByVal localStream As Stream _
) As FtpFile
[C#]
public FtpFile Get(
   string remoteFileName,
   Stream localStream
);
[C++]
public: FtpFile* Get(
   String* remoteFileName,
   Stream* localStream
);
[JScript]
public function Get(
   String remoteFileName,
   Stream localStream
): FtpFile;

Parameters

remoteFileName
Source pathname of the file on the server.
localStream
Initialized destination stream for the file.

Return Value

An FtpFile object that describes the transfer.

Remarks

This method synchronously gets a file from the server as a Stream object. Standard usage would involve first creating a stream, then passing it into the Get method, then using the stream within your application. An FtpFile object is returned from the method, containing data about the transfer such as remote filename and amount of bytes transferred.

For more information on synchronous stream transfer, see the topic Transferring Streams Synchronously Overview .

To get a file as a Stream object asynchronously use the BeginGet method.

This method differs from the Ftp.Get(String, Int64) method in that Ftp.Get(String, Int64) is used to read directly from the open data connection.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ObjectDisposedException | Cannot access a closed stream.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.

Example

The following example demonstrates how to get a file with the result returned as a stream to use within the application. In this example, the file will be displayed in a TextBox, so an ASCII file would work best for this example.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToGet As String = "file1.txt"

' File will be returned as a stream. Create the stream to pass into the method.
Dim stream1 As New System.IO.MemoryStream()

' Get returns an FtpFile object describing the file. Create the object.
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to get file " + FileToGet)

' Get the file, passing in the MemoryStream
Try
   file = Ftp1.Get(FileToGet, stream1)
Catch ex As Exception
   Debug.WriteLine(ex.Message)
   Return
End Try

' Success! Create new byte array to read data into.
Dim data(stream1.Length) As Byte

' Attempt to read from stream
stream1.Position = 0
stream1.Read(data, 0, stream1.Length)

' Display data in TextBox
TextBox1.Text = System.Text.Encoding.ASCII.GetString(data)

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToGet = "file.txt";

// File will be returned as a stream. Create the stream to pass into the method.
System.IO.MemoryStream stream1 = new System.IO.MemoryStream();

// Get returns an FtpFile object describing the file. Create the object.
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to get file " + FileToGet);

// Get the file, passing in the MemoryStream
try
{
    file = ftp1.Get(FileToGet, stream1);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Create new byte array to read data into.
byte[] data = new byte[stream1.Length];

// Attempt to read from stream
stream1.Position = 0;
stream1.Read(data, 0, (int)stream1.Length);

// Display data in a TextBox
textBox1.Text = System.Text.Encoding.ASCII.GetString(data);

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.Get Overload List


Get Method (String, String)

Ftp.Get Method (String, String)

Get a single file from the server synchronously.

[Visual Basic]
Public Function Get( _
   ByVal remoteFileName As String, _
   ByVal localFileName As String _
) As FtpFile
[C#]
public FtpFile Get(
   string remoteFileName,
   string localFileName
);
[C++]
public: FtpFile* Get(
   String* remoteFileName,
   String* localFileName
);
[JScript]
public function Get(
   String remoteFileName,
   String localFileName
): FtpFile;

Parameters

remoteFileName
Source pathname of the file on the server.
localFileName
Local destination pathname for the file.

Return Value

An FtpFile object that describes the transfer.

Remarks

This method synchronously gets a file from the server. An FtpFile object is returned from the method, containing data about the transfer such as local and remote filenames and amount of bytes transferred.

For more information on synchronous file transfer, see the topic Retrieving Files Synchronously Overview.

To get a file asynchronously, use BeginGet.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.

Example

The following example demonstrates a simple Get.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in out taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToGet As String = "myfile.txt"

' Put method returns an FtpFile object containing information about the file transfer
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to get file " + FileToGet)

 ' Get the file, saving it to the app path with the same filename
Try
   file = Ftp1.Get(FileToGet, Application.StartupPath + "\" + FileToGet)
Catch ex As Exception
   Debug.WriteLine(ex.Message)
   Return
End Try

' Success! Display info about the file.
Debug.WriteLine("Successfully retrieved file " + file.RemoteFileName)

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToGet = "file.txt";

// Put method returns an FtpFile object containing information about the file transfer
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to get file " + FileToGet);

// Get the file, saving it to the application path with the same filename.
try
{
    file = ftp1.Get(FileToGet, Application.StartupPath + "\\" + FileToGet);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file.
Debug.WriteLine("Successfully retrieved file " + file.RemoteFileName);

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.Get Overload List


Get Method (String, String, String, Boolean, Boolean)

Ftp.Get Method (String, String, String, Boolean, Boolean)

Get multiple files from the server synchronously.

[Visual Basic]
Public Function Get( _
   ByVal remoteRoot As String, _
   ByVal searchPattern As String, _
   ByVal localRoot As String, _
   ByVal subDirectories As Boolean, _
   ByVal synchronize As Boolean _
) As FtpFile()
[C#]
public FtpFile[] Get(
   string remoteRoot,
   string searchPattern,
   string localRoot,
   bool subDirectories,
   bool synchronize
);
[C++]
public: FtpFile* Get(
   String* remoteRoot,
   String* searchPattern,
   String* localRoot,
   bool subDirectories,
   bool synchronize
)  __gc[];
[JScript]
public function Get(
   String remoteRoot,
   String searchPattern,
   String localRoot,
   bool subDirectories,
   bool synchronize
): FtpFile[];

Parameters

remoteRoot
Source root directory on the server.
searchPattern
Wildcard search pattern of files to get; may include a path.
localRoot
Destination root directory on the client.
subDirectories
true if sub-directories should be recursively copied.
synchronize
true if files of the same size that already exist locally should not be copied.

Return Value

An array of FtpFile objects that describe the transfer.

Remarks

This method gets multiple files from the server synchronously. An array of FtpFile objects are returned from the method, containing data about the transfer such as local and remote filenames and amount of bytes transferred.

To get multiple files asynchronously use BeginGet.

If localRoot exists, the files will be saved to the directory path specified. If it does not exist, the directory will be created.

The Ftp.Get method gets all files specified in remoteRoot (and subdirectories if subDirectories is true) that meet the wildcard requirement specified in searchPattern. The following table shows some examples of wildcards:

Wildcard | Meaning
* | Get all files in the directory.
*.* | Get all files in the directory that have a "." in the filename.
*.txt | Get all files in the directory that end with ".txt".
Test* | Get all files in the directory that start with "Test".
*Test* | Get all files in the directory that contain "Test" in the filename.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.
NotSupportedException | The path format is not supported.

Example

The following example demonstrates how to retrieve multiple files using the Get method.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim RemoteRoot As String = "directory1"

' When using the Get method specifying a directory (MGET) an array of FtpFiles is returned
Dim files() As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to MGET all files in " + RemoteRoot)

' Get files. Files will be saved in the application path\newfiles.
Try
   files = Ftp1.Get(RemoteRoot, "*", Application.StartupPath + "\newfiles", False)
Catch ex As Exception
   Debug.WriteLine(ex.Message)
   Return
End Try

' Success! Iterate through the FtpFile object array and display data about each file retrieved.
Dim file As Dart.PowerTCP.Ftp.FtpFile
For Each file In files
   Debug.WriteLine("Successfully retrieved file " + file.RemoteFileName)
Next

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string RemoteRoot = "directory1";

// When using the Get method specifying a directory (MGET) an array of FtpFiles is returned
Dart.PowerTCP.Ftp.FtpFile[] files;

Debug.WriteLine("Attempting to MGET all files in " + RemoteRoot);

// Get files. Files will be saved in application path\newfiles.
try
{
    files = ftp1.Get(RemoteRoot, "*", Application.StartupPath + "\\newfiles", false);
}
catch(Exception ex)
{
    Debug.WriteLine(ex.Message);
    return;
}

// Success! Iterate through the FtpFile object array and display data about each file retrieved.
foreach(Dart.PowerTCP.Ftp.FtpFile file in files)
    Debug.WriteLine("Successfully retrieved file " + file.RemoteFileName);

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.Get Overload List


GetDirectory Method

Ftp.GetDirectory Method

Gets the server's working directory.

[Visual Basic]
Public Function GetDirectory() As String
[C#]
public string GetDirectory();
[C++]
public: String* GetDirectory();
[JScript]
public function GetDirectory(): String;

Return Value

A string representing the working directory.

Remarks

This method uses Ftp.Invoke(FtpCommand.PrintDir) and parses the directory from the response. To perform this operation asynchronously, use the BeginInvoke method and parse the response.

This method is helpful for retrieving the working directory. The benefit of using GetDirectory over using Invoke(FtpCommand.PrintDir) is that when using GetDirectory, the response returned is a parsed string. For example, if the current directory is "/home/mydir", using the GetDirectory method would return "home/mydir" where the Invoke(FtpCommand.PrintDir) method might return something like "The current directory is home/mydir".

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).

Example

The following example demonstrates code that might be used as FTP client login. It retrieves and displays the root listing, and gets and displays the current directory.

[Visual Basic]
Private Sub Login()

   ' Set server and user properties. This will allow calling of other
   ' Ftp Component methods with the log in taking place "behind the scenes"
   Ftp1.Server = "MyFTPServer"
   Ftp1.Username = "blah"
   Ftp1.Password = "mypass"

   ' Retrieve file list. Listing details will be contained in the Listing Object
   Dim list As Dart.PowerTCP.Ftp.Listing
   list = Ftp1.List("", True)

   ' Begin setting up the ListView diplay

   ' Show gridlines.
   ListView1.GridLines = True

   ' Set View to Details
   ListView1.View = View.Details

   ' Add column headings for file name, size, and date.
   ListView1.Columns.Add("File Name", 100, HorizontalAlignment.Left)
   ListView1.Columns.Add("File Size", 100, HorizontalAlignment.Left)
   ListView1.Columns.Add("File Timestamp", 100, HorizontalAlignment.Left)

   ' Iterate through the listing, adding a row to the ListBox for each
   Dim le As Dart.PowerTCP.Ftp.ListEntry
   For Each le In list

      ' Display files only
      If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then

         Dim cols() As String = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp}
         ListView1.Items.Add(New ListViewItem(cols))
      End If

   Next

   ' Get current directory
   Label1.Text = "Current directory " + Ftp1.GetDirectory()

End Sub

[C#]
private void Login()
{
    // Set server and user properties. This will allow us to call other
    // Ftp Component methods with the log in taking place "behind the scenes"
    ftp1.Server = "MyFTPServer";
    ftp1.Username = "blah";
    ftp1.Password = "mypass";

    // Retrieve file list. Listing details will be contained in
    // the Listing Object
    Dart.PowerTCP.Ftp.Listing list = ftp1.List("", true);

    // Begin setting up the ListView diplay

    // Show gridlines.
    listView1.GridLines = true;

    // Set View to Details
    listView1.View = View.Details;

    // Add column headings for file name, size, and date.
    listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

    // Iterate through the listing, adding a row to the ListBox for each
    foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
    {
        // Display files only
        if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
        {
            string[] cols = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp};
            listView1.Items.Add(new ListViewItem(cols));
        }
    }

    // Get current directory
    label1.Text = "Current directory " + ftp1.GetDirectory();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


GetSize Method

Ftp.GetSize Method

Gets the size of any file.

[Visual Basic]
Public Function GetSize( _
   ByVal remoteFileName As String _
) As Long
[C#]
public long GetSize(
   string remoteFileName
);
[C++]
public: __int64 GetSize(
   String* remoteFileName
);
[JScript]
public function GetSize(
   String remoteFileName
): long;

Return Value

An integer representing the number of bytes that would be sent if the file were to be retrieved. This could be larger than the actual file size (due to CR/LF encoding for type ASCII files).

Remarks

This method uses Invoke(FtpCommand.Size) and parses the size from the response. To perform this operation asynchronously, use the BeginInvoke method and parse the response.

WARNING: Under NT 4.0, when the SIZE command is followed by the DELE command (on the same file), unexpected results may occur.

This method is helpful for retrieving the actual size of any file. This is useful because often the size reported by the server will be less than the actual file size because some characters are not taken into account in the listing. This method is also helpful because size is returned as a parsed integer, allowing comparison to take place such as:

if(ftp1.GetSize("myfile.txt") > 10)
    MessageBox.Show("This file is bigger than 10 bytes.");

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).

Example

The following example demonstrates use of the GetSize method to get the actual file size from the server.

[Visual Basic]
' Sometimes the file size in the listing reported by the FTP Server
' will differ from the actual file size (because characters such as CRLF
' are not taken into account). For this reason, GetSize may be useful as
' it issues the SIZE command which (if supported) returns the actual file size.

' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Get full listing
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*.*", True)

' Iterate through all of the Entries
Dim le As Dart.PowerTCP.Ftp.ListEntry
For Each le In list
   If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then
      Debug.WriteLine("Filename: " + le.Name)

      ' Display the file size reported by the FTP server in the listing
      Debug.WriteLine("Size reported by list: " + le.Size.ToString())

      ' Get and report the actual file size.
      Debug.WriteLine("Actual file size: " + Ftp1.GetSize(le.Name).ToString())
   End If

Next

[C#]
/* Sometimes the file size in the listing reported by the FTP Server
 * will differ from the actual file size (because characters such as CRLF
 * are not taken into account). For this reason, GetSize may be useful as
 * it issues the SIZE command which (if supported) returns the actual file size.
*/

// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Get full listing
Dart.PowerTCP.Ftp.Listing list = ftp1.List("*.*", true);

// Iterate through all of the Entries
foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
{
   if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
   {
       Debug.WriteLine("Filename: " + le.Name);

       // Display the file size reported by the FTP server in the listing
       Debug.WriteLine("Size reported by list: " + le.Size.ToString());

       // Get and report the actual file size.
       Debug.WriteLine("Actual file size: " + ftp1.GetSize(le.Name));
   }
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Invoke Method

Ftp.Invoke Method

Send an FTP command (without a command modifier) synchronously.

Overload List

Send an FTP command (without a command modifier) synchronously.

[Visual Basic] Public Function Invoke(ByVal FtpCommand) As Invoke
[C#] public Invoke Invoke(FtpCommand);
[C++] public: Invoke* Invoke(FtpCommand);
[JScript] public function Invoke(FtpCommand): Invoke;

Send an FTP command (with a command modifier) synchronously.

[Visual Basic] Public Function Invoke(ByVal FtpCommand,ByVal String) As Invoke
[C#] public Invoke Invoke(FtpCommand,string);
[C++] public: Invoke* Invoke(FtpCommand,String*);
[JScript] public function Invoke(FtpCommand,String): Invoke;

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Invoke Method (FtpCommand)

Ftp.Invoke Method (FtpCommand)

Send an FTP command (without a command modifier) synchronously.

[Visual Basic]
Public Function Invoke( _
   ByVal command As FtpCommand _
) As Invoke
[C#]
public Invoke Invoke(
   FtpCommand command
);
[C++]
public: Invoke* Invoke(
   FtpCommand command
);
[JScript]
public function Invoke(
   FtpCommand command
): Invoke;

Parameters

command
FTP command to send.

Return Value

An FtpInvoke object describing the request/response.

Remarks

Use this method to send low-level FTP commands to your server. See the SendCommand method for an even simpler technique.

To invoke a command asynchronously, use BeginInvoke.

For more information about synchronously sending commands, see the topic Sending Commands Synchronously.

This method sends a command WITHOUT a modifier to the server (ex, NOOP or PWD). For example, use this method if you want to send an asynchronous "NOOP" request to the server. FtpCommand.NoOp would be used as the command parameter. This method differs from the Ftp.Invoke(FtpCommand, String) method in that the Ftp.Invoke(FtpCommand, String) method is used to send commands that require an additional parameter (for example, HELP or CWD).

If you wish to send your own command, see Invoke(FtpCommand, String).

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).

Example

The following example demonstrates using Invoke to send a command.

[Visual Basic]
' Set server and user properties. This will allow us to call other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Invoke a command
Dim invoke as Dart.PowerTCP.Ftp.Invoke
Try
   invoke = Ftp1.Invoke(FtpCommand.NoOp)
Catch ex as Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Request/Response messages: " + invoke.ToString())

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Invoke a command
Dart.PowerTCP.Ftp.Invoke invoke;
try
{
   invoke = ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.NoOp);
}
catch (Exception ex)
{
    Debug.WriteLine("Error: " + ex.ToString());
    return;
}

// Success
Debug.WriteLine("Request/Response messages: " + invoke.ToString());

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.Invoke Overload List


Invoke Method (FtpCommand, String)

Ftp.Invoke Method (FtpCommand, String)

Send an FTP command (with a command modifier) synchronously.

[Visual Basic]
Public Function Invoke( _
   ByVal command As FtpCommand, _
   ByVal modifier As String _
) As Invoke
[C#]
public Invoke Invoke(
   FtpCommand command,
   string modifier
);
[C++]
public: Invoke* Invoke(
   FtpCommand command,
   String* modifier
);
[JScript]
public function Invoke(
   FtpCommand command,
   String modifier
): Invoke;

Parameters

command
FTP command to send.
modifier
Command modifier appended to command.

Return Value

An FtpInvoke object describing the request/response.

Remarks

Use this method to send low-level FTP commands to your server. See the SendCommand method for an even simpler technique.

To invoke a command asynchronously, use BeginInvoke.

For more information about synchronously sending commands, see the topic Sending Commands Synchronously.

This method sends a command with a modifier to the server (ex HELP or CWD). For example, use this method if you want to send a synchronous "HELP" request to the server. FtpCommand.Help would be used as the command parameter and the item you wish to receive help on would be used as the modifier parameter. This method differs from the Invoke(FtpCommand) method in that the Invoke(FtpCommand) method is used to send commands that DO NOT require an additional parameter (for example, NOOP or PWD).

If you wish to send your own command, use FtpCommand.Null, and specify your entire command as the modifier. An example would be:

 Invoke(FtpCommand.Null, "MYCOMMAND file1.txt").

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).

Example

The following example demonstrates using Invoke to send a custom command.

[Visual Basic]
' Set server and user properties. This will allow us to call other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Invoke a command
Dim invoke as Dart.PowerTCP.Ftp.Invoke

' Use Invoke(FtpCommand.Null) to send a proprietary command

Try
   invoke = Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "MYFILECOMMAND file1.txt")
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success. Print response.
Debug.WriteLine("Response from server : " + invoke.Response.Text)
Ftp1.Close()

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Use Invoke(FtpCommand.Null) to send a proprietary command
try
{
   Dart.PowerTCP.Ftp.Invoke invoke = ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "MYFILECOMMAND file1.txt");
}
catch(Exception ex)
{
   Debug.WriteLine("Error: " + ex.Message);
   return;
}

// Success. Print response
Debug.WriteLine("Response from server : " + invoke.Response.Text);

// Close connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.Invoke Overload List


List Method

Ftp.List Method

Retrieve a file listing from the server synchronously.

[Visual Basic]
Public Function List( _
   ByVal searchPattern As String, _
   ByVal full As Boolean _
) As Listing
[C#]
public Listing List(
   string searchPattern,
   bool full
);
[C++]
public: Listing* List(
   String* searchPattern,
   bool full
);
[JScript]
public function List(
   String searchPattern,
   bool full
): Listing;

Parameters

searchPattern
Filename for the listing, which may include wildcards.
full
true for a full listing, or false for a named list.

Return Value

Instance of a Listing object.

Remarks

This method returns a Listing object, which represents an FTP listing.

Specify a full listing for complete listing information, but if the server's listing format is not recognized as standard UNIX or DOS, you will have to parse out each line yourself. For an example on how to do this, see the topic Parsing An Unknown Listing Type. Use an abbreviated name list if you only need filename information.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).

Example

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Retrieve file list. Listing details will be contained in the Listing Object
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Begin setting up the ListView diplay
' Show gridlines.
ListView1.GridLines = True

' Set View to Details
ListView1.View = View.Details

' Add column headings for file name, size, and date.
ListView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left)

' Iterate through the listing, adding a row to the ListBox for each
Dim le As Dart.PowerTCP.Ftp.ListEntry
For Each le In list

   ' Display files only
   If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then
      Dim cols() As String = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp}
      ListView1.Items.Add(New ListViewItem(cols))
   End If
Next

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Retrieve file list. Listing details will be contained in the Listing Object
Dart.PowerTCP.Ftp.Listing list = ftp1.List("*", true);

// Begin setting up the ListView diplay

// Show gridlines.
listView1.GridLines = true;

// Set View to Details
listView1.View = View.Details;

// Add column headings for file name, size, and date.
listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

// Iterate through the listing, adding a row to the ListBox for each
foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
{
    // Display files only
    if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
    {
        string[] cols = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp};
        listView1.Items.Add(new ListViewItem(cols));
    }
}

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Put Method

Ftp.Put Method

Synchronously store a stream on the server as a file.

Overload List

Synchronously store a stream on the server as a file.

[Visual Basic] Public Function Put(ByVal Stream,ByVal String) As FtpFile
[C#] public FtpFile Put(Stream,string);
[C++] public: FtpFile* Put(Stream*,String*);
[JScript] public function Put(Stream,String): FtpFile;

Synchronously get a stream that can be used to write to the data connection.

[Visual Basic] Public Function Put(ByVal String,ByVal Long) As SegmentedStream
[C#] public SegmentedStream Put(string,long);
[C++] public: SegmentedStream* Put(String*,__int64);
[JScript] public function Put(String,long): SegmentedStream;

Store a single file to the server synchronously.

[Visual Basic] Public Function Put(ByVal String,ByVal String) As FtpFile
[C#] public FtpFile Put(string,string);
[C++] public: FtpFile* Put(String*,String*);
[JScript] public function Put(String,String): FtpFile;

Synchronously put multiple files to the server.

[Visual Basic] Public Function Put(ByVal String,ByVal String,ByVal String,ByVal Boolean,ByVal Boolean) As FtpFile()
[C#] public FtpFile[] Put(string,string,string,bool,bool);
[C++] public: FtpFile* Put(String*,String*,String*,bool,bool) __gc[];
[JScript] public function Put(String,String,String,bool,bool): FtpFile[];

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Put Method (Stream, String)

Ftp.Put Method (Stream, String)

Synchronously store a stream on the server as a file.

[Visual Basic]
Public Function Put( _
   ByVal localStream As Stream, _
   ByVal remoteFileName As String _
) As FtpFile
[C#]
public FtpFile Put(
   Stream localStream,
   string remoteFileName
);
[C++]
public: FtpFile* Put(
   Stream* localStream,
   String* remoteFileName
);
[JScript]
public function Put(
   Stream localStream,
   String remoteFileName
): FtpFile;

Parameters

localStream
Source stream for the file.
remoteFileName
Remote destination pathname for the file on the server.

Return Value

FtpFile object that describes the transfer.

Remarks

Use this method to synchronously store a file to the server using a stream. To do this asynchronously, use BeginPut.

For more information on synchronous stream transfer, see the topic Transferring Streams Synchronously Overview.

This method differs from the Ftp.Put(String, Int64) method in that Ftp.Put(String, Int64) is used to write to the open data connection.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ObjectDisposedException | Cannot access a closed stream.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.

Example

The following example demonstrates how to synchronously store a stream as a file on the server.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Create a MemoryStream to hold data to be stored on the server
Dim stream1 As New System.IO.MemoryStream()

' Create a byte array to hold data to be written to the stream.
Dim data() As Byte

' Fill the byte array with some text
data = System.Text.ASCIIEncoding.ASCII.GetBytes("Data to be stored on the FTP server.")

' Write to the stream
stream1.Write(data, 0, data.Length)

' Put method returns an FtpFile object containing information about the file
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to store stream")

' Store the data on the server under the name "stream.txt"
Try
   file = Ftp1.Put(stream1, "stream.txt")
Catch ex As Exception
   Debug.WriteLine(ex.Message)
   Return
End Try

' Success! Display information about the file on the server
Debug.WriteLine("Successfully stored stream. Filename on server: " + file.RemoteFileName)

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Create a MemoryStream to hold data to be stored on the server
System.IO.MemoryStream stream1 = new System.IO.MemoryStream();

// Create a byte array containing the data to be written to the stream
byte[] data = System.Text.Encoding.ASCII.GetBytes("Data to be stored on the FTP server.");

// Write to the stream
stream1.Write(data, 0, data.Length);

// Put method returns an FtpFile object containing information about the file
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store stream");

// Store the data on the server under the name "stream.txt"
try
{
   file = ftp1.Put(stream1, "stream.txt");
}
catch(Exception ex)
{
   Debug.WriteLine(ex.Message);
   return;
}

// Success! Display information about the file on the server.
Debug.WriteLine("Successfully Put stream. Filename on server: " + file.RemoteFileName);

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.Put Overload List


Put Method (String, Int64)

Ftp.Put Method (String, Int64)

Synchronously get a stream that can be used to write to the data connection.

[Visual Basic]
Public Function Put( _
   ByVal remoteFileName As String, _
   ByVal restartMarker As Long _
) As SegmentedStream
[C#]
public SegmentedStream Put(
   string remoteFileName,
   long restartMarker
);
[C++]
public: SegmentedStream* Put(
   String* remoteFileName,
   __int64 restartMarker
);
[JScript]
public function Put(
   String remoteFileName,
   long restartMarker
): SegmentedStream;

Parameters

remoteFileName
Remote destination pathname for the file on the server.
restartMarker
Restart location within file on the server.

Return Value

Instance of a SegmentedStream.

Remarks

This method will return a SegmentedStream object which can be used to write to the data connection. Simply call Write or SegmentedStream.BeginWrite to write directly to the data stream.

Since there is no local file to test for an automatic restart, you can specify a restart marker location within the remote file, and the stream will start writing at that byte offset location within the remote file.

To asynchronously get a stream that can be used to write to the FTP data connection use BeginPut.

This method differs from the Ftp.Put(String, Stream) method in that Ftp.Put(String, Stream) is used to retrieve a file as a filled stream. .

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.

Example

This example demonstrates writing data to the data connection.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFtpServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' When writing to the data connection, the Put method returns a SegmentedStream object
Dim stream1 As Dart.PowerTCP.Ftp.SegmentedStream

' Open data connection
Try
   stream1 = Ftp1.Put("myfile.txt", 0)
Catch ex As Exception
   Debug.WriteLine(ex.Message)
   Return
End Try

' Success. Write some data to the data stream
stream1.Write("Some data. ")

' Write some more data
stream1.Write("Some more data. ")

' Write one more time
stream1.Write("This is all of the data. ")

' Close the stream
stream1.Close()

' Close the connection
Ftp1.Close()

'
' Retrieve and open the file "myfile.txt". It should contain:
'    "Some data. Some more data. This is all of the data."
'

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// When writing to the data connection, the Put method returns a SegmentedStream object
Dart.PowerTCP.Ftp.SegmentedStream stream1;

// Open data connection
try
{
   stream1 = ftp1.Put("myfile.txt", 0);
}
catch(Exception ex)
{
   Debug.WriteLine(ex.Message);
   return;
}

// Success. Write some data to the data stream
stream1.Write("Some data. ");

// Write some more data
stream1.Write("Some more data. ");

// Write one more time
stream1.Write("This is all of the data. ");

// Close the stream
stream1.Close();

// Close the connection
ftp1.Close();

/*
Retrieve and open the file "myfile.txt". It should contain:
    "Some data. Some more data. This is all of the data."
*/

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.Put Overload List


Put Method (String, String)

Ftp.Put Method (String, String)

Store a single file to the server synchronously.

[Visual Basic]
Public Function Put( _
   ByVal localFileName As String, _
   ByVal remoteFileName As String _
) As FtpFile
[C#]
public FtpFile Put(
   string localFileName,
   string remoteFileName
);
[C++]
public: FtpFile* Put(
   String* localFileName,
   String* remoteFileName
);
[JScript]
public function Put(
   String localFileName,
   String remoteFileName
): FtpFile;

Parameters

localFileName
Source pathname of the local file to transfer.
remoteFileName
Remote destination pathname for the file on the server.

Return Value

An FtpFile object that describes the transfer.

Remarks

Use this method to synchronously store a single file to the server. To asynchronously store a file, use BeginPut.

For more information on synchronous file transfer, see the topic Storing Files Synchronously Overview.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.

Example

The following example demonstrates simple use of the client/server properties in storing a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToStore As String = "c:\FtpTest\mynewfile.bmp"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file transfer
Dim file As Dart.PowerTCP.Ftp.FtpFile
Debug.WriteLine("Attempting to store file " + FileToStore)

Try
   ' Attempt to store the file (The FileInfo object parses the filename from the path)
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

// Put method returns an FtpFile object containing information about the file transfer
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

try
{
    // Attempt to store the file (The FileInfo object parses the filename from the path)
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.Put Overload List


Put Method (String, String, String, Boolean, Boolean)

Ftp.Put Method (String, String, String, Boolean, Boolean)

Synchronously put multiple files to the server.

[Visual Basic]
Public Function Put( _
   ByVal localRoot As String, _
   ByVal searchPattern As String, _
   ByVal remoteRoot As String, _
   ByVal subDirectories As Boolean, _
   ByVal synchronize As Boolean _
) As FtpFile()
[C#]
public FtpFile[] Put(
   string localRoot,
   string searchPattern,
   string remoteRoot,
   bool subDirectories,
   bool synchronize
);
[C++]
public: FtpFile* Put(
   String* localRoot,
   String* searchPattern,
   String* remoteRoot,
   bool subDirectories,
   bool synchronize
)  __gc[];
[JScript]
public function Put(
   String localRoot,
   String searchPattern,
   String remoteRoot,
   bool subDirectories,
   bool synchronize
): FtpFile[];

Parameters

localRoot
Source root directory on the client.
searchPattern
Wildcard search pattern of files to put; may include a path.
remoteRoot
Destination root directory on the server.
subDirectories
true if sub-directories should be recursively copied.
synchronize
true if files of the same size that already exist remotely should not be copied.

Return Value

An array of FtpFile objects that describe the transfer.

Remarks

Use this method to synchronously put multiple files to the server. To put multiple files asynchronously, use BeginPut.

The following table shows some examples of wildcards:

Wildcard | Meaning
* | Get all files in the directory.
*.* | Get all files in the directory that have a "." in the filename.
*.txt | Get all files in the directory that end with ".txt".
Test* | Get all files in the directory that start with "Test".
*Test* | Get all files in the directory that contain "Test" in the filename.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).
IOException | The filename, directory name, or volume label syntax is incorrect.
ArgumentException | A required argument contains invalid characters, is empty, or contains only white spaces.
NotSupportedException | The path format is not supported.

Example

The following example demonstrates how to synchronously store multiple files using the Put method.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim DirToStore As String = "c:\FtpTest\New"

' When using the Put method specifying a directory (MPUT) an array of FtpFiles is returned upon success
 Dim files() As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to MPUT all files in directory " + DirToStore)

Try
   ' Attempt to store the files to the server's working directory
   files = Ftp1.Put(DirToStore, "*", "", False)
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Return
End Try

' Success! Display info about the files transferred.
Dim file As Dart.PowerTCP.Ftp.FtpFile
For Each file In files
   Debug.WriteLine(file.LocalFileName + " successfully stored.")
Next

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string DirToStore = "C:\\FtpTest";

// When using the Put method specifying a directory (MPUT) an array of FtpFiles is returned upon success
Dart.PowerTCP.Ftp.FtpFile[] files;

Debug.WriteLine("Attempting to MPUT all files in directory " + DirToStore);

try
{
    // Attempt to store the files to the server's working directory
    files =  ftp1.Put(DirToStore, "*", "", false);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the files transferred
foreach(Dart.PowerTCP.Ftp.FtpFile file in files)
    Debug.WriteLine(file.LocalFileName + " successfully stored");

// Close the connection
ftp1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace | Ftp.Put Overload List


RawConnect Method

Ftp.RawConnect Method

Optional method you can use if you need to connect to an FTP server that expects a login sequence that is non-standard.

[Visual Basic]
Public Function RawConnect( _
   ByVal server As String, _
   ByVal serverPort As Integer _
) As Response
[C#]
public Response RawConnect(
   string server,
   int serverPort
);
[C++]
public: Response* RawConnect(
   String* server,
   int serverPort
);
[JScript]
public function RawConnect(
   String server,
   int serverPort
): Response;

Parameters

server
FTP proxy or destination server name.
serverPort
FTP port (usually 21)

Return Value

Initial greeting from the proxy or server.

Remarks

Warning: Do not use this method as the standard means for connecting to an FTP server. Usually, you will simply set the Server property to specify what server you will be using. There are cases, however, where you may want to control the login sequence. Use this method to code any desired login sequence. This method does not have an asynchronous counterpart, so you will need to create your own delegate if you wish to invoke this asynchronously.

Example

The following example demonstrates logging into an FTP server that has a nonstandard login sequence.

[Visual Basic]
' This demonstrates logging into a server that has a nonstandard
' login sequence, for example this server expects these commands
' to log in
' USER username
' PASS password
' GROUP groupname

Try
   Ftp1.RawConnect("MyFtpServer", 21)
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Received greeting OK. Issue USER (Be sure to use FtpCommand.Null
' and define entire command as second parameter).
Try
   Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "USER blah")
Catch ex As Exception
    Debug.WriteLine("Error: " + ex.Message)
    Exit Sub
End Try

' Issued USER OK. Try PASS
Try
   Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "PASS mypass")
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Issued PASS OK. Try GROUP (the non-standard command).
Try
   Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "GROUP Admin")
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Logged in, try a method.
 Ftp1.Get("maladroit.txt", "C:\\weezer\\maladroit.txt")

[C#]
// This demonstrates logging into a server that has a nonstandard
// login sequence, for example this server expects these commands
// to log in
// USER username
// PASS password
// GROUP groupname

try
{
    ftp1.RawConnect("MyFtpServer", 21);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Received greeting OK. Issue USER (Be sure to use FtpCommand.Null
// and define entire command as second parameter).

try
{
    ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "USER blah");
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Issued USER OK. Try PASS
try
{
    ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "PASS mypass");
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Issued PASS OK. Try GROUP
try
{
    ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "GROUP Admin");
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Logged in, try a method.
ftp1.Get("maladroit.txt", "C:\\weezer\\maladroit.txt");

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Rename Method

Ftp.Rename Method

Rename a file on the server.

[Visual Basic]
Public Function Rename( _
   ByVal fromFileName As String, _
   ByVal toFileName As String _
) As Invoke
[C#]
public Invoke Rename(
   string fromFileName,
   string toFileName
);
[C++]
public: Invoke* Rename(
   String* fromFileName,
   String* toFileName
);
[JScript]
public function Rename(
   String fromFileName,
   String toFileName
): Invoke;

Parameters

fromFileName
Current filename.
toFileName
Desired filename.

Return Value

An FtpInvoke object describing the request/response.

Remarks

To rename a file using the FTP protocol, it is necessary to send the command RNFR oldfilename, check the response, then send the command RNTO newfilename. This method encapsulates the RNFR and RNTO commands in a single method call

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).

Example

The following example demonstrates a simple rename.

[Visual Basic]
' Create Invoke object, which will contain request/response data
Dim invoke As Dart.PowerTCP.Ftp.Invoke

' Call Rename. Invoke object will contain request/response data
Try
   invoke = ftp1.Rename("aaa.txt", "zzz.txt")
' ProtocolException thrown if bad response received from server
Catch FTPEx As Dart.PowerTCP.Ftp.ProtocolException
   Debug.WriteLine("Rename unsuccessful")
   Debug.WriteLine(FtpEx.ToString())
   Exit Sub
End Try

' If it gets here, Rename was successful
Debug.WriteLine("Rename successful")

' Request sent and Response received
Debug.WriteLine("Response/response " + invoke.ToString())

[C#]
//Create Invoke object which will contain request/response data
Dart.PowerTCP.Ftp.Invoke invoke;

// Call Rename
try
{
    invoke = ftp1.Rename("aaa.txt", "zzz.txt");
}
// ProtocolException thrown if bad response received from server
catch(Dart.PowerTCP.Ftp.ProtocolException FTPex)
{
    Debug.WriteLine("Rename unsuccessful");
    Debug.WriteLine(FTPEx.ToString());
    return;
}

// If it gets here, Rename was successful
Debug.WriteLine("Rename successful");

// Request sent and response received
Debug.WriteLine("Response/response " + invoke.ToString());

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


SendCommand Method

Ftp.SendCommand Method

Send an FTP command synchronously.

[Visual Basic]
Public Function SendCommand( _
   ByVal command As String _
) As String
[C#]
public string SendCommand(
   string command
);
[C++]
public: String* SendCommand(
   String* command
);
[JScript]
public function SendCommand(
   String command
): String;

Parameters

command
FTP command to send. No trailing "\r\n" is necessary.

Return Value

An FtpInvoke object describing the request/response.

Remarks

Use this method to send low-level FTP commands to your server. Internally, the Invoke method is used.

To invoke a command asynchronously, use BeginInvoke.

For more information about synchronously sending commands, see the topic Sending Commands Synchronously.

This method is the simplest way to send a command to the server (ex HELP or CWD). For example, use this method if you want to send a synchronous "HELP" request to the server.

Exceptions

Exception Type | Condition
ProtocolException | Bad FTP response from server.
SocketException | The requested address is not valid in its context (possibly Server property is not set or is invalid).

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Ftp Events

The events of the Ftp class are listed below. For a complete list of Ftp class members, see the Ftp Members topic.

Public Instance Events

BusyChanged | Raised when the value of the Object.Busy property changes.
CertificateReceived | This event is raised when a certificate has been received to be authenticated.
CertificateRequested | This event is raised when a certificate has been requested.
ConnectedChanged | Raised when the value of the Object.Connected property changes.
Disposed (inherited from Component) | Adds an event handler to listen to the Disposed event on the component.
EndDelete | Raised when the BeginDelete request completes.
EndGet | Raised when the BeginGet request completes.
EndInvoke | Raised when the BeginInvoke request completes.
EndList | Raised when the BeginList request completes.
EndPut | Raised when the BeginPut request completes.
Preview | Raised before each file is transferred.
Progress | Raised repeatedly while a file transfer is in progress.
Trace | Raised when data has been sent/received.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


BusyChanged Event

Ftp.BusyChanged Event

Raised when the value of the Object.Busy property changes.

[Visual Basic]
Public Event BusyChanged As EventHandler
[C#]
public event EventHandler BusyChanged;
[C++]
public: __event EventHandler* BusyChanged;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Remarks

This event is fired when the value of the Object.Busy property changes. The Object.Busy property changes when a method is executing that is occupying the TCP connection.

This event is useful in several scenarios, for example:

  • Displaying to the user when the PowerTCP component is busy.
  • Taking action within your application when the PowerTCP component is no longer busy.

If you are using the PowerTCP component as a reference, you must create a method to handle the event yourself. For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see Using Events In PowerTCP.

Example

The following example demonstrates the Busy property, the BusyChanged event, and the BusyException.

[Visual Basic]
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
   ' Set server and user properties. This will allow calling of other
   ' Ftp Component methods with the log in taking place "behind the scenes"
   Ftp1.Server = "MyFtpServer"
   Ftp1.Username = "blah"
   Ftp1.Password = "mypass"

   ' Storing a binary file
   Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

   ' Store a large file, Ftp.Busy will be true for the duration
   ' of the store operation.
   Ftp1.BeginPut("C:\Test\Test.bmp", "newtest.bmp", Nothing)

   ' Try another asynchronous method immediately after the
   'first, this should throw a BusyException
   Try
      Ftp1.BeginPut("C:\Test\Test.bmp", "newtest2.bmp", Nothing)
   Catch BusyEx As Dart.PowerTCP.Ftp.BusyException
      Debug.WriteLine("BusyException: " + BusyEx.Message)
   End Try
End Sub

Private Sub Ftp1_BusyChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Ftp1.BusyChanged
   Debug.WriteLine("Busy property changed. Busy now = " + Ftp1.Busy)
End Sub

Private Sub Ftp1_EndPut(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndPut
   If e.Exception Is Nothing Then
      Debug.WriteLine("Put complete")
   Else
      Debug.WriteLine("Error: " + e.Exception.Message)
   End If
End Sub

[C#]
private void button1_Click(object sender, System.EventArgs e)
{
   // Set server and user properties. This will allow calling of other
   // Ftp Component methods with the log in taking place "behind the scenes"
   ftp1.Server = "MyFtpServer";
   ftp1.Username = "blah";
   ftp1.Password = "mypass";

   // Storing a binary file
   ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

   // Store a large file, Ftp.Busy will be true for the duration
   // of the store operation.
   ftp1.BeginPut("C:\\Test\\Test.bmp", "newtest.bmp", null);

   // Try another asynchronous method immediately after the
   // first, this should throw a BusyException
   try
   {
      ftp1.BeginPut("C:\\Test\\Test.bmp", "newtest2.bmp", null);
   }
   catch(Dart.PowerTCP.Ftp.BusyException BusyEx)
   {
                Debug.WriteLine("BusyException: " + BusyEx.Message);
   }
}

// BusyChanged event fires whenever the Busy property changes
private void ftp1_BusyChanged(object sender, System.EventArgs e)
{
   Debug.WriteLine("Busy property changed. Busy now = " + ftp1.Busy);
}

// EndPut event fires when the asynchronous BeginGet completes.
private void ftp1_EndPut(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{
   if(e.Exception == null)
      Debug.WriteLine("Put complete");
   else
      Debug.WriteLine("Error: " + e.Exception.Message);
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


CertificateReceived Event

Ftp.CertificateReceived Event

This event is raised when a certificate has been received to be authenticated.

[Visual Basic]
Public Event CertificateReceived As CertificateReceivedEventHandler
[C#]
public event CertificateReceivedEventHandler CertificateReceived;
[C++]
public: __event CertificateReceivedEventHandler* CertificateReceived;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type CertificateReceivedEventArgs containing data related to this event. The following CertificateReceivedEventArgs properties provide information specific to this event.

Property | Description
Accept | Controls whether or not the certificate is accepted.
Certificate | The certificate received for authentication.
TrustedRoot | Returns whether or not the certificate is from a Trusted Root Authority.
ValidDate | Returns whether or not the current time-date is within the certificate's life span.
ValidName | Returns whether or not the name is valid.

Remarks

The CertificateReceived event is raised when a certificate has been received from a secure server. A CertificateReceivedEventArgs object is passed into the event handler, containing information required to determine the validity of the certificate. If the certificate is determined to be invalid (if any of the properties ValidDate, ValidName, or TrustedRoot are false) the certificate is rejected. Accept is false to signify this. Set Accept to true to override this and accept the certificate.

Example

The following example demonstrates receiving a remote certificate.

[Visual Basic]
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Use Implicit Secure FTP
        Ftp1.Security = Security.Implicit

        'Do not ignore problems with remote certificates
        Ftp1.UseAuthentication = True

        'Login and get working directory
        Ftp1.Server = "myServer"
        Ftp1.Username = "myUser"
        Ftp1.Password = "myPassword"
        Ftp1.Invoke(FtpCommand.PrintDir)
    End Sub

    Private Sub Ftp1_CertificateReceived(ByVal sender As Object, ByVal e As CertificateReceivedEventArgs) Handles Ftp1.CertificateReceived
        'Fires during SSL handshake when server presents its certificate
        Dim msg As String = "The server could not be validated for the following reason(s):"
        e.Accept = True

        'Security checks
        If (Not e.TrustedRoot) Then
            msg = msg + vbCrLf + "    -The certificate CA was not trusted"
            e.Accept = False
        End If
        If (Not e.ValidName) Then
            msg = msg + vbCrLf + "    -The certificate name was invalid"
            e.Accept = False
        End If
        If (Not e.ValidDate) Then
            msg = msg + vbCrLf + "   -The certificate date was invalid"
            e.Accept = False
        End If

        'If Validation failed, show message to user
        If (e.Accept = False) Then
            msg = msg + vbCrLf + vbCrLf + "Do you wish to override the security check?"
            If (MessageBox.Show(msg, "Security Alert: Server could not be validated", _
             MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = DialogResult.Yes) Then e.Accept = True
        End If
    End Sub

[C#]
private void button1_Click(object sender, System.EventArgs e)
{
    //Use Implicit Secure FTP
    ftp1.Security = Security.Implicit;

    //Do not ignore problems with remote certificates
    ftp1.UseAuthentication = true;

    //Login and get working directory
    ftp1.Server = "myServer";
    ftp1.Username = "myUser";
    ftp1.Password = "myPassword";
    ftp1.Invoke(FtpCommand.PrintDir);
}

private void ftp1_CertificateReceived(object sender, CertificateReceivedEventArgs e)
{
    //Fires during SSL handshake when server presents its certificate
    string msg = "The server could not be validated for the following reason(s):";
    e.Accept = true;

    //Security checks
    if (!e.TrustedRoot)
    {
        msg = msg + "\r\n    -The certificate CA was not trusted";
        e.Accept = false;
    }
    if (!e.ValidName)
    {
        msg = msg + "\r\n    -The certificate name was invalid";
        e.Accept = false;
    }
    if (!e.ValidDate)
    {
        msg = msg + "\r\n    -The certificate date was invalid";
        e.Accept = false;
    }

    //If Validation failed, show message to user
    if (e.Accept == false)
    {
        msg = msg + "\r\n\r\nDo you wish to override the security check?";
        if (MessageBox.Show(msg, "Security Alert: Server could not be validated",
            MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            e.Accept = true;
    }
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


CertificateRequested Event

Ftp.CertificateRequested Event

This event is raised when a certificate has been requested.

[Visual Basic]
Public Event CertificateRequested As EventHandler
[C#]
public event EventHandler CertificateRequested;
[C++]
public: __event EventHandler* CertificateRequested;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Remarks

The CertificateRequested event is raised when a secure server requests a certificate from the client for client authentication. The SslStream.Certificate property of the current Tcp component (or, if using a different component, the Tcp component used for the underlying connection) must be set to a valid certificate. The easiest way to do this is to cast the sender parameter to an SslStream, then set the SslStream.Certificate property to a valid certificate.

Many objects provide a high-level Object.Certificate property, which represents the certificate used by the object. If the object you are using has such a high-level property it is recommended to use this property instead of the implementation described above.

Example

The following example demonstrates assigning a certificate for client certificate authentication.

[Visual Basic]
Private Sub Ftp1_CertificateRequested(ByVal sender As Object, ByVal e As System.EventArgs) Handles Ftp1.CertificateRequested
    'The server has requested a certificate from the client
    'There is a certificate in the CurrentUser/MY store that we want to use
    'Here it is found and the Certificate property is set to it
    Dim store As CertificateStore = New CertificateStore(CertificateStoreLocation.CurrentUser, CertificateStoreName.My)
    Dim c As Certificate
    For Each c In store
        If (c.IssuerName = "PowerTCPTest-CA" And c.IssuedTo = "PowerTCPTest") Then Ftp1.Certificate = c
    Next
End Sub

[C#]
private void ftp1_CertificateRequested(object sender, System.EventArgs e)
{
    //The server has requested a certificate from the client
    //There is a certificate in the CurrentUser/MY store that we want to use
    //Here it is found and the Certificate property is set to it
    CertificateStore store = new CertificateStore(CertificateStoreLocation.CurrentUser, CertificateStoreName.My);
    foreach (Certificate c in store)
    {
        if (c.IssuerName == "PowerTCPTest-CA" && c.IssuedTo == "PowerTCPTest")
            ftp1.Certificate = c;
    }
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


ConnectedChanged Event

Ftp.ConnectedChanged Event

Raised when the value of the Object.Connected property changes.

[Visual Basic]
Public Event ConnectedChanged As EventHandler
[C#]
public event EventHandler ConnectedChanged;
[C++]
public: __event EventHandler* ConnectedChanged;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Remarks

This event is raised when the value of the Object.Connected property changes. The value of the Object.Connected property changes whenever a TCP connection to a resource is either made or closed.

This event is useful in several scenarios, for example:

  • Displaying the user when a connection has been terminated.
  • Notifying the application if a connection has been terminated.

If you are using the PowerTCP component as a reference, you must create a method to handle the event yourself. For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see Using Events In PowerTCP.

Example

The following example demonstrates the ConnectedChanged event, and how using the AutoClose property effects the connection status.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Create Invoke object
Dim f As Dart.PowerTCP.Ftp.Invoke

' Call a couple of methods. The ConnectedChange event should only fire once , to connect
Debug.WriteLine("Sending a PWD command. The ConnectedChanged Event should fire once for this (log in)")
f = Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.PrintDir)
Debug.WriteLine("Response from server: " + f.Response.ToString())

' Because the connection is maintained, the ConnectedChanged event will not fire for other methods called
Debug.WriteLine("Sending a HELP command. The ConnectedChanged Event should not fire for this.")
f = Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Help)
Debug.WriteLine("Response from server: " + f.Response.ToString())

' Be sure to close the connection. The ConnectedChanged event should fire once more
Ftp1.Close()

' Monitor the connection status using the ConnectedChanged event
Private Sub Ftp1_ConnectedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Ftp1.ConnectedChanged

   ' The state of the connection has changed. Check current state.
   If Ftp1.Connected Then
      Debug.WriteLine("FTP Control connection connected")
   Else
      Debug.WriteLine("FTP Control connection disconnected")
   End If
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Create Invoke object

Dart.PowerTCP.Ftp.Invoke f;

// Call a couple of methods. The ConnectedChange event should only fire once , to connect
Debug.WriteLine("Sending a PWD command. The ConnectedChanged Event should fire once for this (log in)");
f = ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.PrintDir);
Debug.WriteLine("Response from server: " + f.Response.ToString());

// Because the connection is maintained, the ConnectedChanged event will not fire for other methods called
Debug.WriteLine("Sending a HELP command. The ConnectedChanged Event should not fire for this.");
f = ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Help);
Debug.WriteLine("Response from server: " + f.Response.ToString());

// Be sure to close the connection. The ConnectedChanged event should fire once more
ftp1.Close();

// Monitor the connection status using the ConnectedChanged event.

private void ftp1_ConnectedChanged(object sender, System.EventArgs e)
{

    // The state of the connection has changed. Check current state.
    if(ftp1.Connected)
        Debug.WriteLine("FTP control connection connected.");
    else
        Debug.WriteLine("FTP control connection disconnected.");
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


EndDelete Event

Ftp.EndDelete Event

Raised when the BeginDelete request completes.

[Visual Basic]
Public Event EndDelete As FileEventHandler
[C#]
public event FileEventHandler EndDelete;
[C++]
public: __event FileEventHandler* EndDelete;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type FileEventArgs containing data related to this event. The following FileEventArgs properties provide information specific to this event.

Property | Description
Exception | Gets any exception which occurred during the asynchronous operation.
File | Gets the FtpFile that represents a completed file transfer.
Files | Gets the FtpFile array that represents a completed file transfer.
State | Gets the object that was included as part of the associated method call.
Stream | Gets the FileEventArgs.Stream object that was part of the associated method call.

Remarks

This event is raised when the asynchronous method call BeginDelete completes. A FileEventArgs object will be passed into the event, containing information about the files deleted.

If any errors occurred during the asynchronous operation, they would be returned in the FileEventArgs object, check Exception to check for any exception.

For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see the topic, Using Events Within The Visual Studio .NET Environment.

If you are using the Ftp component as a reference, you must create a method to handle the event yourself. To learn how to do this, see the topic Using Events When Using The Ftp Component As A Reference.

This event MUST be implemented if you are using the BeginDelete method. See the topic Using EndXXX Events for more information.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


EndGet Event

Ftp.EndGet Event

Raised when the BeginGet request completes.

[Visual Basic]
Public Event EndGet As FileEventHandler
[C#]
public event FileEventHandler EndGet;
[C++]
public: __event FileEventHandler* EndGet;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type FileEventArgs containing data related to this event. The following FileEventArgs properties provide information specific to this event.

Property | Description
Exception | Gets any exception which occurred during the asynchronous operation.
File | Gets the FtpFile that represents a completed file transfer.
Files | Gets the FtpFile array that represents a completed file transfer.
State | Gets the object that was included as part of the associated method call.
Stream | Gets the FileEventArgs.Stream object that was part of the associated method call.

Remarks

This event is raised when the asynchronous method call BeginGet completes. A FileEventArgs object will be passed into the event, containing information about the transfer.

If any errors occurred during the asynchronous operation, they would be returned in the FileEventArgs object, check Exception to check for any exception.

For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see the topic,Using Events Within The Visual Studio .NET Environment.

If you are using the Ftp component as a reference, you must create a method to handle the event yourself. To learn how to do this, see the topic Using Events When Using The Ftp Component As A Reference.

This event MUST be implemented if you are using the BeginGet method. See the topic Using EndXXX Events for more information.

Example

The following example demonstrates how to asynchronously retrieve a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToGet As String = "test.txt"

' Call BeginGet, this will begin an asynchronous Get. Upon completion the EndGet Event will be fired.
Ftp1.BeginGet(FileToGet, "RetrievedFile.txt", Nothing)

' Display message, because BeginGet is asynchronous, this will be immediately executed.
Debug.WriteLine("Retrieving " + FileToGet)

' When the BeginGet operation has completed, the EndGet Event will fire.

Private Sub Ftp1_EndGet(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndGet

    ' If an error occurred, it would be returned in the event. Be sure to check for it.
    If e.Exception Is Nothing Then
       Debug.WriteLine("Get completed for file " + file.RemoteFileName)
    Else
       Debug.WriteLine("Error: " + e.Exception.ToString())
    End If

   ' Close the connection
   Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToGet = "test.txt";

// Call BeginGet, this will begin an asynchronous Get. Upon completion the EndGet Event will be fired.
ftp1.BeginGet(FileToGet, Application.StartupPath + "\\" + new System.IO.FileInfo(FileToGet).Name, null);

// Display message, because BeginGet is asynchronous, this will be immediately executed.
Debug.WriteLine("Retrieving " + FileToGet);

// When the BeginGet operation has completed, the EndGet Event will fire.
private void ftp1_EndGet(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{

    // If an error occurred, it would be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
       Debug.WriteLine("Get completed for file " + file.RemoteFileName);
    }
    else
    {
       Debug.WriteLine("Error: " + e.Exception.ToString());
    }

    // Close the connection
    ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


EndInvoke Event

Ftp.EndInvoke Event

Raised when the BeginInvoke request completes.

[Visual Basic]
Public Event EndInvoke As InvokeEventHandler
[C#]
public event InvokeEventHandler EndInvoke;
[C++]
public: __event InvokeEventHandler* EndInvoke;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type InvokeEventArgs containing data related to this event. The following InvokeEventArgs properties provide information specific to this event.

Property | Description
Exception | Gets any exception which occurred during the asynchronous operation.
Request | Gets the request sent to the server.
Response | Gets the response received from the server.
State | Gets the object that was included as part of the associated method call.

Remarks

This event is raised when the asynchronous method call BeginInvoke completes. An InvokeEventArgs object will be passed into the event, containing information about the request sent and the response received.

If any errors occurred during the asynchronous operation, they would be returned in the InvokeEventArgs object, check Exception for any exception.

For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see the topic, Using Events Within The Visual Studio .NET Environment.

If you are using the Ftp component as a reference, you must create a method to handle the event yourself. To learn how to do this, see the topic Using Events When Using The Ftp Component As A Reference.

This event MUST be implemented if you are using the BeginInvoke method. See the topic Using EndXXX Events for more information.

Example

The following example demonstrates using Ftp.BeginInvoke to issue a command (in this case, CDUP) asynchronously.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Issue CDUP command asynchronously, upon completion the EndInvoke Event will be fired.
Ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.ChangeDirUp, Nothing, Nothing)

' Report
Debug.WriteLine("CDUP command sent.")

' When the BeginInvoke operation has completed, the EndInvoke Event will fire.
Private Sub Ftp1_EndInvoke(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.InvokeEventArgs) Handles Ftp1.EndInvoke

   ' If an error occurred during the asynchronous method, it would
   ' be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then
      Debug.WriteLine("Command issued " + e.Request)
      Debug.WriteLine("Response received " + e.Response.ToString();
   Else
      Debug.WriteLine(e.Exception.Message)
   End If

   ' Close the connection
   Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Issue CDUP command asynchronously, upon completion the EndInvoke Event will be fired.
ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.ChangeDirUp, null, null);

// Report
Debug.WriteLine("CDUP command sent.");

// When the BeginInvoke operation has completed, the EndInvoke Event will fire.
private void ftp1_EndInvoke(object sender, Dart.PowerTCP.Ftp.InvokeEventArgs e)
{

    // If an error occurred during the asynchronous method, it would
    // be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
        Debug.WriteLine("Command issued " + e.Request);
        Debug.WriteLine("Response received " + e.Response);
    }
    else
    {
        Debug.WriteLine("Error: " + e.Exception.Message);
    }

    // Close the connection
    ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


EndList Event

Ftp.EndList Event

Raised when the BeginList request completes.

[Visual Basic]
Public Event EndList As ListEventHandler
[C#]
public event ListEventHandler EndList;
[C++]
public: __event ListEventHandler* EndList;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type ListEventArgs containing data related to this event. The following ListEventArgs properties provide information specific to this event.

Property | Description
Exception | Gets any exception which occurred during the asynchronous operation.
Listing | Gets the Listing object received from the server.
State | Gets the object that was included as part of the associated method call.

Remarks

This event is raised when the asynchronous method call BeginList completes. A ListEventArgs object will be passed into the event, containing information about the listing.

If any errors occurred during the asynchronous operation, they would be returned in the ListEventArgs object, check Exception to check for any exception.

For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see the topic, Using Events Within The Visual Studio .NET Environment.

If you are using the Ftp component as a reference, you must create a method to handle the event yourself. To learn how to do this, see the topic Using Events When Using The Ftp Component As A Reference.

This event MUST be implemented if you are using the BeginList method. See the topic Using EndXXX Events for more information.

Example

The following example demonstrates using BeginList to retrieve a Listing asynchronously.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Get a listing for all text files in home/test. Upon completion the EndList
' event will fire, with the Listing passed in as an arg
 Ftp1.BeginList("/home/test/*.txt", True, Nothing)

' Because BeginList is asynchronous, this line will be immediately executed.
Debug.WriteLine("Retrieving Listing")

' When the BeginList operation has completed, the EndList Event will fire.
Private Sub Ftp1_EndList(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ListEventArgs) Handles Ftp1.EndList

   ' If an error occurred during the asynchronous method, it would be
   ' returned in the event. Be sure to check for it.
   if e.Exception Is Nothing Then

      ' Retrieve listing and display

      ' Begin setting up the ListView (listView1 is a standard ListView object) display

      ' Show gridlines.
      ListView1.GridLines = True

      ' Set View to Details
      ListView1.View = View.Details

      ' Add column headings for file name, size, and date.
      ListView1.Columns.Add("File Name", 100, HorizontalAlignment.Left)
      ListView1.Columns.Add("File Size", 100, HorizontalAlignment.Left)
      ListView1.Columns.Add("File Timestamp", 100, HorizontalAlignment.Left)

      ' Iterate through the listing, adding a row to the ListBox for each
      Dim le As Dart.PowerTCP.Ftp.ListEntry
      For Each le In e.Listing
         Dim cols() As String = {le.Name, le.Size.ToString(), le.TimeStamp}
         ListView1.Items.Add(New ListViewItem(cols))
      Next
  Else
     Debug.WriteLine(e.Exception.Message)
  End If

  ' Close the connection
  Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Get a listing for all text files in home/test. Upon completion the EndList
// event will fire, with the Listing passed in as an arg
ftp1.BeginList("/home/test/*.txt", true, null);

// Because BeginList is asynchronous, this line will be immediately executed.
Debug.WriteLine("Retrieving listing");

// When the BeginList operation has completed, the EndList Event will fire.

private void ftp1_EndList(object sender, Dart.PowerTCP.Ftp.ListEventArgs e)
{
    // If an error occurred during the asynchronous method, it would
    // be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
       // Retrieve listing and display

       // Begin setting up the ListView (listView1 is a standard ListView object) display

       // Show gridlines.
       listView1.GridLines = true;

       // Set View to Details
       listView1.View = View.Details;

       // Add column headings for file name, size, and date.
       listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
       listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
       listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

       // Iterate through the listing, adding a row to the ListBox for each
       foreach(Dart.PowerTCP.Ftp.ListEntry le in e.Listing)
       {
          string[] cols = {le.Name, le.Size.ToString(), le.TimeStamp};
          listView1.Items.Add(new ListViewItem(cols));
       }
    }
    else
    {
        Debug.WriteLine("Error: " + ex.Message);
    }

    // Close the connection
    ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


EndPut Event

Ftp.EndPut Event

Raised when the BeginPut request completes.

[Visual Basic]
Public Event EndPut As FileEventHandler
[C#]
public event FileEventHandler EndPut;
[C++]
public: __event FileEventHandler* EndPut;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type FileEventArgs containing data related to this event. The following FileEventArgs properties provide information specific to this event.

Property | Description
Exception | Gets any exception which occurred during the asynchronous operation.
File | Gets the FtpFile that represents a completed file transfer.
Files | Gets the FtpFile array that represents a completed file transfer.
State | Gets the object that was included as part of the associated method call.
Stream | Gets the FileEventArgs.Stream object that was part of the associated method call.

Remarks

This event is raised when the asynchronous method call BeginPut completes. A FileEventArgs object will be passed into the event, containing information about the transfer.

If any errors occurred during the asynchronous operation, they would be returned in the FileEventArgs object, check Exception to check for any exception.

For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see the topic, Using Events Within The Visual Studio .NET Environment.

If you are using the Ftp component as a reference, you must create a method to handle the event yourself. To learn how to do this, see the topic Using Events When Using The Ftp Component As A Reference.

This event MUST be implemented if you are using the BeginPut method. See the topic Using EndXXX Events for more information.

Example

The following example demonstrates using BeginPut to Put a file to the server asynchronously

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToPut As String = "c:\FtpTest\doc.txt"

' Call BeginPut for the specified file, this will begin an asynchronous Put. Upon completion
' the EndPut Event will be fired. (The FileInfo object parses the name from the path).
Ftp1.BeginPut(FileToPut, New IO.FileInfo(FileToPut).Name, Nothing)

'Report to user. Since BeginPut is asynchronous, this line will be immediately executed
Debug.WriteLine("Storing file")

' When the BeginPut operation has completed, the EndPut Event will fire.
Private Sub Ftp1_EndPut(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.FileEventArgs) Handles Ftp1.EndPut

   Dim file As Dart.PowerTCP.Ftp.FtpFile

   ' If an error occurred, it would be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then
      Debug.WriteLine("Successfully Put " + file.LocalFileName)
   Else
      Debug.WriteLine("Error: " + e.Exception.ToString())
   End If

   ' Close the connection
   Ftp1.Close()

End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToPut = "c:\\FtpTest\\MyFile.bmp";

// Call BeginPut for the specified file, this will begin an asynchronous Put. Upon completion
// the EndPut Event will be fired. (The FileInfo object parses the filename from the path).
ftp1.BeginPut(FileToPut, new System.IO.FileInfo(FileToPut).Name, null);

// Report to user. Since BeginPut is asynchronous, this line will be immediately executed.
Debug.WriteLine("Storing file");

// When the BeginPut operation has completed, the EndPut Event will fire.
private void ftp1_EndPut(object sender, Dart.PowerTCP.Ftp.FileEventArgs e)
{

   // If an error occurred, it would be returned in the event. Be sure to check for it.
   if(e.Exception == null)
   {
      Debug.WriteLine("Successfully put " + file.LocalFileName);
   }
   else
   {
      Debug.WriteLine("Error: " + e.Exception.ToString())
   }

   // Close the connection
   ftp1.Close();
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Preview Event

Ftp.Preview Event

Raised before each file is transferred.

[Visual Basic]
Public Event Preview As PreviewEventHandler
[C#]
public event PreviewEventHandler Preview;
[C++]
public: __event PreviewEventHandler* Preview;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type PreviewEventArgs containing data related to this event. The following PreviewEventArgs properties provide information specific to this event.

Property | Description
Cancel | Used to cancel the pending file transfer.
CurrentFile | Index of file being transferred.
FileName | Gets the pathname of the file to be transferred.
TotalFiles | Total number of files being transferred.

Remarks

This event is raised before a file transfer is started. A PreviewEventArgs object will be passed into the event, containing data about the file transfer. The transfer may be cancelled from within this event. For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see the topic, Using Events Within The Visual Studio .NET Environment.

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Progress Event

Ftp.Progress Event

Raised repeatedly while a file transfer is in progress.

[Visual Basic]
Public Event Progress As FtpProgressEventHandler
[C#]
public event FtpProgressEventHandler Progress;
[C++]
public: __event FtpProgressEventHandler* Progress;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type FtpProgressEventArgs containing data related to this event. The following FtpProgressEventArgs properties provide information specific to this event.

Property | Description
Count | Gets the byte count transferred.
CurrentFile | Index of file being transferred.
FileName | Gets the pathname of the file transferred.
Length | The length of the stream.
Position | The position within the stream.
Status | Status of the file (or directory) referenced by FileName.
TotalFiles | Total number of files being transferred.
TransferRate | Gets the current transfer rate in bytes per second.

Remarks

This event is raised repeatedly while a file transfer is taking place. A ProgressEventArgs object will be passed into the event, containing data about the file transfer progress (such as current file being transferred, bytes transferred, etc). For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see the topic, Using Events Within The Visual Studio .NET Environment.

The BlockSize and ProgressSize properties controls how often this event will be raised.

If Compression is set to Compression.Archive and the file is being retrieved from the server, ProgressEventArgs.Length will be set to -1.

If the size of the remote file could not be determined, ProgressEventArgs.Length will be set to -1.

If you are using the Ftp component as a reference, you must create a method to handle the event yourself. To learn how to do this, see the topic Using Events When Using The Ftp Component As A Reference.

Example

The following example demonstrates capturing file transfer progress info.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFtpServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
Ftp1.BlockSize = 1024

' Set the MaxTransfer Rate to 5 kbps
Ftp1.MaxTransferRate = 5

' Attempt to put multiple files to the server
Try
   Ftp1.Put("C:\Test", "*", "", True)
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Complete!")

' Monitor the progress using the progress event.
Private Sub Ftp1_Progress(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ProgressEventArgs) Handles Ftp1.Progress
   ' Display the currently transferring file
   Label1.Text = "Currently transferring " + e.FileName

   ' Display the total bytes transferred
   Label2.Text = "Total bytes transferred: " + e.Count

   ' Display the current transfer rate
   Label3.Text = "Transfer Rate: " + e.TransferRate

   ' Set the properties of ProgressBar1 (this ProgressBar displays progress
   ' for each individual file)
   ProgressBar1.Minimum = 0
   ProgressBar1.Maximum = e.Length
   ProgressBar1.Value = e.Position

   ' Set the properties of progressBar2 (this ProgressBar displays progress
   ' for all files, useful when transferring multiple files - MPUT).
   ProgressBar2.Minimum = 0
   ProgressBar2.Maximum = e.TotalFiles
   ProgressBar2.Value = e.CurrentFile
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
ftp1.BlockSize = 1024;

// Set the MaxTransferRate to 5 kbps
ftp1.MaxTransferRate = 5;

// Attempt to put multiple files to the server
try
{
   ftp1.Put("C:\\Test", "*", "", true);
}
catch(Exception ex)
{
   Debug.WriteLine("Error: " + ex.Message);
   return;
}

// Success
Debug.WriteLine("Complete!");

// Monitor the progress using the progress event.
private void ftp1_Progress(object sender, Dart.PowerTCP.Ftp.ProgressEventArgs e)
{
   // Display the currently transferring file
   label1.Text = "Currently transferring " + e.FileName;

   // Display the total bytes transferred
   label2.Text = "Total bytes transferred: " + e.Count;

   // Display the current transfer rate
   label3.Text = "Transfer Rate: " + e.TransferRate;

   // Set the properties of progressBar1 (this ProgressBar displays progress
   // for each individual file)
   progressBar1.Minimum = 0;
   progressBar1.Maximum = (int)e.Length;
   progressBar1.Value = (int)e.Position;

   // Set the properties of progressBar2 (this ProgressBar displays progress
   // for all files, useful when transferring multiple files - MPUT).
   progressBar2.Minimum = 0;
   progressBar2.Maximum = (int)e.TotalFiles;
   progressBar2.Value = (int)e.CurrentFile;
}

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


Trace Event

Ftp.Trace Event

Raised when data has been sent/received.

[Visual Basic]
Public Event Trace As SegmentEventHandler
[C#]
public event SegmentEventHandler Trace;
[C++]
public: __event SegmentEventHandler* Trace;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type SegmentEventArgs containing data related to this event. The following SegmentEventArgs properties provide information specific to this event.

Property | Description
Exception | Gets any exception which occurred during the asynchronous operation.
Segment | The Segment object referencing the data that was sent or received.
State | Gets the object that was included as part of the associated method call.

Remarks

This event is raised when commands or data has been sent/received. If you are using a component which uses TCP as the transport protocol a SegmentEventArgs object is passed into the event containing any commands or data sent or received. If you are using a component which uses UDP as the transport protocol a DatagramEventArgs object is passed into the event containing any commands or data sent or received.

The Object.RawTrace event always reports actual data sent/received over the socket. The Count of each segment reflects the number of bytes actually written and received. The Object.Trace event reports data sent/received at a higher level. For example, for the Telnet component, Object.Trace reports data sent/received, but does not report IAC option sequences that are processed by TelnetStream, whereas Object.RawTrace allows you to trace the actual data sent/received, including Telnet option commands.

If you are using the PowerTCP component as a reference, you must create a method to handle the event yourself. For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see Using Events In PowerTCP.

Example

The following example demonstrates using the Log event to create a text log of all data sent over the control connection.

[Visual Basic]
' The Trace Event will fire whenever data is sent/received over the control connection.
Private Sub Ftp1_Log(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.SegmentEventArgs) Handles Ftp1.Log
   ' Create FileStream to write to log file
   Dim stream1 As New System.IO.FileStream("c:\FtpTest\mylog.log", IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite)

   ' Create text to precede sent/received data.
   Dim recv() As Byte = System.Text.Encoding.ASCII.GetBytes(vbCrLf + "Received <--" + vbCrLf)
   Dim sent() As Byte = System.Text.Encoding.ASCII.GetBytes(vbCrLf + "Sent -->" + vbCrLf)

   ' Set the stream position to append.
   stream1.Position = stream1.Length

   ' Check if data is incoming or outgoing and write appropriate data
   If e.Sent = True Then
      stream1.Write(sent, 0, sent.Length)
   Else
      stream1.Write(recv, 0, recv.Length)
   End If

   ' Write the data
   stream1.Write(e.Segment.Buffer, e.Segment.Offset, e.Segment.Count)

   ' Close the stream
   stream1.Close()

End Sub

[C#]
// The Trace Event will fire whenever data is sent/received.

private void Ftp1_Trace(object sender, Dart.PowerTCP.Ftp.SegmentEventArgs e)
{

    // Create FileStream to write to log file
    System.IO.FileStream stream1 = new System.IO.FileStream("c:\\FtpTest\\log.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);

    // Create text to precede sent/received data.
    byte[] recv = System.Text.ASCIIEncoding.ASCII.GetBytes("\r\nReceived <-- \r\n");
    byte[] sent = System.Text.ASCIIEncoding.ASCII.GetBytes("\r\nSent --> \r\n");

    // Set the stream position to append.
    stream1.Position = stream1.Length;

    // Check if data is incoming or outgoing and write appropriate data
    if(e.Sent == true)
        stream1.Write(sent, 0, sent.Length);
    else
        stream1.Write(recv, 0, recv.Length);

    // Write the data
    stream1.Write(e.Segment.Buffer, e.Segment.Offset, e.Segment.Count);

    // Close the stream
    stream1.Close();

See Also

Ftp Class | Dart.PowerTCP.Ftp Namespace


FtpCommand Enumeration

Enumerates commands that can be sent using Invoke and BeginInvoke.

[Visual Basic]
Public Enum FtpCommand
[C#]
public enum FtpCommand
[C++]
public __value enum FtpCommand
[JScript]
public enum FtpCommand

Remarks

Use Invoke and BeginInvoke to send commands. Use FtpCommand.Null to send your own command.

Example

The following example demonstrates using Invoke to send a command.

[Visual Basic]
' Set server and user properties. This will allow us to call other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Invoke a command
Dim invoke as Dart.PowerTCP.Ftp.Invoke
Try
   invoke = Ftp1.Invoke(FtpCommand.NoOp)
Catch ex as Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Request/Response messages: " + invoke.ToString())

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Invoke a command
Dart.PowerTCP.Ftp.Invoke invoke;
try
{
   invoke = ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.NoOp);
}
catch (Exception ex)
{
    Debug.WriteLine("Error: " + ex.ToString());
    return;
}

// Success
Debug.WriteLine("Request/Response messages: " + invoke.ToString());

Members

Member Name | Description
Account | Send "ACCT" to provide authentication information.
ChangeDir | Send "CWD <pathname>" to change the default working directory.
ChangeDirUp | Send "CDUP" to move the default working directory up one level.
Delete | Send "DELE <filename>" to delete a file.
Help | Send "HELP" to get help info.
MakeDir | Send "MKD <pathname>" to make a directory.
NoOp | Send "NOOP" to test the connection.
Null | Send the modifier parameter only, so you can send your own command.
Password | Send "PASS" to provide authentication information.
PrintDir | Send "PWD" to discover the current working directory.
Quit | Send "QUIT" to terminate the connection.
Reinitialize | Send "REIN" to reinitialize the session and login.
RemoveDir | Send "RMD <pathname>" to remove a directory.
RenameFrom | Send "RNFR <pathname>" to specify what file to rename.
RenameTo | Send "RNTO <pathname>" to specify the new name of the file.
Restart | Send "REST <byteOffset>" to specify starting location in the remote file.
SiteParameters | Send "SITE" to access special services
Size | Send "SIZE <filename>" to get the size of a file
Status | Send "STAT" to get status information.
Structure | Send "STRU <F|R|P>" to perform special-case record and page structure manipulation.
StructureMount | Send "SMNT <structure>" to mount a different file system data structure without logging out
System | Send "SYST" to get system information.
Username | Send "USER" to provide authentication information.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


FtpFile Class

Presents the results from an FTP file transfer.

For a list of all members of this type, see FtpFile Members.

System.Object
Dart.PowerTCP.Ftp.FtpFile

[Visual Basic]
Public Class FtpFile
[C#]
public class FtpFile
[C++]
public __gc class FtpFile
[JScript]
public class FtpFile

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

When any file transfer method is called (i.e. Get, Put, BeginGet, or BeginPut) an FtpFile object (or an array of FtpFile objects) is returned. When using synchronous methods such as Get and Put this object is returned directly from the method. When using asynchronous methods such as BeginGet or BeginPut this object is passed into the event handler as part of the FileEventArgs class.

The FtpFile object encapsulates data about the file transfer on both the local and remote machines such as local file name, remote file name, file length, and bytes transferred.

Example

The following example demonstrates simple use of the client/server properties in storing a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToStore As String = "c:\FtpTest\mynewfile.bmp"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file transfer
Dim file As Dart.PowerTCP.Ftp.FtpFile
Debug.WriteLine("Attempting to store file " + FileToStore)

Try
   ' Attempt to store the file (The FileInfo object parses the filename from the path)
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

// Put method returns an FtpFile object containing information about the file transfer
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

try
{
    // Attempt to store the file (The FileInfo object parses the filename from the path)
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

// Close the connection
ftp1.Close();

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

FtpFile Members | Dart.PowerTCP.Ftp Namespace


FtpFile Members

FtpFile overview

Public Instance Properties

Count | After any file transfer method (Get, BeginGet, Put, or BeginPut) has completed, this property gets the byte count transferred.
Exception | Contains any exception (if any) which occurred during the file transfer
Length | After any file transfer method (Get, BeginGet, Put, or BeginPut) has completed, this property gets the length of the file.
LocalFileName | After any file transfer method (Get, BeginGet, Put, or BeginPut) has completed, this property gets the pathname of the local file transferred.
Position | Gets the position within the stream/file.
RemoteFileName | After any file transfer method (Get, BeginGet, Put, or BeginPut) has completed, this property gets the pathname of the remote file transferred.
Status | Status of the file (or directory) referenced by RemoteFileName.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

FtpFile Class | Dart.PowerTCP.Ftp Namespace


FtpFile Properties

The properties of the FtpFile class are listed below. For a complete list of FtpFile class members, see the FtpFile Members topic.

Public Instance Properties

Count | After any file transfer method (Get, BeginGet, Put, or BeginPut) has completed, this property gets the byte count transferred.
Exception | Contains any exception (if any) which occurred during the file transfer
Length | After any file transfer method (Get, BeginGet, Put, or BeginPut) has completed, this property gets the length of the file.
LocalFileName | After any file transfer method (Get, BeginGet, Put, or BeginPut) has completed, this property gets the pathname of the local file transferred.
Position | Gets the position within the stream/file.
RemoteFileName | After any file transfer method (Get, BeginGet, Put, or BeginPut) has completed, this property gets the pathname of the remote file transferred.
Status | Status of the file (or directory) referenced by RemoteFileName.

See Also

FtpFile Class | Dart.PowerTCP.Ftp Namespace


Count Property

FtpFile.Count Property

After any file transfer method (Get, BeginGet, Put, or BeginPut) has completed, this property gets the byte count transferred.

[Visual Basic]
Public Property ReadOnly Count As Long
[C#]
public long Count { get; }
[C++]
public: __property __int64 get_Count();
[JScript]
public function get Count() : long

Property Value

A long representing the byte count transferred

Remarks

This property represents the number of bytes transferred. This value may be less than Length for transfers that have been restarted.

This data is also accessible via the Progress event, when file transfer is completed.

Example

The following example demonstrates simple use of the client/server properties in storing a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToStore As String = "c:\FtpTest\mynewfile.bmp"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file transfer
Dim file As Dart.PowerTCP.Ftp.FtpFile
Debug.WriteLine("Attempting to store file " + FileToStore)

Try
   ' Attempt to store the file (The FileInfo object parses the filename from the path)
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

// Put method returns an FtpFile object containing information about the file transfer
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

try
{
    // Attempt to store the file (The FileInfo object parses the filename from the path)
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

// Close the connection
ftp1.Close();

See Also

FtpFile Class | Dart.PowerTCP.Ftp Namespace


Exception Property

FtpFile.Exception Property

Contains any exception (if any) which occurred during the file transfer

[Visual Basic]
Public Property ReadOnly Exception As Exception
[C#]
public Exception Exception { get; }
[C++]
public: __property Exception* get_Exception();
[JScript]
public function get Exception() : Exception

Property Value

If any exception occurred during the file transfer, this property will contain an Exception object describing the exception.

Remarks

Check this property for a non-null value to tell if an exception occurred during the transfer. If this property is null, no exception occurred.

See Also

FtpFile Class | Dart.PowerTCP.Ftp Namespace


Length Property

FtpFile.Length Property

After any file transfer method (Get, BeginGet, Put, or BeginPut) has completed, this property gets the length of the file.

[Visual Basic]
Public Property ReadOnly Length As Long
[C#]
public long Length { get; }
[C++]
public: __property __int64 get_Length();
[JScript]
public function get Length() : long

Property Value

A long representing the length of the file.

Remarks

When transferring files, this number represents the length of the file. When transferring streams, this number will be the length of the stream (equal to Stream.Length).

This data is also accessible via the Progress event, when file transfer is completed.

Example

The following example demonstrates simple use of the client/server properties in storing a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToStore As String = "c:\FtpTest\mynewfile.bmp"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file transfer
Dim file As Dart.PowerTCP.Ftp.FtpFile
Debug.WriteLine("Attempting to store file " + FileToStore)

Try
   ' Attempt to store the file (The FileInfo object parses the filename from the path)
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

// Put method returns an FtpFile object containing information about the file transfer
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

try
{
    // Attempt to store the file (The FileInfo object parses the filename from the path)
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

// Close the connection
ftp1.Close();

See Also

FtpFile Class | Dart.PowerTCP.Ftp Namespace


LocalFileName Property

FtpFile.LocalFileName Property

After any file transfer method (Get, BeginGet, Put, or BeginPut) has completed, this property gets the pathname of the local file transferred.

[Visual Basic]
Public Property ReadOnly LocalFileName As String
[C#]
public string LocalFileName { get; }
[C++]
public: __property String* get_LocalFileName();
[JScript]
public function get LocalFileName() : String

Property Value

A string representing the local pathname of the transferred file.

Remarks

When transferring files, this will property contain the pathname of the local file. When transferring streams (either storing streams to the server or retrieving files from the server as streams) this property will be null as the file only exists in memory.

Example

The following example demonstrates simple use of the client/server properties in storing a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToStore As String = "c:\FtpTest\mynewfile.bmp"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file transfer
Dim file As Dart.PowerTCP.Ftp.FtpFile
Debug.WriteLine("Attempting to store file " + FileToStore)

Try
   ' Attempt to store the file (The FileInfo object parses the filename from the path)
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

// Put method returns an FtpFile object containing information about the file transfer
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

try
{
    // Attempt to store the file (The FileInfo object parses the filename from the path)
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

// Close the connection
ftp1.Close();

See Also

FtpFile Class | Dart.PowerTCP.Ftp Namespace


Position Property

FtpFile.Position Property

Gets the position within the stream/file.

[Visual Basic]
Public Property ReadOnly Position As Long
[C#]
public long Position { get; }
[C++]
public: __property __int64 get_Position();
[JScript]
public function get Position() : long

Property Value

A long representing the current position within the stream/file.

Remarks

Position equals Length when the transfer completes normally, but is less than Length if AbortTransfer is used to abort the transfer. If AbortTransfer is used to abort a multiple-file transfer, or an Exception is encountered, a -1 value indicates the file transfer never started.

See Also

FtpFile Class | Dart.PowerTCP.Ftp Namespace


RemoteFileName Property

FtpFile.RemoteFileName Property

After any file transfer method (Get, BeginGet, Put, or BeginPut) has completed, this property gets the pathname of the remote file transferred.

[Visual Basic]
Public Property ReadOnly RemoteFileName As String
[C#]
public string RemoteFileName { get; }
[C++]
public: __property String* get_RemoteFileName();
[JScript]
public function get RemoteFileName() : String

Property Value

A string representing the pathname of the transferred file on the remote machine.

Remarks

When transferring files or streams, this property will contain the pathname of the file on the server.

Example

The following example demonstrates simple use of the client/server properties in storing a single file.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

Dim FileToStore As String = "c:\FtpTest\mynewfile.bmp"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file transfer
Dim file As Dart.PowerTCP.Ftp.FtpFile
Debug.WriteLine("Attempting to store file " + FileToStore)

Try
   ' Attempt to store the file (The FileInfo object parses the filename from the path)
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image;

// Put method returns an FtpFile object containing information about the file transfer
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

try
{
    // Attempt to store the file (The FileInfo object parses the filename from the path)
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

// Close the connection
ftp1.Close();

See Also

FtpFile Class | Dart.PowerTCP.Ftp Namespace


Status Property

FtpFile.Status Property

Status of the file (or directory) referenced by RemoteFileName.

[Visual Basic]
Public Property ReadOnly Status As FtpFileStatus
[C#]
public FtpFileStatus Status { get; }
[C++]
public: __property FtpFileStatus get_Status();
[JScript]
public function get Status() : FtpFileStatus

See Also

FtpFile Class | Dart.PowerTCP.Ftp Namespace


FtpFileStatus Enumeration

Used to report status of a file transfer or deletion.

[Visual Basic]
Public Enum FtpFileStatus
[C#]
public enum FtpFileStatus
[C++]
public __value enum FtpFileStatus
[JScript]
public enum FtpFileStatus

Members

Member Name | Description
TransferInProgress | FTP file transfer is in progress.
TransferCompleted | FTP file transfer has completed successfully.
TransferFailed | FTP file transfer failed (check for a reported exception).
TransferAborted | FTP file transfer has been aborted by the user.
DeleteCompleted | File has been deleted from the FTP server.
DeleteFailed | File could not be deleted or removed from the FTP server.
DeleteAborted | Delete process has been aborted by the user.
Cancelled | User cancelled the transfer from within the PreviewPut or PreviewGet events.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


FtpProgressEventArgs Class

This class is passed into the Progress event and provides data for that event.

For a list of all members of this type, see FtpProgressEventArgs Members.

System.Object
System.EventArgs
Dart.PowerTCP.Ftp.FtpProgressEventArgs

[Visual Basic]
Public Class FtpProgressEventArgs
    Inherits EventArgs
[C#]
public class FtpProgressEventArgs : EventArgs
[C++]
public __gc class FtpProgressEventArgs : public EventArgs
[JScript]
public class FtpProgressEventArgs extends EventArgs

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

When any file transfer method is called (Get, Put, BeginGet, or BeginPut) the Progress event will be raised in the frequency specified by BlockSize. An FtpProgressEventArgs object is passed into the Progress event containing information about the current file transfer.

This class is useful for displaying information to the user about the current file transfer. For example, the current file being transferred is accessible through FtpProgressEventArgs.Filename. To get the amount of bytes that have been transferred check Count. To display progress using a ProgressBar, use Length as ProgressBar.Max and Position as ProgressBar.Value.

If any error occurred during the asynchronous method call, it would be returned in the handling event. To trap the error, simply put a try/catch block around any access of the parameter e.

Example

The following example demonstrates capturing file transfer progress info.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFtpServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
Ftp1.BlockSize = 1024

' Set the MaxTransfer Rate to 5 kbps
Ftp1.MaxTransferRate = 5

' Attempt to put multiple files to the server
Try
   Ftp1.Put("C:\Test", "*", "", True)
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Complete!")

' Monitor the progress using the progress event.
Private Sub Ftp1_Progress(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ProgressEventArgs) Handles Ftp1.Progress
   ' Display the currently transferring file
   Label1.Text = "Currently transferring " + e.FileName

   ' Display the total bytes transferred
   Label2.Text = "Total bytes transferred: " + e.Count

   ' Display the current transfer rate
   Label3.Text = "Transfer Rate: " + e.TransferRate

   ' Set the properties of ProgressBar1 (this ProgressBar displays progress
   ' for each individual file)
   ProgressBar1.Minimum = 0
   ProgressBar1.Maximum = e.Length
   ProgressBar1.Value = e.Position

   ' Set the properties of progressBar2 (this ProgressBar displays progress
   ' for all files, useful when transferring multiple files - MPUT).
   ProgressBar2.Minimum = 0
   ProgressBar2.Maximum = e.TotalFiles
   ProgressBar2.Value = e.CurrentFile
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
ftp1.BlockSize = 1024;

// Set the MaxTransferRate to 5 kbps
ftp1.MaxTransferRate = 5;

// Attempt to put multiple files to the server
try
{
   ftp1.Put("C:\\Test", "*", "", true);
}
catch(Exception ex)
{
   Debug.WriteLine("Error: " + ex.Message);
   return;
}

// Success
Debug.WriteLine("Complete!");

// Monitor the progress using the progress event.
private void ftp1_Progress(object sender, Dart.PowerTCP.Ftp.ProgressEventArgs e)
{
   // Display the currently transferring file
   label1.Text = "Currently transferring " + e.FileName;

   // Display the total bytes transferred
   label2.Text = "Total bytes transferred: " + e.Count;

   // Display the current transfer rate
   label3.Text = "Transfer Rate: " + e.TransferRate;

   // Set the properties of progressBar1 (this ProgressBar displays progress
   // for each individual file)
   progressBar1.Minimum = 0;
   progressBar1.Maximum = (int)e.Length;
   progressBar1.Value = (int)e.Position;

   // Set the properties of progressBar2 (this ProgressBar displays progress
   // for all files, useful when transferring multiple files - MPUT).
   progressBar2.Minimum = 0;
   progressBar2.Maximum = (int)e.TotalFiles;
   progressBar2.Value = (int)e.CurrentFile;
}

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

FtpProgressEventArgs Members | Dart.PowerTCP.Ftp Namespace


FtpProgressEventArgs Members

FtpProgressEventArgs overview

Public Instance Properties

Count | Gets the byte count transferred.
CurrentFile | Index of file being transferred.
FileName | Gets the pathname of the file transferred.
Length | The length of the stream.
Position | The position within the stream.
Status | Status of the file (or directory) referenced by FileName.
TotalFiles | Total number of files being transferred.
TransferRate | Gets the current transfer rate in bytes per second.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

FtpProgressEventArgs Class | Dart.PowerTCP.Ftp Namespace


FtpProgressEventArgs Properties

The properties of the FtpProgressEventArgs class are listed below. For a complete list of FtpProgressEventArgs class members, see the FtpProgressEventArgs Members topic.

Public Instance Properties

Count | Gets the byte count transferred.
CurrentFile | Index of file being transferred.
FileName | Gets the pathname of the file transferred.
Length | The length of the stream.
Position | The position within the stream.
Status | Status of the file (or directory) referenced by FileName.
TotalFiles | Total number of files being transferred.
TransferRate | Gets the current transfer rate in bytes per second.

See Also

FtpProgressEventArgs Class | Dart.PowerTCP.Ftp Namespace


Count Property

FtpProgressEventArgs.Count Property

Gets the byte count transferred.

[Visual Basic]
Public Property ReadOnly Count As Long
[C#]
public long Count { get; }
[C++]
public: __property __int64 get_Count();
[JScript]
public function get Count() : long

Property Value

A long representing the number of bytes transferred.

Remarks

This property returns the current number of bytes transferred. The final FtpFileEventArgs.Count may be less than FtpFileEventArgs.Position for transfers that have been restarted.

This property is useful for transfers involving multiple files in displaying a total byte transfer for ALL files.

Example

The following example demonstrates capturing file transfer progress info.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFtpServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
Ftp1.BlockSize = 1024

' Set the MaxTransfer Rate to 5 kbps
Ftp1.MaxTransferRate = 5

' Attempt to put multiple files to the server
Try
   Ftp1.Put("C:\Test", "*", "", True)
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Complete!")

' Monitor the progress using the progress event.
Private Sub Ftp1_Progress(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ProgressEventArgs) Handles Ftp1.Progress
   ' Display the currently transferring file
   Label1.Text = "Currently transferring " + e.FileName

   ' Display the total bytes transferred
   Label2.Text = "Total bytes transferred: " + e.Count

   ' Display the current transfer rate
   Label3.Text = "Transfer Rate: " + e.TransferRate

   ' Set the properties of ProgressBar1 (this ProgressBar displays progress
   ' for each individual file)
   ProgressBar1.Minimum = 0
   ProgressBar1.Maximum = e.Length
   ProgressBar1.Value = e.Position

   ' Set the properties of progressBar2 (this ProgressBar displays progress
   ' for all files, useful when transferring multiple files - MPUT).
   ProgressBar2.Minimum = 0
   ProgressBar2.Maximum = e.TotalFiles
   ProgressBar2.Value = e.CurrentFile
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
ftp1.BlockSize = 1024;

// Set the MaxTransferRate to 5 kbps
ftp1.MaxTransferRate = 5;

// Attempt to put multiple files to the server
try
{
   ftp1.Put("C:\\Test", "*", "", true);
}
catch(Exception ex)
{
   Debug.WriteLine("Error: " + ex.Message);
   return;
}

// Success
Debug.WriteLine("Complete!");

// Monitor the progress using the progress event.
private void ftp1_Progress(object sender, Dart.PowerTCP.Ftp.ProgressEventArgs e)
{
   // Display the currently transferring file
   label1.Text = "Currently transferring " + e.FileName;

   // Display the total bytes transferred
   label2.Text = "Total bytes transferred: " + e.Count;

   // Display the current transfer rate
   label3.Text = "Transfer Rate: " + e.TransferRate;

   // Set the properties of progressBar1 (this ProgressBar displays progress
   // for each individual file)
   progressBar1.Minimum = 0;
   progressBar1.Maximum = (int)e.Length;
   progressBar1.Value = (int)e.Position;

   // Set the properties of progressBar2 (this ProgressBar displays progress
   // for all files, useful when transferring multiple files - MPUT).
   progressBar2.Minimum = 0;
   progressBar2.Maximum = (int)e.TotalFiles;
   progressBar2.Value = (int)e.CurrentFile;
}

See Also

FtpProgressEventArgs Class | Dart.PowerTCP.Ftp Namespace


CurrentFile Property

FtpProgressEventArgs.CurrentFile Property

Index of file being transferred.

[Visual Basic]
Public Property ReadOnly CurrentFile As Long
[C#]
public long CurrentFile { get; }
[C++]
public: __property __int64 get_CurrentFile();
[JScript]
public function get CurrentFile() : long

Property Value

A long representing the index of the current file being transferred.

Remarks

If transferring multiple files, this property will contain the index of the currently transferring file. If transferring a single file, this property will always be 1.

This property is useful for displaying multiple file transfer progress to the user. For example, the application could have two ProgressBar objects, one to track the file transfer progress of individual files, one to track the progress of all files (for an MPUT or MGET).

Example

The following example demonstrates capturing file transfer progress info.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFtpServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
Ftp1.BlockSize = 1024

' Set the MaxTransfer Rate to 5 kbps
Ftp1.MaxTransferRate = 5

' Attempt to put multiple files to the server
Try
   Ftp1.Put("C:\Test", "*", "", True)
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Complete!")

' Monitor the progress using the progress event.
Private Sub Ftp1_Progress(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ProgressEventArgs) Handles Ftp1.Progress
   ' Display the currently transferring file
   Label1.Text = "Currently transferring " + e.FileName

   ' Display the total bytes transferred
   Label2.Text = "Total bytes transferred: " + e.Count

   ' Display the current transfer rate
   Label3.Text = "Transfer Rate: " + e.TransferRate

   ' Set the properties of ProgressBar1 (this ProgressBar displays progress
   ' for each individual file)
   ProgressBar1.Minimum = 0
   ProgressBar1.Maximum = e.Length
   ProgressBar1.Value = e.Position

   ' Set the properties of progressBar2 (this ProgressBar displays progress
   ' for all files, useful when transferring multiple files - MPUT).
   ProgressBar2.Minimum = 0
   ProgressBar2.Maximum = e.TotalFiles
   ProgressBar2.Value = e.CurrentFile
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
ftp1.BlockSize = 1024;

// Set the MaxTransferRate to 5 kbps
ftp1.MaxTransferRate = 5;

// Attempt to put multiple files to the server
try
{
   ftp1.Put("C:\\Test", "*", "", true);
}
catch(Exception ex)
{
   Debug.WriteLine("Error: " + ex.Message);
   return;
}

// Success
Debug.WriteLine("Complete!");

// Monitor the progress using the progress event.
private void ftp1_Progress(object sender, Dart.PowerTCP.Ftp.ProgressEventArgs e)
{
   // Display the currently transferring file
   label1.Text = "Currently transferring " + e.FileName;

   // Display the total bytes transferred
   label2.Text = "Total bytes transferred: " + e.Count;

   // Display the current transfer rate
   label3.Text = "Transfer Rate: " + e.TransferRate;

   // Set the properties of progressBar1 (this ProgressBar displays progress
   // for each individual file)
   progressBar1.Minimum = 0;
   progressBar1.Maximum = (int)e.Length;
   progressBar1.Value = (int)e.Position;

   // Set the properties of progressBar2 (this ProgressBar displays progress
   // for all files, useful when transferring multiple files - MPUT).
   progressBar2.Minimum = 0;
   progressBar2.Maximum = (int)e.TotalFiles;
   progressBar2.Value = (int)e.CurrentFile;
}

See Also

FtpProgressEventArgs Class | Dart.PowerTCP.Ftp Namespace


FileName Property

FtpProgressEventArgs.FileName Property

Gets the pathname of the file transferred.

[Visual Basic]
Public Property ReadOnly FileName As String
[C#]
public string FileName { get; }
[C++]
public: __property String* get_FileName();
[JScript]
public function get FileName() : String

Property Value

A string representing the path and name of the file being transferred.

Remarks

When storing or retrieving files or streams, this property will contain the name of the file on the server. When storing multiple files, this property will contain the pathname of the file being transferred.

The FileName property is useful for displaying to the user the file being transferred. It is also useful if you wish to take some action (for example, make a log entry) based on whether a particular file was downloaded.

Example

The following example demonstrates capturing file transfer progress info.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFtpServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
Ftp1.BlockSize = 1024

' Set the MaxTransfer Rate to 5 kbps
Ftp1.MaxTransferRate = 5

' Attempt to put multiple files to the server
Try
   Ftp1.Put("C:\Test", "*", "", True)
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Complete!")

' Monitor the progress using the progress event.
Private Sub Ftp1_Progress(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ProgressEventArgs) Handles Ftp1.Progress
   ' Display the currently transferring file
   Label1.Text = "Currently transferring " + e.FileName

   ' Display the total bytes transferred
   Label2.Text = "Total bytes transferred: " + e.Count

   ' Display the current transfer rate
   Label3.Text = "Transfer Rate: " + e.TransferRate

   ' Set the properties of ProgressBar1 (this ProgressBar displays progress
   ' for each individual file)
   ProgressBar1.Minimum = 0
   ProgressBar1.Maximum = e.Length
   ProgressBar1.Value = e.Position

   ' Set the properties of progressBar2 (this ProgressBar displays progress
   ' for all files, useful when transferring multiple files - MPUT).
   ProgressBar2.Minimum = 0
   ProgressBar2.Maximum = e.TotalFiles
   ProgressBar2.Value = e.CurrentFile
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
ftp1.BlockSize = 1024;

// Set the MaxTransferRate to 5 kbps
ftp1.MaxTransferRate = 5;

// Attempt to put multiple files to the server
try
{
   ftp1.Put("C:\\Test", "*", "", true);
}
catch(Exception ex)
{
   Debug.WriteLine("Error: " + ex.Message);
   return;
}

// Success
Debug.WriteLine("Complete!");

// Monitor the progress using the progress event.
private void ftp1_Progress(object sender, Dart.PowerTCP.Ftp.ProgressEventArgs e)
{
   // Display the currently transferring file
   label1.Text = "Currently transferring " + e.FileName;

   // Display the total bytes transferred
   label2.Text = "Total bytes transferred: " + e.Count;

   // Display the current transfer rate
   label3.Text = "Transfer Rate: " + e.TransferRate;

   // Set the properties of progressBar1 (this ProgressBar displays progress
   // for each individual file)
   progressBar1.Minimum = 0;
   progressBar1.Maximum = (int)e.Length;
   progressBar1.Value = (int)e.Position;

   // Set the properties of progressBar2 (this ProgressBar displays progress
   // for all files, useful when transferring multiple files - MPUT).
   progressBar2.Minimum = 0;
   progressBar2.Maximum = (int)e.TotalFiles;
   progressBar2.Value = (int)e.CurrentFile;
}

See Also

FtpProgressEventArgs Class | Dart.PowerTCP.Ftp Namespace


Length Property

FtpProgressEventArgs.Length Property

The length of the stream.

[Visual Basic]
Public Property ReadOnly Length As Long
[C#]
public long Length { get; }
[C++]
public: __property __int64 get_Length();
[JScript]
public function get Length() : long

Property Value

A long representing the number in bytes of the length of the stream.

Remarks

This value represents the number in bytes of the length of the Stream of the message being retrieved at the time the Object.Progress event was raised. This is useful for displaying progress as Object.Position divided by Object.Length gives the percentage complete.

Object.Position will equal Object.Length when all data has been transferred.

Example

The following example demonstrates capturing file transfer progress info.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFtpServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
Ftp1.BlockSize = 1024

' Set the MaxTransfer Rate to 5 kbps
Ftp1.MaxTransferRate = 5

' Attempt to put multiple files to the server
Try
   Ftp1.Put("C:\Test", "*", "", True)
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Complete!")

' Monitor the progress using the progress event.
Private Sub Ftp1_Progress(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ProgressEventArgs) Handles Ftp1.Progress
   ' Display the currently transferring file
   Label1.Text = "Currently transferring " + e.FileName

   ' Display the total bytes transferred
   Label2.Text = "Total bytes transferred: " + e.Count

   ' Display the current transfer rate
   Label3.Text = "Transfer Rate: " + e.TransferRate

   ' Set the properties of ProgressBar1 (this ProgressBar displays progress
   ' for each individual file)
   ProgressBar1.Minimum = 0
   ProgressBar1.Maximum = e.Length
   ProgressBar1.Value = e.Position

   ' Set the properties of progressBar2 (this ProgressBar displays progress
   ' for all files, useful when transferring multiple files - MPUT).
   ProgressBar2.Minimum = 0
   ProgressBar2.Maximum = e.TotalFiles
   ProgressBar2.Value = e.CurrentFile
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
ftp1.BlockSize = 1024;

// Set the MaxTransferRate to 5 kbps
ftp1.MaxTransferRate = 5;

// Attempt to put multiple files to the server
try
{
   ftp1.Put("C:\\Test", "*", "", true);
}
catch(Exception ex)
{
   Debug.WriteLine("Error: " + ex.Message);
   return;
}

// Success
Debug.WriteLine("Complete!");

// Monitor the progress using the progress event.
private void ftp1_Progress(object sender, Dart.PowerTCP.Ftp.ProgressEventArgs e)
{
   // Display the currently transferring file
   label1.Text = "Currently transferring " + e.FileName;

   // Display the total bytes transferred
   label2.Text = "Total bytes transferred: " + e.Count;

   // Display the current transfer rate
   label3.Text = "Transfer Rate: " + e.TransferRate;

   // Set the properties of progressBar1 (this ProgressBar displays progress
   // for each individual file)
   progressBar1.Minimum = 0;
   progressBar1.Maximum = (int)e.Length;
   progressBar1.Value = (int)e.Position;

   // Set the properties of progressBar2 (this ProgressBar displays progress
   // for all files, useful when transferring multiple files - MPUT).
   progressBar2.Minimum = 0;
   progressBar2.Maximum = (int)e.TotalFiles;
   progressBar2.Value = (int)e.CurrentFile;
}

See Also

FtpProgressEventArgs Class | Dart.PowerTCP.Ftp Namespace


Position Property

FtpProgressEventArgs.Position Property

The position within the stream.

[Visual Basic]
Public Property ReadOnly Position As Long
[C#]
public long Position { get; }
[C++]
public: __property __int64 get_Position();
[JScript]
public function get Position() : long

Property Value

A long representing the current position within the stream.

Remarks

This value represents the position within the Stream of the message being retrieved at the time the Object.Progress event was raised. This is useful for displaying progress as Object.Position divided by Object.Length gives the percentage complete.

Object.Position will equal Object.Length when all data has been transferred.

Example

The following example demonstrates capturing file transfer progress info.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFtpServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
Ftp1.BlockSize = 1024

' Set the MaxTransfer Rate to 5 kbps
Ftp1.MaxTransferRate = 5

' Attempt to put multiple files to the server
Try
   Ftp1.Put("C:\Test", "*", "", True)
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Complete!")

' Monitor the progress using the progress event.
Private Sub Ftp1_Progress(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ProgressEventArgs) Handles Ftp1.Progress
   ' Display the currently transferring file
   Label1.Text = "Currently transferring " + e.FileName

   ' Display the total bytes transferred
   Label2.Text = "Total bytes transferred: " + e.Count

   ' Display the current transfer rate
   Label3.Text = "Transfer Rate: " + e.TransferRate

   ' Set the properties of ProgressBar1 (this ProgressBar displays progress
   ' for each individual file)
   ProgressBar1.Minimum = 0
   ProgressBar1.Maximum = e.Length
   ProgressBar1.Value = e.Position

   ' Set the properties of progressBar2 (this ProgressBar displays progress
   ' for all files, useful when transferring multiple files - MPUT).
   ProgressBar2.Minimum = 0
   ProgressBar2.Maximum = e.TotalFiles
   ProgressBar2.Value = e.CurrentFile
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
ftp1.BlockSize = 1024;

// Set the MaxTransferRate to 5 kbps
ftp1.MaxTransferRate = 5;

// Attempt to put multiple files to the server
try
{
   ftp1.Put("C:\\Test", "*", "", true);
}
catch(Exception ex)
{
   Debug.WriteLine("Error: " + ex.Message);
   return;
}

// Success
Debug.WriteLine("Complete!");

// Monitor the progress using the progress event.
private void ftp1_Progress(object sender, Dart.PowerTCP.Ftp.ProgressEventArgs e)
{
   // Display the currently transferring file
   label1.Text = "Currently transferring " + e.FileName;

   // Display the total bytes transferred
   label2.Text = "Total bytes transferred: " + e.Count;

   // Display the current transfer rate
   label3.Text = "Transfer Rate: " + e.TransferRate;

   // Set the properties of progressBar1 (this ProgressBar displays progress
   // for each individual file)
   progressBar1.Minimum = 0;
   progressBar1.Maximum = (int)e.Length;
   progressBar1.Value = (int)e.Position;

   // Set the properties of progressBar2 (this ProgressBar displays progress
   // for all files, useful when transferring multiple files - MPUT).
   progressBar2.Minimum = 0;
   progressBar2.Maximum = (int)e.TotalFiles;
   progressBar2.Value = (int)e.CurrentFile;
}

See Also

FtpProgressEventArgs Class | Dart.PowerTCP.Ftp Namespace


Status Property

FtpProgressEventArgs.Status Property

Status of the file (or directory) referenced by FileName.

[Visual Basic]
Public Property ReadOnly Status As FtpFileStatus
[C#]
public FtpFileStatus Status { get; }
[C++]
public: __property FtpFileStatus get_Status();
[JScript]
public function get Status() : FtpFileStatus

See Also

FtpProgressEventArgs Class | Dart.PowerTCP.Ftp Namespace


TotalFiles Property

FtpProgressEventArgs.TotalFiles Property

Total number of files being transferred.

[Visual Basic]
Public Property ReadOnly TotalFiles As Long
[C#]
public long TotalFiles { get; }
[C++]
public: __property __int64 get_TotalFiles();
[JScript]
public function get TotalFiles() : long

Property Value

A long representing the total number of files being transferred.

Remarks

If transferring multiple files, this property will contain the total number of all files being transferred. If transferring a single file, this property will always be 1.

This property is useful for displaying multiple file transfer progress to the user. For example, the application could have two ProgressBar objects, one to track the file transfer progress of individual files, one to track the progress of all files transferred (for an MPUT or MGET).

Example

The following example demonstrates capturing file transfer progress info.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFtpServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
Ftp1.BlockSize = 1024

' Set the MaxTransfer Rate to 5 kbps
Ftp1.MaxTransferRate = 5

' Attempt to put multiple files to the server
Try
   Ftp1.Put("C:\Test", "*", "", True)
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Complete!")

' Monitor the progress using the progress event.
Private Sub Ftp1_Progress(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ProgressEventArgs) Handles Ftp1.Progress
   ' Display the currently transferring file
   Label1.Text = "Currently transferring " + e.FileName

   ' Display the total bytes transferred
   Label2.Text = "Total bytes transferred: " + e.Count

   ' Display the current transfer rate
   Label3.Text = "Transfer Rate: " + e.TransferRate

   ' Set the properties of ProgressBar1 (this ProgressBar displays progress
   ' for each individual file)
   ProgressBar1.Minimum = 0
   ProgressBar1.Maximum = e.Length
   ProgressBar1.Value = e.Position

   ' Set the properties of progressBar2 (this ProgressBar displays progress
   ' for all files, useful when transferring multiple files - MPUT).
   ProgressBar2.Minimum = 0
   ProgressBar2.Maximum = e.TotalFiles
   ProgressBar2.Value = e.CurrentFile
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
ftp1.BlockSize = 1024;

// Set the MaxTransferRate to 5 kbps
ftp1.MaxTransferRate = 5;

// Attempt to put multiple files to the server
try
{
   ftp1.Put("C:\\Test", "*", "", true);
}
catch(Exception ex)
{
   Debug.WriteLine("Error: " + ex.Message);
   return;
}

// Success
Debug.WriteLine("Complete!");

// Monitor the progress using the progress event.
private void ftp1_Progress(object sender, Dart.PowerTCP.Ftp.ProgressEventArgs e)
{
   // Display the currently transferring file
   label1.Text = "Currently transferring " + e.FileName;

   // Display the total bytes transferred
   label2.Text = "Total bytes transferred: " + e.Count;

   // Display the current transfer rate
   label3.Text = "Transfer Rate: " + e.TransferRate;

   // Set the properties of progressBar1 (this ProgressBar displays progress
   // for each individual file)
   progressBar1.Minimum = 0;
   progressBar1.Maximum = (int)e.Length;
   progressBar1.Value = (int)e.Position;

   // Set the properties of progressBar2 (this ProgressBar displays progress
   // for all files, useful when transferring multiple files - MPUT).
   progressBar2.Minimum = 0;
   progressBar2.Maximum = (int)e.TotalFiles;
   progressBar2.Value = (int)e.CurrentFile;
}

See Also

FtpProgressEventArgs Class | Dart.PowerTCP.Ftp Namespace


TransferRate Property

FtpProgressEventArgs.TransferRate Property

Gets the current transfer rate in bytes per second.

[Visual Basic]
Public Property ReadOnly TransferRate As Long
[C#]
public long TransferRate { get; }
[C++]
public: __property __int64 get_TransferRate();
[JScript]
public function get TransferRate() : long

Property Value

A long representing the file transfer rate.

Remarks

The transfer rate can be controlled with the MaxTransferRate property. The value represents the rate seen between calls made to the Progress event. By default operation, the Ftp component will use all available bandwidth.

Example

The following example demonstrates capturing file transfer progress info.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFtpServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
Ftp1.BlockSize = 1024

' Set the MaxTransfer Rate to 5 kbps
Ftp1.MaxTransferRate = 5

' Attempt to put multiple files to the server
Try
   Ftp1.Put("C:\Test", "*", "", True)
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Complete!")

' Monitor the progress using the progress event.
Private Sub Ftp1_Progress(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ProgressEventArgs) Handles Ftp1.Progress
   ' Display the currently transferring file
   Label1.Text = "Currently transferring " + e.FileName

   ' Display the total bytes transferred
   Label2.Text = "Total bytes transferred: " + e.Count

   ' Display the current transfer rate
   Label3.Text = "Transfer Rate: " + e.TransferRate

   ' Set the properties of ProgressBar1 (this ProgressBar displays progress
   ' for each individual file)
   ProgressBar1.Minimum = 0
   ProgressBar1.Maximum = e.Length
   ProgressBar1.Value = e.Position

   ' Set the properties of progressBar2 (this ProgressBar displays progress
   ' for all files, useful when transferring multiple files - MPUT).
   ProgressBar2.Minimum = 0
   ProgressBar2.Maximum = e.TotalFiles
   ProgressBar2.Value = e.CurrentFile
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFtpServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set FtpProgressEvent to raise every 1024 K processed (default is 8096).
ftp1.BlockSize = 1024;

// Set the MaxTransferRate to 5 kbps
ftp1.MaxTransferRate = 5;

// Attempt to put multiple files to the server
try
{
   ftp1.Put("C:\\Test", "*", "", true);
}
catch(Exception ex)
{
   Debug.WriteLine("Error: " + ex.Message);
   return;
}

// Success
Debug.WriteLine("Complete!");

// Monitor the progress using the progress event.
private void ftp1_Progress(object sender, Dart.PowerTCP.Ftp.ProgressEventArgs e)
{
   // Display the currently transferring file
   label1.Text = "Currently transferring " + e.FileName;

   // Display the total bytes transferred
   label2.Text = "Total bytes transferred: " + e.Count;

   // Display the current transfer rate
   label3.Text = "Transfer Rate: " + e.TransferRate;

   // Set the properties of progressBar1 (this ProgressBar displays progress
   // for each individual file)
   progressBar1.Minimum = 0;
   progressBar1.Maximum = (int)e.Length;
   progressBar1.Value = (int)e.Position;

   // Set the properties of progressBar2 (this ProgressBar displays progress
   // for all files, useful when transferring multiple files - MPUT).
   progressBar2.Minimum = 0;
   progressBar2.Maximum = (int)e.TotalFiles;
   progressBar2.Value = (int)e.CurrentFile;
}

See Also

FtpProgressEventArgs Class | Dart.PowerTCP.Ftp Namespace


FtpProgressEventHandler Delegate

Represents the method (event handler) that will be raised when file transfer information is available.

[Visual Basic]
Public Delegate Function Sub  FtpProgressEventHandler( _
   ByVal sender As Object, _
   ByVal e As FtpProgressEventArgs _
)
[C#]
public delegate void FtpProgressEventHandler(
   object sender,
   FtpProgressEventArgs e
)
[C++]
public __gc __delegate void FtpProgressEventHandler(
   Object* sender,
   FtpProgressEventArgs* e
)

[JScript] In JScript, you can use the delegates defined by a type, but you cannot define your own.

Parameters

sender
The source of the event.
e
An FtpProgressEventArgs object that contains the event data.

Remarks

As Microsoft describes in their MSDN documentation, the event model in the .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed:

  • A class that holds the event data. This class must derive from the base class EventArgs.
  • A delegate that points to a method that provides the response to the event.

When capturing file transfer information is desired, the class that holds the event data is the FtpProgressEventArgs class. A method must be created with the same signature as the delegate. If you are working within the Visual Studio.NET environment, this can be automatically done for you. See the "Using Events In PowerTCP" topic for more information. If you are not working within the Visual Studio.NET environment, you must do this yourself. In this example that would mean a method would have to be defined to accept two arguments (an object and an FtpProgressEventArgs) and return void. Once this has been done, the delegate must be "connected" to the handling event. This is done by adding an instance of the delegate to the event (see examples below).

For more information about event handler delegates, see the "Using Events In PowerTCP" topic.

Example

The following example demonstrates how to assign an event handler to an event.

[Visual Basic]
' *** Progress Event ***

' You can either use the AddHandler statement to associate an event with an event handler in your init code
AddHandler Ftp1.Progress, New Dart.PowerTCP.Ftp.ProgressEventHandler(AddressOf Ftp1_Progress)

' Or you can use the Handles keyword to associate an event handler with an event
Private Sub Ftp1_Progress(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ProgressEventArgs) Handles Ftp1.Progress

[C#]
// Progress event
this.ftp1.Progress += new Dart.PowerTCP.Ftp.ProgressEventHandler(this.ftp1_Progress);

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


FtpProxy Class

The FtpProxy class provides an easy way to manage communication with FTP proxy servers when transferring files.

For a list of all members of this type, see FtpProxy Members.

System.Object
Dart.PowerTCP.Ftp.FtpProxy

[Visual Basic]
Public Class FtpProxy
[C#]
public class FtpProxy
[C++]
public __gc class FtpProxy
[JScript]
public class FtpProxy

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

The FtpProxy class provides extensive native support for proxy servers. Simply set the appropriate properties of the FtpProxy class and proxy communication occurs transparently.

Example

The following example demonstrates basic proxy use.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in/log out taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set Proxy properties and all proxy issues will be handled "behind the scenes"
Ftp1.Proxy.Server = "MyProxy"
Ftp1.Proxy.ServerPort = 8888
Ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.Socks5
Ftp1.Proxy.Username = "proxyblah"
Ftp1.Proxy.Password = "myproxypass"

Dim FileToStore As String = "c:\FtpTest\mypic.gif"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to store file " + FileToStore)

' Store the file
Try
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set Proxy properties and all proxy issues will be handled "behind the scenes"
ftp1.Proxy.Server = "MyProxy";
ftp1.Proxy.ServerPort = 8888;
ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.User;
ftp1.Proxy.Username = "proxyblah";
ftp1.Proxy.Password = "myproxypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

// Put method returns an FtpFile object containing information about the file
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

// Store the file
try
{
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

FtpProxy Members | Dart.PowerTCP.Ftp Namespace


FtpProxy Members

FtpProxy overview

Public Instance Constructors

FtpProxy Constructor Initializes a new instance of the FtpProxy class.

Public Instance Properties

Password | Password to use when authenticating to an FTP proxy.
Server | Get or set a value which specifies the FTP Proxy to use.
ServerPort | Port to use when connecting to an FTP Proxy.
Type | Type of FTP proxy.
Username | Username to use when authenticating to an FTP proxy.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

FtpProxy Class | Dart.PowerTCP.Ftp Namespace


FtpProxy Constructor

Initializes a new instance of the FtpProxy class.

[Visual Basic]
Public Sub New()
[C#]
public FtpProxy();
[C++]
public: FtpProxy();
[JScript]
public function FtpProxy();

Remarks

The default constructor initializes a new instance of the FtpProxy class.

Example

The following example demonstrates creating an FtpProxy object.

[Visual Basic]
' Declare as class member
Friend WithEvents FtpProxy1 As Dart.PowerTCP.Ftp.FtpProxy

' Create in class initilization
Me.FtpProxy1 = New Dart.PowerTCP.Ftp.FtpProxy

[C#]
private Dart.PowerTCP.Ftp.FtpProxy FtpProxy1 = new Dart.PowerTCP.Ftp.FtpProxy();

See Also

FtpProxy Class | Dart.PowerTCP.Ftp Namespace


FtpProxy Properties

The properties of the FtpProxy class are listed below. For a complete list of FtpProxy class members, see the FtpProxy Members topic.

Public Instance Properties

Password | Password to use when authenticating to an FTP proxy.
Server | Get or set a value which specifies the FTP Proxy to use.
ServerPort | Port to use when connecting to an FTP Proxy.
Type | Type of FTP proxy.
Username | Username to use when authenticating to an FTP proxy.

See Also

FtpProxy Class | Dart.PowerTCP.Ftp Namespace


Password Property

FtpProxy.Password Property

Password to use when authenticating to an FTP proxy.

[Visual Basic]
Public Property Password As String
[C#]
public string Password { get; set; }
[C++]
public: __property String* get_Password();
public: __property void set_Password(String* );
[JScript]
public function get Password() : String
public function set Password(String);

Property Value

A string value representing the password used to access the FTP proxy.

Remarks

Specifies the password to use for authentication on some proxies. Set this property if you are using a Socks4, Socks5, Site (optional), or User (optional) proxy.

Example

The following example demonstrates basic proxy use.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in/log out taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set Proxy properties and all proxy issues will be handled "behind the scenes"
Ftp1.Proxy.Server = "MyProxy"
Ftp1.Proxy.ServerPort = 8888
Ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.Socks5
Ftp1.Proxy.Username = "proxyblah"
Ftp1.Proxy.Password = "myproxypass"

Dim FileToStore As String = "c:\FtpTest\mypic.gif"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to store file " + FileToStore)

' Store the file
Try
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set Proxy properties and all proxy issues will be handled "behind the scenes"
ftp1.Proxy.Server = "MyProxy";
ftp1.Proxy.ServerPort = 8888;
ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.User;
ftp1.Proxy.Username = "proxyblah";
ftp1.Proxy.Password = "myproxypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

// Put method returns an FtpFile object containing information about the file
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

// Store the file
try
{
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

See Also

FtpProxy Class | Dart.PowerTCP.Ftp Namespace


Server Property

FtpProxy.Server Property

Get or set a value which specifies the FTP Proxy to use.

[Visual Basic]
Public Property Server As String
[C#]
public string Server { get; set; }
[C++]
public: __property String* get_Server();
public: __property void set_Server(String* );
[JScript]
public function get Server() : String
public function set Server(String);

Property Value

A string representing the FTP Proxy to use.

Remarks

Specifies the hostname of the proxy server. Specify the server either in dot notation ("111.111.111.111") or by host name ("myserver"). Use this property if you are using a Socks4, Socks5, Site, User, or Pipe proxy.

Example

The following example demonstrates basic proxy use.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in/log out taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set Proxy properties and all proxy issues will be handled "behind the scenes"
Ftp1.Proxy.Server = "MyProxy"
Ftp1.Proxy.ServerPort = 8888
Ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.Socks5
Ftp1.Proxy.Username = "proxyblah"
Ftp1.Proxy.Password = "myproxypass"

Dim FileToStore As String = "c:\FtpTest\mypic.gif"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to store file " + FileToStore)

' Store the file
Try
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set Proxy properties and all proxy issues will be handled "behind the scenes"
ftp1.Proxy.Server = "MyProxy";
ftp1.Proxy.ServerPort = 8888;
ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.User;
ftp1.Proxy.Username = "proxyblah";
ftp1.Proxy.Password = "myproxypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

// Put method returns an FtpFile object containing information about the file
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

// Store the file
try
{
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

See Also

FtpProxy Class | Dart.PowerTCP.Ftp Namespace


ServerPort Property

FtpProxy.ServerPort Property

Port to use when connecting to an FTP Proxy.

[Visual Basic]
Public Property ServerPort As Integer
[C#]
public int ServerPort { get; set; }
[C++]
public: __property int get_ServerPort();
public: __property void set_ServerPort(int );
[JScript]
public function get ServerPort() : int
public function set ServerPort(int);

Property Value

An integer value representing the FTP Proxy port to connect to.

Remarks

Specifies the port to use when connecting to the proxy server. Set this property if you are using a Socks4, Socks5, Site, User, or Pipe proxy.

Example

The following example demonstrates basic proxy use.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in/log out taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set Proxy properties and all proxy issues will be handled "behind the scenes"
Ftp1.Proxy.Server = "MyProxy"
Ftp1.Proxy.ServerPort = 8888
Ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.Socks5
Ftp1.Proxy.Username = "proxyblah"
Ftp1.Proxy.Password = "myproxypass"

Dim FileToStore As String = "c:\FtpTest\mypic.gif"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to store file " + FileToStore)

' Store the file
Try
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set Proxy properties and all proxy issues will be handled "behind the scenes"
ftp1.Proxy.Server = "MyProxy";
ftp1.Proxy.ServerPort = 8888;
ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.User;
ftp1.Proxy.Username = "proxyblah";
ftp1.Proxy.Password = "myproxypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

// Put method returns an FtpFile object containing information about the file
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

// Store the file
try
{
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

See Also

FtpProxy Class | Dart.PowerTCP.Ftp Namespace


Type Property

FtpProxy.Type Property

Type of FTP proxy.

[Visual Basic]
Public Property Type As FtpProxyType
[C#]
public FtpProxyType Type { get; set; }
[C++]
public: __property FtpProxyType get_Type();
public: __property void set_Type(FtpProxyType );
[JScript]
public function get Type() : FtpProxyType
public function set Type(FtpProxyType);

Property Value

One of the FtpProxyType values.

Remarks

Specifies the type of proxy. Set this property to specify the type of proxy server for the connection, or else use FtpProxyType.None if no proxy server will be used.

Example

The following example demonstrates basic proxy use.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in/log out taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set Proxy properties and all proxy issues will be handled "behind the scenes"
Ftp1.Proxy.Server = "MyProxy"
Ftp1.Proxy.ServerPort = 8888
Ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.Socks5
Ftp1.Proxy.Username = "proxyblah"
Ftp1.Proxy.Password = "myproxypass"

Dim FileToStore As String = "c:\FtpTest\mypic.gif"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to store file " + FileToStore)

' Store the file
Try
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set Proxy properties and all proxy issues will be handled "behind the scenes"
ftp1.Proxy.Server = "MyProxy";
ftp1.Proxy.ServerPort = 8888;
ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.User;
ftp1.Proxy.Username = "proxyblah";
ftp1.Proxy.Password = "myproxypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

// Put method returns an FtpFile object containing information about the file
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

// Store the file
try
{
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

See Also

FtpProxy Class | Dart.PowerTCP.Ftp Namespace


Username Property

FtpProxy.Username Property

Username to use when authenticating to an FTP proxy.

[Visual Basic]
Public Property Username As String
[C#]
public string Username { get; set; }
[C++]
public: __property String* get_Username();
public: __property void set_Username(String* );
[JScript]
public function get Username() : String
public function set Username(String);

Property Value

A string value representing the username used to access the FTP proxy.

Remarks

Specifies the username to use for authentication on some proxies. Set this property if you are using a Socks4, Socks5, Site (optional), or User (optional) proxy.

Example

The following example demonstrates basic proxy use.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in/log out taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set Proxy properties and all proxy issues will be handled "behind the scenes"
Ftp1.Proxy.Server = "MyProxy"
Ftp1.Proxy.ServerPort = 8888
Ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.Socks5
Ftp1.Proxy.Username = "proxyblah"
Ftp1.Proxy.Password = "myproxypass"

Dim FileToStore As String = "c:\FtpTest\mypic.gif"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to store file " + FileToStore)

' Store the file
Try
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set Proxy properties and all proxy issues will be handled "behind the scenes"
ftp1.Proxy.Server = "MyProxy";
ftp1.Proxy.ServerPort = 8888;
ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.User;
ftp1.Proxy.Username = "proxyblah";
ftp1.Proxy.Password = "myproxypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

// Put method returns an FtpFile object containing information about the file
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

// Store the file
try
{
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

See Also

FtpProxy Class | Dart.PowerTCP.Ftp Namespace


FtpProxyType Enumeration

Enumerates the supported proxy types for FTP.

[Visual Basic]
Public Enum FtpProxyType
[C#]
public enum FtpProxyType
[C++]
public __value enum FtpProxyType
[JScript]
public enum FtpProxyType

Remarks

This enumeration is used by the Proxy property. Set the Type property to the proper FtpProxyType of your proxy server before calling any method that requires communication with the server.

For more information on using the Ftp component with proxies, see the topic Proxy Support Overview.

Example

The following example demonstrates basic proxy use.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in/log out taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Set Proxy properties and all proxy issues will be handled "behind the scenes"
Ftp1.Proxy.Server = "MyProxy"
Ftp1.Proxy.ServerPort = 8888
Ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.Socks5
Ftp1.Proxy.Username = "proxyblah"
Ftp1.Proxy.Password = "myproxypass"

Dim FileToStore As String = "c:\FtpTest\mypic.gif"

' File is an image
Ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

' Put method returns an FtpFile object containing information about the file
Dim file As Dart.PowerTCP.Ftp.FtpFile

Debug.WriteLine("Attempting to store file " + FileToStore)

' Store the file
Try
   file = Ftp1.Put(FileToStore, New System.IO.FileInfo(FileToStore).Name)
Catch ex As Exception
   Debug.WriteLine("Error " + ex.Message)
   Return
End Try

' Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName)
Debug.WriteLine("File now on server as " + file.RemoteFileName)
Debug.WriteLine("Size of file " + file.Length.ToString())
Debug.WriteLine("Data transferred " + file.Count.ToString())

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Set Proxy properties and all proxy issues will be handled "behind the scenes"
ftp1.Proxy.Server = "MyProxy";
ftp1.Proxy.ServerPort = 8888;
ftp1.Proxy.Type = Dart.PowerTCP.Ftp.FtpProxyType.User;
ftp1.Proxy.Username = "proxyblah";
ftp1.Proxy.Password = "myproxypass";

string FileToStore = "C:\\FtpTest\\MyPic.gif";

// File is an image
ftp1.FileType = Dart.PowerTCP.Ftp.FileType.Image

// Put method returns an FtpFile object containing information about the file
Dart.PowerTCP.Ftp.FtpFile file;

Debug.WriteLine("Attempting to store file " + FileToStore);

// Store the file
try
{
    file = ftp1.Put(FileToStore, new System.IO.FileInfo(FileToStore).Name);
}
catch(Exception ex)
{
    Debug.WriteLine("Error: " + ex.Message);
    return;
}

// Success! Display info about the file transferred.
Debug.WriteLine("Successfully stored file " + file.LocalFileName);
Debug.WriteLine("File now on server as " + file.RemoteFileName);
Debug.WriteLine("Size of file " + file.Length.ToString());
Debug.WriteLine("Data transferred " + file.Count.ToString());

Members

Member Name | Description
None | No proxy server is used.
Socks4 | SOCKS v4 proxy.
Socks5 | SOCKS v5 proxy.
Site | SITE proxy sends a SITE command to connect to the FTP server.
User | USER proxy sends a USER command to connect to the FTP server.
Open | OPEN proxy sends an OPEN command to connect to the FTP server.
Pipe | PIPE proxy is pre-configured to connect to the FTP server.
HttpConnect | HttpConnect proxy sends a CONNECT command to an HTTP proxy to connect to the FTP server.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


FtpWebRequest Class

Provides an FTP-specific implementation of the WebRequest class.

For a list of all members of this type, see FtpWebRequest Members.

System.Object
System.MarshalByRefObject
System.Net.WebRequest
Dart.PowerTCP.Ftp.FtpWebRequest

[Visual Basic]
Public Class FtpWebRequest
    Inherits WebRequest
[C#]
public class FtpWebRequest : WebRequest
[C++]
public __gc class FtpWebRequest : public WebRequest
[JScript]
public class FtpWebRequest extends WebRequest

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

The FtpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using FTP.

Do not use the FtpWebRequest constructor. Use the WebRequest.Create method to initialize new FtpWebRequest instances. If the scheme for the URI is ftp://, WebRequest.Create returns an FtpWebRequest instance.

The GetResponse method makes a synchronous request to the Internet resource specified in the RequestUri property and returns an FtpWebResponse instance containing the response.

Example

The following example demonstrates using the WebRequest/Response classes to get a file using FTP.

[Visual Basic]
' Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", New Dart.PowerTCP.Ftp.FtpWebRequestCreator())

' Create Request object (this will be anonymous FTP)
Dim req As Dart.PowerTCP.Ftp.FtpWebRequest
req = System.Net.WebRequest.Create("ftp://myServer/file.txt")

req.Password = "pass"
req.Username = "user"

' Get response
Dim res As Dart.PowerTCP.Ftp.FtpWebResponse = req.GetResponse

' Get response content
Dim stream1 As System.IO.Stream = res.GetResponseStream()

' Create file stream to write content to file
Dim fstream As System.IO.FileStream
fstream = New System.IO.FileStream("c:\FtpTest\file.txt", System.IO.FileMode.Create)

Dim buffer(8096) As Byte
Dim count As Integer

count = -1
Do While (count <> 0)

   ' Read content into a buffer
   count = stream1.Read(buffer, 0, buffer.Length)

   ' Write content to a file
   fstream.Write(buffer, 0, count)

Loop

' Close the file
fstream.Close()

[C#]
// Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", new Dart.PowerTCP.Ftp.FtpWebRequestCreator());

// Create Request object (this will be anonymous FTP)
Dart.PowerTCP.Ftp.FtpWebRequest req =
(Dart.PowerTCP.Ftp.FtpWebRequest)System.Net.WebRequest.Create("ftp://myServer//file.txt");

req.Username = "user";
req.Password = "pass";

// Get response
System.Net.WebResponse res = req.GetResponse();

// Get response content
System.IO.Stream stream1 = res.GetResponseStream();

// Create file stream to write content to file
System.IO.FileStream fstream = new System.IO.FileStream("c:\\FtpTest\\file.txt", System.IO.FileMode.Create);

byte[] buffer = new byte[8096];
int count = -1;

do
{
    // Read content into a buffer
    count = stream1.Read(buffer, 0, buffer.Length);

    // Write content to a file
    fstream.Write(buffer, 0, count);
}
while (count != 0);

// Close the file
fstream.Close();

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

FtpWebRequest Members | Dart.PowerTCP.Ftp Namespace


FtpWebRequest Members

FtpWebRequest overview

Public Instance Constructors

FtpWebRequest Constructor Initializes a new instance of the FtpWebRequest class.

Public Instance Properties

ConnectionGroupName | Overridden. Gets or sets the name of the connection group for the request. This property always throws a NotSupportedException.
ContentLength | Overridden. Gets or sets the name of the connection group for the request. This property always throws a NotSupportedException.
ContentType | Overridden. Gets or sets the value of the Content-type HTTP header. This property always throws a NotSupportedException.
Credentials | Overridden. Provides authentication information for the request.
Ftp | The Ftp instance used to make the FtpWebRequest.
Headers | Overridden. Gets a collection of the name/value pairs that make up the HTTP headers. This property always throws a NotSupportedException.
Method | Overridden. Gets or sets the method for the request. This property always throws a NotSupportedException.
Password | Gets or sets the password to use for authentication
PreAuthenticate | Overridden. Gets or sets a value indicating whether to send a preauthentication header with the request. This property always throws a NotSupportedException.
Proxy | Overridden. Gets or sets proxy information for the request. This property always throws a NotSupportedException.
RequestUri | Overridden. Gets the original Uri of the request.
Timeout | Overridden. Gets or sets the timeout value for a request.
Username | Gets or sets the username to use for authentication

Public Instance Methods

Abort | Overridden. Cancels an FTP request for an Internet resource.
BeginGetRequestStream | Overridden. Starts an asynchronous request for a Stream used to send file data to an Internet resource.
BeginGetResponse | Overridden. Begins an asynchronous request for an Internet file using FTP.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
EndGetRequestStream | Overridden. Completes an asynchronous stream request that was started by the BeginGetRequestStream() method.
EndGetResponse | Overridden. Completes an asynchronous request for an Internet resource that was started with the BeginGetResponse method.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetRequestStream | Overridden. Returns a Stream for writing file data to the Internet resource specified by the Uri property.
GetResponse | Overridden. Sends a request to an Internet resource and returns a WebResponse instance (file).
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


FtpWebRequest Constructor

Initializes a new instance of the FtpWebRequest class.

[Visual Basic]
Public Sub New( _
   ByVal uri As Uri _
)
[C#]
public FtpWebRequest(
   Uri uri
);
[C++]
public: FtpWebRequest(
   Uri* uri
);
[JScript]
public function FtpWebRequest(
   Uri uri
);

Parameters

uri
A Uri containing the URI of the requested resource.

Remarks

Do not use the FtpWebRequest constructor. Use the WebRequest.Createmethod to initialize new FtpWebRequest instances. If the scheme for the URI is ftp://, WebRequest.Create returns an FtpWebRequest instance.

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


FtpWebRequest Properties

The properties of the FtpWebRequest class are listed below. For a complete list of FtpWebRequest class members, see the FtpWebRequest Members topic.

Public Instance Properties

ConnectionGroupName | Overridden. Gets or sets the name of the connection group for the request. This property always throws a NotSupportedException.
ContentLength | Overridden. Gets or sets the name of the connection group for the request. This property always throws a NotSupportedException.
ContentType | Overridden. Gets or sets the value of the Content-type HTTP header. This property always throws a NotSupportedException.
Credentials | Overridden. Provides authentication information for the request.
Ftp | The Ftp instance used to make the FtpWebRequest.
Headers | Overridden. Gets a collection of the name/value pairs that make up the HTTP headers. This property always throws a NotSupportedException.
Method | Overridden. Gets or sets the method for the request. This property always throws a NotSupportedException.
Password | Gets or sets the password to use for authentication
PreAuthenticate | Overridden. Gets or sets a value indicating whether to send a preauthentication header with the request. This property always throws a NotSupportedException.
Proxy | Overridden. Gets or sets proxy information for the request. This property always throws a NotSupportedException.
RequestUri | Overridden. Gets the original Uri of the request.
Timeout | Overridden. Gets or sets the timeout value for a request.
Username | Gets or sets the username to use for authentication

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


ConnectionGroupName Property

FtpWebRequest.ConnectionGroupName Property

Gets or sets the name of the connection group for the request. This property always throws a NotSupportedException.

[Visual Basic]
Overrides Public Property ConnectionGroupName As String
[C#]
public override string ConnectionGroupName { get; set; }
[C++]
public: __property String* get_ConnectionGroupName();
public: __property void set_ConnectionGroupName(String* );
[JScript]
public override function get ConnectionGroupName() : String
public override function set ConnectionGroupName(String);

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


ContentLength Property

FtpWebRequest.ContentLength Property

Gets or sets the name of the connection group for the request. This property always throws a NotSupportedException.

[Visual Basic]
Overrides Public Property ContentLength As Long
[C#]
public override long ContentLength { get; set; }
[C++]
public: __property __int64 get_ContentLength();
public: __property void set_ContentLength(__int64 );
[JScript]
public override function get ContentLength() : long
public override function set ContentLength(long);

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


ContentType Property

FtpWebRequest.ContentType Property

Gets or sets the value of the Content-type HTTP header. This property always throws a NotSupportedException.

[Visual Basic]
Overrides Public Property ContentType As String
[C#]
public override string ContentType { get; set; }
[C++]
public: __property String* get_ContentType();
public: __property void set_ContentType(String* );
[JScript]
public override function get ContentType() : String
public override function set ContentType(String);

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


Credentials Property

FtpWebRequest.Credentials Property

Provides authentication information for the request.

[Visual Basic]
Overrides Public Property Credentials As ICredentials
[C#]
public override ICredentials Credentials { get; set; }
[C++]
public: __property ICredentials* get_Credentials();
public: __property void set_Credentials(ICredentials* );
[JScript]
public override function get Credentials() : ICredentials
public override function set Credentials(ICredentials);

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


Ftp Property

FtpWebRequest.Ftp Property

The Ftp instance used to make the FtpWebRequest.

[Visual Basic]
Public Property ReadOnly Ftp As Ftp
[C#]
public Ftp Ftp { get; }
[C++]
public: __property Ftp* get_Ftp();
[JScript]
public function get Ftp() : Ftp

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


Headers Property

FtpWebRequest.Headers Property

Gets a collection of the name/value pairs that make up the HTTP headers. This property always throws a NotSupportedException.

[Visual Basic]
Overrides Public Property Headers As WebHeaderCollection
[C#]
public override WebHeaderCollection Headers { get; set; }
[C++]
public: __property WebHeaderCollection* get_Headers();
public: __property void set_Headers(WebHeaderCollection* );
[JScript]
public override function get Headers() : WebHeaderCollection
public override function set Headers(WebHeaderCollection);

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


Method Property

FtpWebRequest.Method Property

Gets or sets the method for the request. This property always throws a NotSupportedException.

[Visual Basic]
Overrides Public Property Method As String
[C#]
public override string Method { get; set; }
[C++]
public: __property String* get_Method();
public: __property void set_Method(String* );
[JScript]
public override function get Method() : String
public override function set Method(String);

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


Password Property

FtpWebRequest.Password Property

Gets or sets the password to use for authentication

[Visual Basic]
Public Property Password As String
[C#]
public string Password { get; set; }
[C++]
public: __property String* get_Password();
public: __property void set_Password(String* );
[JScript]
public function get Password() : String
public function set Password(String);

Property Value

A string value to use for authentication.

Remarks

If requesting a resource from a server that requires authentication, this property must be set.

Example

The following example demonstrates using the WebRequest/Response classes to get a file using FTP.

[Visual Basic]
' Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", New Dart.PowerTCP.Ftp.FtpWebRequestCreator())

' Create Request object (this will be anonymous FTP)
Dim req As Dart.PowerTCP.Ftp.FtpWebRequest
req = System.Net.WebRequest.Create("ftp://myServer/file.txt")

req.Password = "pass"
req.Username = "user"

' Get response
Dim res As Dart.PowerTCP.Ftp.FtpWebResponse = req.GetResponse

' Get response content
Dim stream1 As System.IO.Stream = res.GetResponseStream()

' Create file stream to write content to file
Dim fstream As System.IO.FileStream
fstream = New System.IO.FileStream("c:\FtpTest\file.txt", System.IO.FileMode.Create)

Dim buffer(8096) As Byte
Dim count As Integer

count = -1
Do While (count <> 0)

   ' Read content into a buffer
   count = stream1.Read(buffer, 0, buffer.Length)

   ' Write content to a file
   fstream.Write(buffer, 0, count)

Loop

' Close the file
fstream.Close()

[C#]
// Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", new Dart.PowerTCP.Ftp.FtpWebRequestCreator());

// Create Request object (this will be anonymous FTP)
Dart.PowerTCP.Ftp.FtpWebRequest req =
(Dart.PowerTCP.Ftp.FtpWebRequest)System.Net.WebRequest.Create("ftp://myServer//file.txt");

req.Username = "user";
req.Password = "pass";

// Get response
System.Net.WebResponse res = req.GetResponse();

// Get response content
System.IO.Stream stream1 = res.GetResponseStream();

// Create file stream to write content to file
System.IO.FileStream fstream = new System.IO.FileStream("c:\\FtpTest\\file.txt", System.IO.FileMode.Create);

byte[] buffer = new byte[8096];
int count = -1;

do
{
    // Read content into a buffer
    count = stream1.Read(buffer, 0, buffer.Length);

    // Write content to a file
    fstream.Write(buffer, 0, count);
}
while (count != 0);

// Close the file
fstream.Close();

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


PreAuthenticate Property

FtpWebRequest.PreAuthenticate Property

Gets or sets a value indicating whether to send a preauthentication header with the request. This property always throws a NotSupportedException.

[Visual Basic]
Overrides Public Property PreAuthenticate As Boolean
[C#]
public override bool PreAuthenticate { get; set; }
[C++]
public: __property bool get_PreAuthenticate();
public: __property void set_PreAuthenticate(bool );
[JScript]
public override function get PreAuthenticate() : bool
public override function set PreAuthenticate(bool);

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


Proxy Property

FtpWebRequest.Proxy Property

Gets or sets proxy information for the request. This property always throws a NotSupportedException.

[Visual Basic]
Overrides Public Property Proxy As IWebProxy
[C#]
public override IWebProxy Proxy { get; set; }
[C++]
public: __property IWebProxy* get_Proxy();
public: __property void set_Proxy(IWebProxy* );
[JScript]
public override function get Proxy() : IWebProxy
public override function set Proxy(IWebProxy);

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


RequestUri Property

FtpWebRequest.RequestUri Property

Gets the original Uri of the request.

[Visual Basic]
Overrides Public Property ReadOnly RequestUri As Uri
[C#]
public override Uri RequestUri { get; }
[C++]
public: __property Uri* get_RequestUri();
[JScript]
public override function get RequestUri() : Uri

Property Value

A Uri containing the URI of the Internet resource passed to the WebRequest.Create method.

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


Timeout Property

FtpWebRequest.Timeout Property

Gets or sets the timeout value for a request.

[Visual Basic]
Overrides Public Property Timeout As Integer
[C#]
public override int Timeout { get; set; }
[C++]
public: __property int get_Timeout();
public: __property void set_Timeout(int );
[JScript]
public override function get Timeout() : int
public override function set Timeout(int);

Property Value

The number of milliseconds to wait before the request times out.

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


Username Property

FtpWebRequest.Username Property

Gets or sets the username to use for authentication

[Visual Basic]
Public Property Username As String
[C#]
public string Username { get; set; }
[C++]
public: __property String* get_Username();
public: __property void set_Username(String* );
[JScript]
public function get Username() : String
public function set Username(String);

Property Value

A string value to use for authentication.

Remarks

If requesting a resource from a server that requires authentication, this property must be set.

Example

The following example demonstrates using the WebRequest/Response classes to get a file using FTP.

[Visual Basic]
' Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", New Dart.PowerTCP.Ftp.FtpWebRequestCreator())

' Create Request object (this will be anonymous FTP)
Dim req As Dart.PowerTCP.Ftp.FtpWebRequest
req = System.Net.WebRequest.Create("ftp://myServer/file.txt")

req.Password = "pass"
req.Username = "user"

' Get response
Dim res As Dart.PowerTCP.Ftp.FtpWebResponse = req.GetResponse

' Get response content
Dim stream1 As System.IO.Stream = res.GetResponseStream()

' Create file stream to write content to file
Dim fstream As System.IO.FileStream
fstream = New System.IO.FileStream("c:\FtpTest\file.txt", System.IO.FileMode.Create)

Dim buffer(8096) As Byte
Dim count As Integer

count = -1
Do While (count <> 0)

   ' Read content into a buffer
   count = stream1.Read(buffer, 0, buffer.Length)

   ' Write content to a file
   fstream.Write(buffer, 0, count)

Loop

' Close the file
fstream.Close()

[C#]
// Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", new Dart.PowerTCP.Ftp.FtpWebRequestCreator());

// Create Request object (this will be anonymous FTP)
Dart.PowerTCP.Ftp.FtpWebRequest req =
(Dart.PowerTCP.Ftp.FtpWebRequest)System.Net.WebRequest.Create("ftp://myServer//file.txt");

req.Username = "user";
req.Password = "pass";

// Get response
System.Net.WebResponse res = req.GetResponse();

// Get response content
System.IO.Stream stream1 = res.GetResponseStream();

// Create file stream to write content to file
System.IO.FileStream fstream = new System.IO.FileStream("c:\\FtpTest\\file.txt", System.IO.FileMode.Create);

byte[] buffer = new byte[8096];
int count = -1;

do
{
    // Read content into a buffer
    count = stream1.Read(buffer, 0, buffer.Length);

    // Write content to a file
    fstream.Write(buffer, 0, count);
}
while (count != 0);

// Close the file
fstream.Close();

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


FtpWebRequest Methods

The methods of the FtpWebRequest class are listed below. For a complete list of FtpWebRequest class members, see the FtpWebRequest Members topic.

Public Instance Methods

Abort | Overridden. Cancels an FTP request for an Internet resource.
BeginGetRequestStream | Overridden. Starts an asynchronous request for a Stream used to send file data to an Internet resource.
BeginGetResponse | Overridden. Begins an asynchronous request for an Internet file using FTP.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
EndGetRequestStream | Overridden. Completes an asynchronous stream request that was started by the BeginGetRequestStream() method.
EndGetResponse | Overridden. Completes an asynchronous request for an Internet resource that was started with the BeginGetResponse method.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetRequestStream | Overridden. Returns a Stream for writing file data to the Internet resource specified by the Uri property.
GetResponse | Overridden. Sends a request to an Internet resource and returns a WebResponse instance (file).
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


Abort Method

FtpWebRequest.Abort Method

Cancels an FTP request for an Internet resource.

[Visual Basic]
Overrides Public Sub Abort()
[C#]
public override void Abort();
[C++]
public: void Abort();
[JScript]
public override function Abort();

Remarks

Abort cancels a request for a resource.

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


BeginGetRequestStream Method

FtpWebRequest.BeginGetRequestStream Method

Starts an asynchronous request for a Stream used to send file data to an Internet resource.

[Visual Basic]
Overrides Public Function BeginGetRequestStream( _
   ByVal callback As AsyncCallback, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public override IAsyncResult BeginGetRequestStream(
   AsyncCallback callback,
   object state
);
[C++]
public: IAsyncResult* BeginGetRequestStream(
   AsyncCallback* callback,
   Object* state
);
[JScript]
public override function BeginGetRequestStream(
   AsyncCallback callback,
   Object state
): IAsyncResult;

Parameters

callback
The AsyncCallback delegate to be called when the operation is complete.
state
An object containing state information for this operation.

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


BeginGetResponse Method

FtpWebRequest.BeginGetResponse Method

Begins an asynchronous request for an Internet file using FTP.

[Visual Basic]
Overrides Public Function BeginGetResponse( _
   ByVal callback As AsyncCallback, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public override IAsyncResult BeginGetResponse(
   AsyncCallback callback,
   object state
);
[C++]
public: IAsyncResult* BeginGetResponse(
   AsyncCallback* callback,
   Object* state
);
[JScript]
public override function BeginGetResponse(
   AsyncCallback callback,
   Object state
): IAsyncResult;

Parameters

callback
The AsyncCallback delegate to be called when the operation is complete.
state
An object containing state information for this operation.

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


EndGetRequestStream Method

FtpWebRequest.EndGetRequestStream Method

Completes an asynchronous stream request that was started by the BeginGetRequestStream() method.

[Visual Basic]
Overrides Public Function EndGetRequestStream( _
   ByVal ar As IAsyncResult _
) As Stream
[C#]
public override Stream EndGetRequestStream(
   IAsyncResult ar
);
[C++]
public: Stream* EndGetRequestStream(
   IAsyncResult* ar
);
[JScript]
public override function EndGetRequestStream(
   IAsyncResult ar
): Stream;

Parameters

ar
Reference to the pending asynchronous request that is returned from BeginGetRequestStream.

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


EndGetResponse Method

FtpWebRequest.EndGetResponse Method

Completes an asynchronous request for an Internet resource that was started with the BeginGetResponse method.

[Visual Basic]
Overrides Public Function EndGetResponse( _
   ByVal ar As IAsyncResult _
) As WebResponse
[C#]
public override WebResponse EndGetResponse(
   IAsyncResult ar
);
[C++]
public: WebResponse* EndGetResponse(
   IAsyncResult* ar
);
[JScript]
public override function EndGetResponse(
   IAsyncResult ar
): WebResponse;

Parameters

ar
Reference to the pending asynchronous request that is returned from BeginGetResponse.

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


GetRequestStream Method

FtpWebRequest.GetRequestStream Method

Returns a Stream for writing file data to the Internet resource specified by the Uri property.

[Visual Basic]
Overrides Public Function GetRequestStream() As Stream
[C#]
public override Stream GetRequestStream();
[C++]
public: Stream* GetRequestStream();
[JScript]
public override function GetRequestStream(): Stream;

Exceptions

Exception Type | Condition
InvalidOperationException | The GetRequestStream method is called more than once.
ProtocolException | Bad response was received from the server.

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


GetResponse Method

FtpWebRequest.GetResponse Method

Sends a request to an Internet resource and returns a WebResponse instance (file).

[Visual Basic]
Overrides Public Function GetResponse() As WebResponse
[C#]
public override WebResponse GetResponse();
[C++]
public: WebResponse* GetResponse();
[JScript]
public override function GetResponse(): WebResponse;

Remarks

The GetResponse method returns an WebResponse instance containing the response from the Internet resource. The actual instance returned is an instance of FtpWebResponse, and can be typecast to that class to access FTP-specific properties.

Exceptions

Exception Type | Condition
ProtocolException | Bad response was received from the server.

Example

The following example demonstrates using the WebRequest/Response classes to get a file using FTP.

[Visual Basic]
' Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", New Dart.PowerTCP.Ftp.FtpWebRequestCreator())

' Create Request object (this will be anonymous FTP)
Dim req As Dart.PowerTCP.Ftp.FtpWebRequest
req = System.Net.WebRequest.Create("ftp://myServer/file.txt")

req.Password = "pass"
req.Username = "user"

' Get response
Dim res As Dart.PowerTCP.Ftp.FtpWebResponse = req.GetResponse

' Get response content
Dim stream1 As System.IO.Stream = res.GetResponseStream()

' Create file stream to write content to file
Dim fstream As System.IO.FileStream
fstream = New System.IO.FileStream("c:\FtpTest\file.txt", System.IO.FileMode.Create)

Dim buffer(8096) As Byte
Dim count As Integer

count = -1
Do While (count <> 0)

   ' Read content into a buffer
   count = stream1.Read(buffer, 0, buffer.Length)

   ' Write content to a file
   fstream.Write(buffer, 0, count)

Loop

' Close the file
fstream.Close()

[C#]
// Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", new Dart.PowerTCP.Ftp.FtpWebRequestCreator());

// Create Request object (this will be anonymous FTP)
Dart.PowerTCP.Ftp.FtpWebRequest req =
(Dart.PowerTCP.Ftp.FtpWebRequest)System.Net.WebRequest.Create("ftp://myServer//file.txt");

req.Username = "user";
req.Password = "pass";

// Get response
System.Net.WebResponse res = req.GetResponse();

// Get response content
System.IO.Stream stream1 = res.GetResponseStream();

// Create file stream to write content to file
System.IO.FileStream fstream = new System.IO.FileStream("c:\\FtpTest\\file.txt", System.IO.FileMode.Create);

byte[] buffer = new byte[8096];
int count = -1;

do
{
    // Read content into a buffer
    count = stream1.Read(buffer, 0, buffer.Length);

    // Write content to a file
    fstream.Write(buffer, 0, count);
}
while (count != 0);

// Close the file
fstream.Close();

See Also

FtpWebRequest Class | Dart.PowerTCP.Ftp Namespace


FtpWebRequestCreator Class

Provides an FTP-specific implementation of the IWebRequest interface.

For a list of all members of this type, see FtpWebRequestCreator Members.

System.Object
Dart.PowerTCP.Ftp.FtpWebRequestCreator

[Visual Basic]
Public Class FtpWebRequestCreator
    Implements IWebRequestCreate
[C#]
public class FtpWebRequestCreator : IWebRequestCreate
[C++]
public __gc class FtpWebRequestCreator : public IWebRequestCreate
[JScript]
public class FtpWebRequestCreator extends IWebRequestCreate

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Example

The following example demonstrates using the WebRequest/Response classes to get a file using FTP.

[Visual Basic]
' Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", New Dart.PowerTCP.Ftp.FtpWebRequestCreator())

' Create Request object (this will be anonymous FTP)
Dim req As Dart.PowerTCP.Ftp.FtpWebRequest
req = System.Net.WebRequest.Create("ftp://myServer/file.txt")

req.Password = "pass"
req.Username = "user"

' Get response
Dim res As Dart.PowerTCP.Ftp.FtpWebResponse = req.GetResponse

' Get response content
Dim stream1 As System.IO.Stream = res.GetResponseStream()

' Create file stream to write content to file
Dim fstream As System.IO.FileStream
fstream = New System.IO.FileStream("c:\FtpTest\file.txt", System.IO.FileMode.Create)

Dim buffer(8096) As Byte
Dim count As Integer

count = -1
Do While (count <> 0)

   ' Read content into a buffer
   count = stream1.Read(buffer, 0, buffer.Length)

   ' Write content to a file
   fstream.Write(buffer, 0, count)

Loop

' Close the file
fstream.Close()

[C#]
// Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", new Dart.PowerTCP.Ftp.FtpWebRequestCreator());

// Create Request object (this will be anonymous FTP)
Dart.PowerTCP.Ftp.FtpWebRequest req =
(Dart.PowerTCP.Ftp.FtpWebRequest)System.Net.WebRequest.Create("ftp://myServer//file.txt");

req.Username = "user";
req.Password = "pass";

// Get response
System.Net.WebResponse res = req.GetResponse();

// Get response content
System.IO.Stream stream1 = res.GetResponseStream();

// Create file stream to write content to file
System.IO.FileStream fstream = new System.IO.FileStream("c:\\FtpTest\\file.txt", System.IO.FileMode.Create);

byte[] buffer = new byte[8096];
int count = -1;

do
{
    // Read content into a buffer
    count = stream1.Read(buffer, 0, buffer.Length);

    // Write content to a file
    fstream.Write(buffer, 0, count);
}
while (count != 0);

// Close the file
fstream.Close();

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

FtpWebRequestCreator Members | Dart.PowerTCP.Ftp Namespace


FtpWebRequestCreator Members

FtpWebRequestCreator overview

Public Instance Constructors

FtpWebRequestCreator Constructor Initializes a new instance of the FtpWebRequestCreator class.

Public Instance Methods

Create | Implements the IWebRequestCreate interface
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

FtpWebRequestCreator Class | Dart.PowerTCP.Ftp Namespace


FtpWebRequestCreator Constructor

Initializes a new instance of the FtpWebRequestCreator class.

[Visual Basic]
Public Sub New()
[C#]
public FtpWebRequestCreator();
[C++]
public: FtpWebRequestCreator();
[JScript]
public function FtpWebRequestCreator();

See Also

FtpWebRequestCreator Class | Dart.PowerTCP.Ftp Namespace


FtpWebRequestCreator Methods

The methods of the FtpWebRequestCreator class are listed below. For a complete list of FtpWebRequestCreator class members, see the FtpWebRequestCreator Members topic.

Public Instance Methods

Create | Implements the IWebRequestCreate interface
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

FtpWebRequestCreator Class | Dart.PowerTCP.Ftp Namespace


Create Method

FtpWebRequestCreator.Create Method

Implements the IWebRequestCreate interface

[Visual Basic]
Public Function Create( _
   ByVal uri As Uri _
) _
    Implements IWebRequestCreate.Create As WebRequest
[C#]
public WebRequest Create(
   Uri uri
);
[C++]
public: WebRequest* Create(
   Uri* uri
);
[JScript]
public function Create(
   Uri uri
): WebRequest;

Parameters

uri
A Uri containing the URI of the requested resource.

Implements

IWebRequestCreate.Create

See Also

FtpWebRequestCreator Class | Dart.PowerTCP.Ftp Namespace


FtpWebResponse Class

Provides an FTP-specific implementation of the WebResponse class.

For a list of all members of this type, see FtpWebResponse Members.

System.Object
System.MarshalByRefObject
System.Net.WebResponse
Dart.PowerTCP.Ftp.FtpWebResponse

[Visual Basic]
Public Class FtpWebResponse
    Inherits WebResponse
[C#]
public class FtpWebResponse : WebResponse
[C++]
public __gc class FtpWebResponse : public WebResponse
[JScript]
public class FtpWebResponse extends WebResponse

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

The WebResponse class is the abstract (MustInherit in Visual Basic) base class from which protocol-specific response classes are derived. Applications can participate in request and response transactions in a protocol-agnostic manner using instances of the WebResponse class while protocol-specific classes derived from WebResponse carry out the details of the request.

Client applications do not create WebResponse objects directly, they are created by calling the GetResponse method on a WebRequest instance.

Example

The following example demonstrates using the WebRequest/Response classes to get a file using FTP.

[Visual Basic]
' Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", New Dart.PowerTCP.Ftp.FtpWebRequestCreator())

' Create Request object (this will be anonymous FTP)
Dim req As Dart.PowerTCP.Ftp.FtpWebRequest
req = System.Net.WebRequest.Create("ftp://myServer/file.txt")

req.Password = "pass"
req.Username = "user"

' Get response
Dim res As Dart.PowerTCP.Ftp.FtpWebResponse = req.GetResponse

' Get response content
Dim stream1 As System.IO.Stream = res.GetResponseStream()

' Create file stream to write content to file
Dim fstream As System.IO.FileStream
fstream = New System.IO.FileStream("c:\FtpTest\file.txt", System.IO.FileMode.Create)

Dim buffer(8096) As Byte
Dim count As Integer

count = -1
Do While (count <> 0)

   ' Read content into a buffer
   count = stream1.Read(buffer, 0, buffer.Length)

   ' Write content to a file
   fstream.Write(buffer, 0, count)

Loop

' Close the file
fstream.Close()

[C#]
// Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", new Dart.PowerTCP.Ftp.FtpWebRequestCreator());

// Create Request object (this will be anonymous FTP)
Dart.PowerTCP.Ftp.FtpWebRequest req =
(Dart.PowerTCP.Ftp.FtpWebRequest)System.Net.WebRequest.Create("ftp://myServer//file.txt");

req.Username = "user";
req.Password = "pass";

// Get response
System.Net.WebResponse res = req.GetResponse();

// Get response content
System.IO.Stream stream1 = res.GetResponseStream();

// Create file stream to write content to file
System.IO.FileStream fstream = new System.IO.FileStream("c:\\FtpTest\\file.txt", System.IO.FileMode.Create);

byte[] buffer = new byte[8096];
int count = -1;

do
{
    // Read content into a buffer
    count = stream1.Read(buffer, 0, buffer.Length);

    // Write content to a file
    fstream.Write(buffer, 0, count);
}
while (count != 0);

// Close the file
fstream.Close();

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

FtpWebResponse Members | Dart.PowerTCP.Ftp Namespace


FtpWebResponse Members

FtpWebResponse overview

Public Instance Constructors

FtpWebResponse Constructor Initializes a new instance of the FtpWebResponse class.

Public Instance Properties

ContentLength | Overridden. Gets the length of the content returned by the request. This property always throws a NotSupportedException.
ContentType | Overridden. Gets the content type of the response. This property always throws a NotSupportedException.
Headers | Overridden. Gets the headers associated with this response from the server. This property always throws a NotSupportedException.
ResponseUri | Overridden. Gets the Uri of the Internet resource that responded to the request.

Public Instance Methods

Close | Overridden. Cleans up resources and closes the underlying stream by calling the Stream.Close method. This property always throws a NotSupportedException.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetResponseStream | Overridden. Returns the file data stream from the Internet resource.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

FtpWebResponse Class | Dart.PowerTCP.Ftp Namespace


FtpWebResponse Constructor

Initializes a new instance of the FtpWebResponse class.

[Visual Basic]
Public Sub New( _
   ByVal request As FtpWebRequest _
)
[C#]
public FtpWebResponse(
   FtpWebRequest request
);
[C++]
public: FtpWebResponse(
   FtpWebRequest* request
);
[JScript]
public function FtpWebResponse(
   FtpWebRequest request
);

Parameters

request
An FtpWebRequest object encapsulating the request.

See Also

FtpWebResponse Class | Dart.PowerTCP.Ftp Namespace


FtpWebResponse Properties

The properties of the FtpWebResponse class are listed below. For a complete list of FtpWebResponse class members, see the FtpWebResponse Members topic.

Public Instance Properties

ContentLength | Overridden. Gets the length of the content returned by the request. This property always throws a NotSupportedException.
ContentType | Overridden. Gets the content type of the response. This property always throws a NotSupportedException.
Headers | Overridden. Gets the headers associated with this response from the server. This property always throws a NotSupportedException.
ResponseUri | Overridden. Gets the Uri of the Internet resource that responded to the request.

See Also

FtpWebResponse Class | Dart.PowerTCP.Ftp Namespace


ContentLength Property

FtpWebResponse.ContentLength Property

Gets the length of the content returned by the request. This property always throws a NotSupportedException.

[Visual Basic]
Overrides Public Property ContentLength As Long
[C#]
public override long ContentLength { get; set; }
[C++]
public: __property __int64 get_ContentLength();
public: __property void set_ContentLength(__int64 );
[JScript]
public override function get ContentLength() : long
public override function set ContentLength(long);

See Also

FtpWebResponse Class | Dart.PowerTCP.Ftp Namespace


ContentType Property

FtpWebResponse.ContentType Property

Gets the content type of the response. This property always throws a NotSupportedException.

[Visual Basic]
Overrides Public Property ContentType As String
[C#]
public override string ContentType { get; set; }
[C++]
public: __property String* get_ContentType();
public: __property void set_ContentType(String* );
[JScript]
public override function get ContentType() : String
public override function set ContentType(String);

See Also

FtpWebResponse Class | Dart.PowerTCP.Ftp Namespace


Headers Property

FtpWebResponse.Headers Property

Gets the headers associated with this response from the server. This property always throws a NotSupportedException.

[Visual Basic]
Overrides Public Property ReadOnly Headers As WebHeaderCollection
[C#]
public override WebHeaderCollection Headers { get; }
[C++]
public: __property WebHeaderCollection* get_Headers();
[JScript]
public override function get Headers() : WebHeaderCollection

See Also

FtpWebResponse Class | Dart.PowerTCP.Ftp Namespace


ResponseUri Property

FtpWebResponse.ResponseUri Property

Gets the Uri of the Internet resource that responded to the request.

[Visual Basic]
Overrides Public Property ReadOnly ResponseUri As Uri
[C#]
public override Uri ResponseUri { get; }
[C++]
public: __property Uri* get_ResponseUri();
[JScript]
public override function get ResponseUri() : Uri

Property Value

A Uri containing the URI of the Internet resource that responded to the request.

See Also

FtpWebResponse Class | Dart.PowerTCP.Ftp Namespace


FtpWebResponse Methods

The methods of the FtpWebResponse class are listed below. For a complete list of FtpWebResponse class members, see the FtpWebResponse Members topic.

Public Instance Methods

Close | Overridden. Cleans up resources and closes the underlying stream by calling the Stream.Close method. This property always throws a NotSupportedException.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetResponseStream | Overridden. Returns the file data stream from the Internet resource.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

FtpWebResponse Class | Dart.PowerTCP.Ftp Namespace


Close Method

FtpWebResponse.Close Method

Cleans up resources and closes the underlying stream by calling the Stream.Close method. This property always throws a NotSupportedException.

[Visual Basic]
Overrides Public Sub Close()
[C#]
public override void Close();
[C++]
public: void Close();
[JScript]
public override function Close();

See Also

FtpWebResponse Class | Dart.PowerTCP.Ftp Namespace


GetResponseStream Method

FtpWebResponse.GetResponseStream Method

Returns the file data stream from the Internet resource.

[Visual Basic]
Overrides Public Function GetResponseStream() As Stream
[C#]
public override Stream GetResponseStream();
[C++]
public: Stream* GetResponseStream();
[JScript]
public override function GetResponseStream(): Stream;

Return Value

A Stream containing the body of the response.

Exceptions

Exception Type | Condition
ProtocolException | Bad response was received from the server.

Example

The following example demonstrates using the WebRequest/Response classes to get a file using FTP.

[Visual Basic]
' Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", New Dart.PowerTCP.Ftp.FtpWebRequestCreator())

' Create Request object (this will be anonymous FTP)
Dim req As Dart.PowerTCP.Ftp.FtpWebRequest
req = System.Net.WebRequest.Create("ftp://myServer/file.txt")

req.Password = "pass"
req.Username = "user"

' Get response
Dim res As Dart.PowerTCP.Ftp.FtpWebResponse = req.GetResponse

' Get response content
Dim stream1 As System.IO.Stream = res.GetResponseStream()

' Create file stream to write content to file
Dim fstream As System.IO.FileStream
fstream = New System.IO.FileStream("c:\FtpTest\file.txt", System.IO.FileMode.Create)

Dim buffer(8096) As Byte
Dim count As Integer

count = -1
Do While (count <> 0)

   ' Read content into a buffer
   count = stream1.Read(buffer, 0, buffer.Length)

   ' Write content to a file
   fstream.Write(buffer, 0, count)

Loop

' Close the file
fstream.Close()

[C#]
// Register the FTP prefix
System.Net.WebRequest.RegisterPrefix("ftp", new Dart.PowerTCP.Ftp.FtpWebRequestCreator());

// Create Request object (this will be anonymous FTP)
Dart.PowerTCP.Ftp.FtpWebRequest req =
(Dart.PowerTCP.Ftp.FtpWebRequest)System.Net.WebRequest.Create("ftp://myServer//file.txt");

req.Username = "user";
req.Password = "pass";

// Get response
System.Net.WebResponse res = req.GetResponse();

// Get response content
System.IO.Stream stream1 = res.GetResponseStream();

// Create file stream to write content to file
System.IO.FileStream fstream = new System.IO.FileStream("c:\\FtpTest\\file.txt", System.IO.FileMode.Create);

byte[] buffer = new byte[8096];
int count = -1;

do
{
    // Read content into a buffer
    count = stream1.Read(buffer, 0, buffer.Length);

    // Write content to a file
    fstream.Write(buffer, 0, count);
}
while (count != 0);

// Close the file
fstream.Close();

See Also

FtpWebResponse Class | Dart.PowerTCP.Ftp Namespace


InvalidParameterTypeException Class

Thrown whenever a method is called with an invalid parameter.

For a list of all members of this type, see InvalidParameterTypeException Members.

System.Object
System.Exception
System.ApplicationException
Dart.PowerTCP.Ftp.InvalidParameterTypeException

[Visual Basic]
Public Class InvalidParameterTypeException
    Inherits ApplicationException
[C#]
public class InvalidParameterTypeException : ApplicationException
[C++]
public __gc class InvalidParameterTypeException : public ApplicationException
[JScript]
public class InvalidParameterTypeException extends ApplicationException

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

This exception is thrown if a method is called with a parameter of the wrong type. To keep this exception from being thrown read the documentation on the function throwing the exception.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

InvalidParameterTypeException Members | Dart.PowerTCP.Ftp Namespace


InvalidParameterTypeException Members

InvalidParameterTypeException overview

Public Instance Constructors

InvalidParameterTypeException Overloaded. Initializes a new instance of the InvalidParameterTypeException class.

Public Instance Properties

HelpLink (inherited from Exception) | Gets or sets a link to the help file associated with this exception.
InnerException (inherited from Exception) | Gets the Exception instance that caused the current exception.
Message (inherited from Exception) | Gets a message that describes the current exception.
Source (inherited from Exception) | Gets or sets the name of the application or the object that causes the error.
StackTrace (inherited from Exception) | Gets a string representation of the frames on the call stack at the time the current exception was thrown.
TargetSite (inherited from Exception) | Gets the method that throws the current exception.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetBaseException (inherited from Exception) | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetObjectData (inherited from Exception) | When overridden in a derived class, sets the SerializationInfo with information about the exception.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Exception) | Overridden. Creates and returns a string representation of the current exception.

See Also

InvalidParameterTypeException Class | Dart.PowerTCP.Ftp Namespace


InvalidParameterTypeException Constructor

Initializes a new instance of InvalidParameterTypeException.

Overload List

Initializes a new instance of InvalidParameterTypeException.

[Visual Basic] Public Sub New()
[C#] public InvalidParameterTypeException();
[C++] public: InvalidParameterTypeException();
[JScript] public function InvalidParameterTypeException();

Initializes a new instance of InvalidParameterTypeException.

[Visual Basic] Public Sub New(ByVal String)
[C#] public InvalidParameterTypeException(string);
[C++] public: InvalidParameterTypeException(String*);
[JScript] public function InvalidParameterTypeException(String);

Initializes a new instance of InvalidParameterTypeException.

[Visual Basic] Public Sub New(ByVal String,ByVal Exception)
[C#] public InvalidParameterTypeException(string,Exception);
[C++] public: InvalidParameterTypeException(String*,Exception*);
[JScript] public function InvalidParameterTypeException(String,Exception);

Initializes a new instance of the InvalidParameterException class.

[Visual Basic] Public Sub New(ByVal String,ByVal Integer)
[C#] public InvalidParameterTypeException(string,int);
[C++] public: InvalidParameterTypeException(String*,int);
[JScript] public function InvalidParameterTypeException(String,int);

See Also

InvalidParameterTypeException Class | Dart.PowerTCP.Ftp Namespace


InvalidParameterTypeException Constructor ()

Initializes a new instance of InvalidParameterTypeException.

[Visual Basic]
Public Sub New()
[C#]
public InvalidParameterTypeException();
[C++]
public: InvalidParameterTypeException();
[JScript]
public function InvalidParameterTypeException();

See Also

InvalidParameterTypeException Class | Dart.PowerTCP.Ftp Namespace | InvalidParameterTypeException Constructor Overload List


InvalidParameterTypeException Constructor (String)

Initializes a new instance of InvalidParameterTypeException.

[Visual Basic]
Public Sub New( _
   ByVal message As String _
)
[C#]
public InvalidParameterTypeException(
   string message
);
[C++]
public: InvalidParameterTypeException(
   String* message
);
[JScript]
public function InvalidParameterTypeException(
   String message
);

See Also

InvalidParameterTypeException Class | Dart.PowerTCP.Ftp Namespace | InvalidParameterTypeException Constructor Overload List


InvalidParameterTypeException Constructor (String, Exception)

Initializes a new instance of InvalidParameterTypeException.

[Visual Basic]
Public Sub New( _
   ByVal message As String, _
   ByVal e As Exception _
)
[C#]
public InvalidParameterTypeException(
   string message,
   Exception e
);
[C++]
public: InvalidParameterTypeException(
   String* message,
   Exception* e
);
[JScript]
public function InvalidParameterTypeException(
   String message,
   Exception e
);

See Also

InvalidParameterTypeException Class | Dart.PowerTCP.Ftp Namespace | InvalidParameterTypeException Constructor Overload List


InvalidParameterTypeException Constructor (String, Int32)

Initializes a new instance of the InvalidParameterException class.

[Visual Basic]
Public Sub New( _
   ByVal description As String, _
   ByVal parameterNumber As Integer _
)
[C#]
public InvalidParameterTypeException(
   string description,
   int parameterNumber
);
[C++]
public: InvalidParameterTypeException(
   String* description,
   int parameterNumber
);
[JScript]
public function InvalidParameterTypeException(
   String description,
   int parameterNumber
);

See Also

InvalidParameterTypeException Class | Dart.PowerTCP.Ftp Namespace | InvalidParameterTypeException Constructor Overload List


Invoke Class

Presents the results from an Internet protocol Request/Response pair.

For a list of all members of this type, see Invoke Members.

System.Object
Dart.PowerTCP.Ftp.Invoke

[Visual Basic]
Public Class Invoke
[C#]
public class Invoke
[C++]
public __gc class Invoke
[JScript]
public class Invoke

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

Many Internet protocols are based on a request/reply system, where the client sends a request, and the server sends at least one reply. This continues lock-step until communication is complete. The Invoke object encapsulates these request/reply pairs.

In PowerTCP commands are often sent using the Object.Invoke or Object.BeginInvoke methods. When a command is sent an Invoke object is returned describing both the request and response. The response is encapsulated by the Response property, which allows easy access to the raw and parsed response from the server. The request is represented by the Request property, a string containing the request sent.

Example

The following example demonstrates using Invoke to send a command.

[Visual Basic]
' Set server and user properties. This will allow us to call other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Invoke a command
Dim invoke as Dart.PowerTCP.Ftp.Invoke
Try
   invoke = Ftp1.Invoke(FtpCommand.NoOp)
Catch ex as Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Request/Response messages: " + invoke.ToString())

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Invoke a command
Dart.PowerTCP.Ftp.Invoke invoke;
try
{
   invoke = ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.NoOp);
}
catch (Exception ex)
{
    Debug.WriteLine("Error: " + ex.ToString());
    return;
}

// Success
Debug.WriteLine("Request/Response messages: " + invoke.ToString());

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Invoke Members | Dart.PowerTCP.Ftp Namespace


Invoke Members

Invoke overview

Public Instance Constructors

Invoke Overloaded. Initializes a new instance of the Invoke class.

Public Instance Properties

Request | Gets the request sent to the server.
Response | Gets the response received from the server.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString | Overridden. Returns the entire request/response pair.

See Also

Invoke Class | Dart.PowerTCP.Ftp Namespace


Invoke Constructor

Initializes a new instance of the Invoke class.

Overload List

Initializes a new instance of the Invoke class.

[Visual Basic] Public Sub New()
[C#] public Invoke();
[C++] public: Invoke();
[JScript] public function Invoke();

Initializes a new instance of the Invoke class.

[Visual Basic] Public Sub New(ByVal String,ByVal Response)
[C#] public Invoke(string,Response);
[C++] public: Invoke(String*,Response*);
[JScript] public function Invoke(String,Response);

See Also

Invoke Class | Dart.PowerTCP.Ftp Namespace


Invoke Constructor ()

Initializes a new instance of the Invoke class.

[Visual Basic]
Public Sub New()
[C#]
public Invoke();
[C++]
public: Invoke();
[JScript]
public function Invoke();

See Also

Invoke Class | Dart.PowerTCP.Ftp Namespace | Invoke Constructor Overload List


Invoke Constructor (String, Response)

Initializes a new instance of the Invoke class.

[Visual Basic]
Public Sub New( _
   ByVal request As String, _
   ByVal response As Response _
)
[C#]
public Invoke(
   string request,
   Response response
);
[C++]
public: Invoke(
   String* request,
   Response* response
);
[JScript]
public function Invoke(
   String request,
   Response response
);

See Also

Invoke Class | Dart.PowerTCP.Ftp Namespace | Invoke Constructor Overload List


Invoke Properties

The properties of the Invoke class are listed below. For a complete list of Invoke class members, see the Invoke Members topic.

Public Instance Properties

Request | Gets the request sent to the server.
Response | Gets the response received from the server.

See Also

Invoke Class | Dart.PowerTCP.Ftp Namespace


Request Property

Invoke.Request Property

Gets the request sent to the server.

[Visual Basic]
Public Property ReadOnly Request As String
[C#]
public string Request { get; }
[C++]
public: __property String* get_Request();
[JScript]
public function get Request() : String

Property Value

A string representing the request sent to the server.

Remarks

This property represents the command sent to the server.

Example

The following example demonstrates using Invoke to send a command.

[Visual Basic]
' Set server and user properties. This will allow us to call other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Invoke a command
Dim invoke as Dart.PowerTCP.Ftp.Invoke
Try
   invoke = Ftp1.Invoke(FtpCommand.NoOp)
Catch ex as Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Request/Response messages: " + invoke.ToString())

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Invoke a command
Dart.PowerTCP.Ftp.Invoke invoke;
try
{
   invoke = ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.NoOp);
}
catch (Exception ex)
{
    Debug.WriteLine("Error: " + ex.ToString());
    return;
}

// Success
Debug.WriteLine("Request/Response messages: " + invoke.ToString());

See Also

Invoke Class | Dart.PowerTCP.Ftp Namespace


Response Property

Invoke.Response Property

Gets the response received from the server.

[Visual Basic]
Public Property ReadOnly Response As Response
[C#]
public Response Response { get; }
[C++]
public: __property Response* get_Response();
[JScript]
public function get Response() : Response

Property Value

A Response object representing the response received from the server.

Remarks

The response to a command is encapsulated by the Response object, which allows easy access to the code (through the Code property) and text (through the Text property) portions of the response without parsing. If you wish to have to entire, unparsed response from the server, simply use the ToString method.

Example

The following example demonstrates using Invoke to send a command.

[Visual Basic]
' Set server and user properties. This will allow us to call other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Invoke a command
Dim invoke as Dart.PowerTCP.Ftp.Invoke
Try
   invoke = Ftp1.Invoke(FtpCommand.NoOp)
Catch ex as Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success
Debug.WriteLine("Request/Response messages: " + invoke.ToString())

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Invoke a command
Dart.PowerTCP.Ftp.Invoke invoke;
try
{
   invoke = ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.NoOp);
}
catch (Exception ex)
{
    Debug.WriteLine("Error: " + ex.ToString());
    return;
}

// Success
Debug.WriteLine("Request/Response messages: " + invoke.ToString());

See Also

Invoke Class | Dart.PowerTCP.Ftp Namespace


Invoke Methods

The methods of the Invoke class are listed below. For a complete list of Invoke class members, see the Invoke Members topic.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString | Overridden. Returns the entire request/response pair.

See Also

Invoke Class | Dart.PowerTCP.Ftp Namespace


ToString Method

Invoke.ToString Method

Returns the entire request/response pair.

[Visual Basic]
Overrides Public Function ToString() As String
[C#]
public override string ToString();
[C++]
public: String* ToString();
[JScript]
public override function ToString(): String;

Return Value

A string value representing the entire request/response pair.

Remarks

This method returns the entire request/response pair, with additional formatting.

Example

The following example demonstrates a simple rename.

[Visual Basic]
' Create Invoke object, which will contain request/response data
Dim invoke As Dart.PowerTCP.Ftp.Invoke

' Call Rename. Invoke object will contain request/response data
Try
   invoke = ftp1.Rename("aaa.txt", "zzz.txt")
' ProtocolException thrown if bad response received from server
Catch FTPEx As Dart.PowerTCP.Ftp.ProtocolException
   Debug.WriteLine("Rename unsuccessful")
   Debug.WriteLine(FtpEx.ToString())
   Exit Sub
End Try

' If it gets here, Rename was successful
Debug.WriteLine("Rename successful")

' Request sent and Response received
Debug.WriteLine("Response/response " + invoke.ToString())

[C#]
//Create Invoke object which will contain request/response data
Dart.PowerTCP.Ftp.Invoke invoke;

// Call Rename
try
{
    invoke = ftp1.Rename("aaa.txt", "zzz.txt");
}
// ProtocolException thrown if bad response received from server
catch(Dart.PowerTCP.Ftp.ProtocolException FTPex)
{
    Debug.WriteLine("Rename unsuccessful");
    Debug.WriteLine(FTPEx.ToString());
    return;
}

// If it gets here, Rename was successful
Debug.WriteLine("Rename successful");

// Request sent and response received
Debug.WriteLine("Response/response " + invoke.ToString());

See Also

Invoke Class | Dart.PowerTCP.Ftp Namespace


InvokeEventArgs Class

This class is passed into EndInvoke events and provides data for these event.

For a list of all members of this type, see InvokeEventArgs Members.

System.Object
System.EventArgs
Dart.PowerTCP.Ftp.InvokeEventArgs

[Visual Basic]
Public Class InvokeEventArgs
    Inherits EventArgs
[C#]
public class InvokeEventArgs : EventArgs
[C++]
public __gc class InvokeEventArgs : public EventArgs
[JScript]
public class InvokeEventArgs extends EventArgs

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

A InvokeEventArgs object is passed into an EndInvoke event after a command has been sent asynchronously. This object represents the command sent to the server and the response received from the server.

Many TCP/IP protocols are based on a request/response system, where the client sends a request, and the server sends at least one reply. This continues lock-step until communication is finished. The InvokeEventArgs object encapsulates these request/reply pairs.

In PowerTCP commands are often explicitly sent using the Object.Invoke or Object.BeginInvoke methods, and transparently sent using higher-level methods. When a command is sent asynchronously an InvokeEventArgs object is returned in the event handler describing both the request and response. The response is encapsulated by the Response property which allows easy access to the raw and parsed response from the server. The request is represented by the Request property, a string containing the request sent.

If your code causes an exception, it would be returned to the handling event without you seeing it. To preclude such a condition, you should ALWAYS use a try/catch block around your event-handling code.

Example

The following example demonstrates using Ftp.BeginInvoke to issue a command (in this case, CDUP) asynchronously.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Issue CDUP command asynchronously, upon completion the EndInvoke Event will be fired.
Ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.ChangeDirUp, Nothing, Nothing)

' Report
Debug.WriteLine("CDUP command sent.")

' When the BeginInvoke operation has completed, the EndInvoke Event will fire.
Private Sub Ftp1_EndInvoke(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.InvokeEventArgs) Handles Ftp1.EndInvoke

   ' If an error occurred during the asynchronous method, it would
   ' be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then
      Debug.WriteLine("Command issued " + e.Request)
      Debug.WriteLine("Response received " + e.Response.ToString();
   Else
      Debug.WriteLine(e.Exception.Message)
   End If

   ' Close the connection
   Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Issue CDUP command asynchronously, upon completion the EndInvoke Event will be fired.
ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.ChangeDirUp, null, null);

// Report
Debug.WriteLine("CDUP command sent.");

// When the BeginInvoke operation has completed, the EndInvoke Event will fire.
private void ftp1_EndInvoke(object sender, Dart.PowerTCP.Ftp.InvokeEventArgs e)
{

    // If an error occurred during the asynchronous method, it would
    // be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
        Debug.WriteLine("Command issued " + e.Request);
        Debug.WriteLine("Response received " + e.Response);
    }
    else
    {
        Debug.WriteLine("Error: " + e.Exception.Message);
    }

    // Close the connection
    ftp1.Close();
}

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

InvokeEventArgs Members | Dart.PowerTCP.Ftp Namespace


InvokeEventArgs Members

InvokeEventArgs overview

Public Instance Constructors

InvokeEventArgs Constructor Initializes a new instance of the InvokeEventArgs class.

Public Instance Properties

Exception | Gets any exception which occurred during the asynchronous operation.
Request | Gets the request sent to the server.
Response | Gets the response received from the server.
State | Gets the object that was included as part of the associated method call.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

InvokeEventArgs Class | Dart.PowerTCP.Ftp Namespace


InvokeEventArgs Constructor

Initializes a new instance of the InvokeEventArgs class.

[Visual Basic]
Public Sub New( _
   ByVal request As String, _
   ByVal response As Response, _
   ByVal state As Object, _
   ByVal exception As Exception _
)
[C#]
public InvokeEventArgs(
   string request,
   Response response,
   object state,
   Exception exception
);
[C++]
public: InvokeEventArgs(
   String* request,
   Response* response,
   Object* state,
   Exception* exception
);
[JScript]
public function InvokeEventArgs(
   String request,
   Response response,
   Object state,
   Exception exception
);

See Also

InvokeEventArgs Class | Dart.PowerTCP.Ftp Namespace


InvokeEventArgs Properties

The properties of the InvokeEventArgs class are listed below. For a complete list of InvokeEventArgs class members, see the InvokeEventArgs Members topic.

Public Instance Properties

Exception | Gets any exception which occurred during the asynchronous operation.
Request | Gets the request sent to the server.
Response | Gets the response received from the server.
State | Gets the object that was included as part of the associated method call.

See Also

InvokeEventArgs Class | Dart.PowerTCP.Ftp Namespace


Exception Property

InvokeEventArgs.Exception Property

Gets any exception which occurred during the asynchronous operation.

[Visual Basic]
Public Property ReadOnly Exception As Exception
[C#]
public Exception Exception { get; }
[C++]
public: __property Exception* get_Exception();
[JScript]
public function get Exception() : Exception

Property Value

If any exception occurred during the asynchronous operation, this property will contain an Exception object describing the exception.

Remarks

Check this property to tell if an exception occurred during the asynchronous operation. If this property is null, no exception occurred.

The exception property is useful for checking exceptions and handling them appropriately. For example, if a bad command was sent to the server, a ProtocolException may be thrown. You could check this property to see if it was of type ProtocolException, than handle appropriately.

Example

The following example demonstrates using Ftp.BeginInvoke to issue a command (in this case, CDUP) asynchronously.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Issue CDUP command asynchronously, upon completion the EndInvoke Event will be fired.
Ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.ChangeDirUp, Nothing, Nothing)

' Report
Debug.WriteLine("CDUP command sent.")

' When the BeginInvoke operation has completed, the EndInvoke Event will fire.
Private Sub Ftp1_EndInvoke(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.InvokeEventArgs) Handles Ftp1.EndInvoke

   ' If an error occurred during the asynchronous method, it would
   ' be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then
      Debug.WriteLine("Command issued " + e.Request)
      Debug.WriteLine("Response received " + e.Response.ToString();
   Else
      Debug.WriteLine(e.Exception.Message)
   End If

   ' Close the connection
   Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Issue CDUP command asynchronously, upon completion the EndInvoke Event will be fired.
ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.ChangeDirUp, null, null);

// Report
Debug.WriteLine("CDUP command sent.");

// When the BeginInvoke operation has completed, the EndInvoke Event will fire.
private void ftp1_EndInvoke(object sender, Dart.PowerTCP.Ftp.InvokeEventArgs e)
{

    // If an error occurred during the asynchronous method, it would
    // be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
        Debug.WriteLine("Command issued " + e.Request);
        Debug.WriteLine("Response received " + e.Response);
    }
    else
    {
        Debug.WriteLine("Error: " + e.Exception.Message);
    }

    // Close the connection
    ftp1.Close();
}

See Also

InvokeEventArgs Class | Dart.PowerTCP.Ftp Namespace


Request Property

InvokeEventArgs.Request Property

Gets the request sent to the server.

[Visual Basic]
Public Property ReadOnly Request As String
[C#]
public string Request { get; }
[C++]
public: __property String* get_Request();
[JScript]
public function get Request() : String

Property Value

A string representing the request sent to the server.

Remarks

This property represents the command sent to the server.

Example

The following example demonstrates using Ftp.BeginInvoke to issue a command (in this case, CDUP) asynchronously.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Issue CDUP command asynchronously, upon completion the EndInvoke Event will be fired.
Ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.ChangeDirUp, Nothing, Nothing)

' Report
Debug.WriteLine("CDUP command sent.")

' When the BeginInvoke operation has completed, the EndInvoke Event will fire.
Private Sub Ftp1_EndInvoke(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.InvokeEventArgs) Handles Ftp1.EndInvoke

   ' If an error occurred during the asynchronous method, it would
   ' be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then
      Debug.WriteLine("Command issued " + e.Request)
      Debug.WriteLine("Response received " + e.Response.ToString();
   Else
      Debug.WriteLine(e.Exception.Message)
   End If

   ' Close the connection
   Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Issue CDUP command asynchronously, upon completion the EndInvoke Event will be fired.
ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.ChangeDirUp, null, null);

// Report
Debug.WriteLine("CDUP command sent.");

// When the BeginInvoke operation has completed, the EndInvoke Event will fire.
private void ftp1_EndInvoke(object sender, Dart.PowerTCP.Ftp.InvokeEventArgs e)
{

    // If an error occurred during the asynchronous method, it would
    // be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
        Debug.WriteLine("Command issued " + e.Request);
        Debug.WriteLine("Response received " + e.Response);
    }
    else
    {
        Debug.WriteLine("Error: " + e.Exception.Message);
    }

    // Close the connection
    ftp1.Close();
}

See Also

InvokeEventArgs Class | Dart.PowerTCP.Ftp Namespace


Response Property

InvokeEventArgs.Response Property

Gets the response received from the server.

[Visual Basic]
Public Property ReadOnly Response As Response
[C#]
public Response Response { get; }
[C++]
public: __property Response* get_Response();
[JScript]
public function get Response() : Response

Property Value

A Response object representing the response received from the server.

Remarks

The response to a command is encapsulated by the Response property, which allows easy access to the code (through the InvokeEventArgs.Code property) and text (through the InvokeEventArgs.Text property) portions of the response without parsing. If you wish to have to entire, unparsed response from the server, simply use the ToString method.

Example

The following example demonstrates using Ftp.BeginInvoke to issue a command (in this case, CDUP) asynchronously.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Issue CDUP command asynchronously, upon completion the EndInvoke Event will be fired.
Ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.ChangeDirUp, Nothing, Nothing)

' Report
Debug.WriteLine("CDUP command sent.")

' When the BeginInvoke operation has completed, the EndInvoke Event will fire.
Private Sub Ftp1_EndInvoke(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.InvokeEventArgs) Handles Ftp1.EndInvoke

   ' If an error occurred during the asynchronous method, it would
   ' be returned in the event. Be sure to check for it.
   If e.Exception Is Nothing Then
      Debug.WriteLine("Command issued " + e.Request)
      Debug.WriteLine("Response received " + e.Response.ToString();
   Else
      Debug.WriteLine(e.Exception.Message)
   End If

   ' Close the connection
   Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Issue CDUP command asynchronously, upon completion the EndInvoke Event will be fired.
ftp1.BeginInvoke(Dart.PowerTCP.Ftp.FtpCommand.ChangeDirUp, null, null);

// Report
Debug.WriteLine("CDUP command sent.");

// When the BeginInvoke operation has completed, the EndInvoke Event will fire.
private void ftp1_EndInvoke(object sender, Dart.PowerTCP.Ftp.InvokeEventArgs e)
{

    // If an error occurred during the asynchronous method, it would
    // be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
        Debug.WriteLine("Command issued " + e.Request);
        Debug.WriteLine("Response received " + e.Response);
    }
    else
    {
        Debug.WriteLine("Error: " + e.Exception.Message);
    }

    // Close the connection
    ftp1.Close();
}

See Also

InvokeEventArgs Class | Dart.PowerTCP.Ftp Namespace


State Property

InvokeEventArgs.State Property

Gets the object that was included as part of the associated method call.

[Visual Basic]
Public Property ReadOnly State As Object
[C#]
public object State { get; }
[C++]
public: __property Object* get_State();
[JScript]
public function get State() : Object

Property Value

An object containing data passed into the calling asynchronous method.

Remarks

The EndEventArgs.State property can be used in the calling asynchronous method to make data accessible to the handling event.

This property is useful for making data accessible to the handling event. Since asynchronous methods are "disconnected" (meaning that when one is called, it executes on it's own and returns in the event handler) data that you were using in the code that called the asynchronous method may not be available in the event handler. Simply pass this data in as state when calling the asynchronous method (usually a BeginXXX method) and it is available in the event handler. If you do not wish to make an object accessible in the EndXXX event, simple pass in null as state.

See Also

InvokeEventArgs Class | Dart.PowerTCP.Ftp Namespace


InvokeEventHandler Delegate

Represents the method (event handler) that will be raised when the Object.BeginInvoke operation completes.

[Visual Basic]
Public Delegate Function Sub  InvokeEventHandler( _
   ByVal sender As Object, _
   ByVal e As InvokeEventArgs _
)
[C#]
public delegate void InvokeEventHandler(
   object sender,
   InvokeEventArgs e
)
[C++]
public __gc __delegate void InvokeEventHandler(
   Object* sender,
   InvokeEventArgs* e
)

[JScript] In JScript, you can use the delegates defined by a type, but you cannot define your own.

Parameters

sender
The source of the event.
e
An InvokeEventArgs object that contains the event data.

Remarks

As Microsoft describes in their MSDN documentation, the event model in the .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed:

  • A class that holds the event data. This class must derive from the base class EventArgs.
  • A delegate that points to a method that provides the response to the event.
When using the Object.BeginInvoke method, the class that holds the event data is the InvokeEventArgs class. A method must be created with the same signature as the delegate. If you are working within the Visual Studio.NET environment, this can be automatically done for you. See the "Using Events In PowerTCP" topic for more information. If you are not working within the Visual Studio.NET environment, you must do this yourself. In this example that would mean a method would have to be defined to accept two arguments (an object and a InvokeEventArgs) and return void. Once this has been done, the delegate must be "connected" to the handling event. This is done by adding an instance of the delegate to the event (see examples below).

For more information about event handler delegates, see the "Using Events In PowerTCP" topic.

Example

The following example demonstrates how to assign an event handler to an event.

[Visual Basic]
' *** EndInvoke Event ***

' You can either use the AddHandler statement to associate an event with an event handler in your init code
AddHandler Ftp1.EndInvoke, New Dart.PowerTCP.Ftp.InvokeEventHandler(AddressOf Ftp1_EndInvoke)

' Or you can use the Handles keyword to associate an event handler with an event
Private Sub Ftp1_EndInvoke(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.InvokeEventArgs) Handles Ftp1.EndInvoke

[C#]
// EndInvoke event
this.ftp1.EndInvoke += new Dart.PowerTCP.Ftp.InvokeEventHandler(this.ftp1_EndInvoke);

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


KeyUsage Enumeration

Enumerates the uses for a key.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

[Visual Basic]
Public Enum KeyUsage
[C#]
public enum KeyUsage
[C++]
public __value enum KeyUsage
[JScript]
public enum KeyUsage

Remarks

Key usage is an extension to the x.509 certificate format specifying the purpose for a key.

Members

Member Name | Description | Value
EncipherOnly | Certificate can be used for Key Encipherment. | 1
CrlSigning | Certificate can be used for signing the Certificate Revocation List (CRL). | 2
CertificateSigning | Certificate can be used for certificate validation. | 4
KeyAgreement | Certificate can be used for key negotiation. | 8
DataEncipherment | Certificate can be used for encryption. | 16
KeyEncipherment | Certificate can be used for symmetric key transfer. | 32
NonRepudiation | Certificate can be used for validation | 64
DigitalSignature | Certificate can be used for data validation. | 128
ServerAuth | Certificate can be used for server authentication. | 256
ClientAuth | Certificate can be used for client authentication. | 512
CodeSigning | Certificate can be used for code signing. | 1024
EmailProtection | Certificate can be used for email encryption. | 2048
IPSecEndSystem | Certificate can be used for IPSec “server”. | 4096
IPSecTunnel | Certificate can be used for IPSec transfer encryption. | 8192
IPSecUser | Certificate can be used for IPSec user encryption. | 16384
TimestampSigning | Certificate can be used for timestamp validation | 32768
All | Certificate can be used for everything. | 65535

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


ListEntry Class

Represents each line of the textual listing received from an FTP server

For a list of all members of this type, see ListEntry Members.

System.Object
Dart.PowerTCP.Ftp.ListEntry

[Visual Basic]
Public Class ListEntry
[C#]
public class ListEntry
[C++]
public __gc class ListEntry
[JScript]
public class ListEntry

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

When any method is called that requests an FTP listing from the server (for example, List or BeginList) a Listing object (and all of the ListEntry objects contained within this object) is automatically created. The ListEntry object represents the fields of a listing, such as name, path, time stamp, etc.

For example, the following code,

Dart.PowerTCP.Listing myList =  ftp1.List("*", true);

would return a listing that would be encapsulated by the Listing object myList. This object would be made up of many ListEntry objects describing each individual file/directory. For example, perhaps the raw listing returned from the above method call was as follows:

-rw-r--r--   1 test     users         240 Aug 10 09:23 file1.txt
-rw-r--r--   1 test     users         255 Aug 10 09:23 file2.txt

This would return a Listing object with two ListEntry objects. The values for the first ListEntry object (contained at myList[0]) would look like the following:

Property | Value
myList[0].Name | "file1.txt"
myList[0].Permissions | "-rw-r--r--"
myList[0].Group | "users"
myList[0].Size | 12
myList[0].TimeStamp | "Oct 19 10:08"
myList[0].Text | "-rw-r--r-- 1 test users 240 Aug 10 09:23 file1.txt"

If a field is needed that is not represented in the ListEntry object, simple use the Text property to retrieve the raw text listing, and parse appropriately.

Example

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Retrieve file list. Listing details will be contained in the Listing Object
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Begin setting up the ListView diplay
' Show gridlines.
ListView1.GridLines = True

' Set View to Details
ListView1.View = View.Details

' Add column headings for file name, size, and date.
ListView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left)

' Iterate through the listing, adding a row to the ListBox for each
Dim le As Dart.PowerTCP.Ftp.ListEntry
For Each le In list

   ' Display files only
   If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then
      Dim cols() As String = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp}
      ListView1.Items.Add(New ListViewItem(cols))
   End If
Next

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Retrieve file list. Listing details will be contained in the Listing Object
Dart.PowerTCP.Ftp.Listing list = ftp1.List("*", true);

// Begin setting up the ListView diplay

// Show gridlines.
listView1.GridLines = true;

// Set View to Details
listView1.View = View.Details;

// Add column headings for file name, size, and date.
listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

// Iterate through the listing, adding a row to the ListBox for each
foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
{
    // Display files only
    if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
    {
        string[] cols = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp};
        listView1.Items.Add(new ListViewItem(cols));
    }
}

// Close the connection
ftp1.Close();

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

ListEntry Members | Dart.PowerTCP.Ftp Namespace


ListEntry Members

ListEntry overview

Public Instance Constructors

ListEntry Constructor Creates a new instance of ListEntry.

Public Instance Properties

Destination | Gets or sets the actual location to which a link is pointing when Format indicates a UNIX listing, and Listing.Type is Link. Can be set by the user when parsing the Text property.
Group | When Format indicates a UNIX listing, gets the UNIX file group name. Can be set by the user when parsing the Text property.
Name | Gets or sets the file or directory name, depending on the value of the Type property. Can be set by the user when parsing the Text property.
Owner | When Format indicates a UNIX listing, gets the UNIX file owner name. Can be set by the user when parsing the Text property.
Path | Gets the path reported for files in sub-directories. Can be set by the user when parsing the Text property.
Permissions | In UNIX, gets the file permissions for a ListEntry object. Can be set by the user when parsing the Text property.
Size | Gets the size of the file in bytes. Can be set by the user when parsing the Text property.
Source | When Format indicates a UNIX listing, and Type is Link, gets the name of the link. Can be set by the user when parsing the Text property.
Text | Gets the raw list entry.
TimeStamp | Gets the time/date the file was last modified. Can be set by the user when parsing the Text property.
Type | Gets type of entry (File or Directory)

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


ListEntry Constructor

Creates a new instance of ListEntry.

[Visual Basic]
Public Sub New( _
   ByVal text As String, _
   ByVal path As String, _
   ByVal format As ListingFormat, _
   ByVal full As Boolean _
)
[C#]
public ListEntry(
   string text,
   string path,
   ListingFormat format,
   bool full
);
[C++]
public: ListEntry(
   String* text,
   String* path,
   ListingFormat format,
   bool full
);
[JScript]
public function ListEntry(
   String text,
   String path,
   ListingFormat format,
   bool full
);

Parameters

text
Line received from the server.
path
Path information returned from the server.
format
Format of the Listing.
full
Indicates a full listing or a name list.

Remarks

When any method is called that requests an FTP listing from the server (for example, List or BeginList) a Listing object (and all of the ListEntry objects contained within this object) is automatically created.

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


ListEntry Properties

The properties of the ListEntry class are listed below. For a complete list of ListEntry class members, see the ListEntry Members topic.

Public Instance Properties

Destination | Gets or sets the actual location to which a link is pointing when Format indicates a UNIX listing, and Listing.Type is Link. Can be set by the user when parsing the Text property.
Group | When Format indicates a UNIX listing, gets the UNIX file group name. Can be set by the user when parsing the Text property.
Name | Gets or sets the file or directory name, depending on the value of the Type property. Can be set by the user when parsing the Text property.
Owner | When Format indicates a UNIX listing, gets the UNIX file owner name. Can be set by the user when parsing the Text property.
Path | Gets the path reported for files in sub-directories. Can be set by the user when parsing the Text property.
Permissions | In UNIX, gets the file permissions for a ListEntry object. Can be set by the user when parsing the Text property.
Size | Gets the size of the file in bytes. Can be set by the user when parsing the Text property.
Source | When Format indicates a UNIX listing, and Type is Link, gets the name of the link. Can be set by the user when parsing the Text property.
Text | Gets the raw list entry.
TimeStamp | Gets the time/date the file was last modified. Can be set by the user when parsing the Text property.
Type | Gets type of entry (File or Directory)

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


Destination Property

ListEntry.Destination Property

Gets or sets the actual location to which a link is pointing when Format indicates a UNIX listing, and Listing.Type is Link. Can be set by the user when parsing the Text property.

[Visual Basic]
Public Property Destination As String
[C#]
public string Destination { get; set; }
[C++]
public: __property String* get_Destination();
public: __property void set_Destination(String* );
[JScript]
public function get Destination() : String
public function set Destination(String);

Property Value

A string representing the actual location to which a link is pointing

Remarks

UNIX links act as shortcuts to other files. For example, if there is a link named "MyLink" pointing to a file called "MyFile.txt", the Name property will be "MyLink". To get the actual file, you would have to access Destination, which would contain "MyFile.txt".

This property will only have a value if the Format is UNIX and the Type is Link.

Example

The following example demonstrates checking the ListEntry to determine if it is a link, and displaying appropriately.

[Visual Basic]
' In this example, a Listing is displayed. In the cases where a link
' is present, instead of displaying the link, the actual file the link
' is pointing to will be displayed

' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in/log out taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "MyPass"

' Retrieve listing
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Iterate through the ListEntries
Dim le As Dart.PowerTCP.Ftp.ListEntry
For Each le In list

    If le.Type = Dart.PowerTCP.Ftp.EntryType.Link Then
        ' It is a link, add the link to the ListBox
        listBox1.Items.Add(le.Source + "->" + le.Destination)
    else
        'It is not a link, display the file name
        listBox1.Items.Add(le.Name)
    End If
Next

' Close the connection
Ftp1.Close()

[C#]
// In this example, a Listing is displayed. In the cases where a link
// is present, instead of displaying the link, the actual file the link
// is pointing to will be displayed

// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "MyPass";

// Retrieve listing
Dart.PowerTCP.Ftp.Listing list =  ftp1.List("*", true);

// Iterate through the ListEntries
foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
{
    if(le.Type == Dart.PowerTCP.Ftp.EntryType.Link)
        // It is a link, add the link to the ListBox
        listBox1.Items.Add(le.Source + "->" + le.Destination);
    else
        // It is not a link, display the file name
        listBox1.Items.Add(le.Name);
}

// Close the connection
ftp1.Close();

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


Group Property

ListEntry.Group Property

When Format indicates a UNIX listing, gets the UNIX file group name. Can be set by the user when parsing the Text property.

[Visual Basic]
Public Property Group As String
[C#]
public string Group { get; set; }
[C++]
public: __property String* get_Group();
public: __property void set_Group(String* );
[JScript]
public function get Group() : String
public function set Group(String);

Property Value

A string representing the UNIX file group name.

Remarks

This property will only have value when the Format property is UNIX. To determine group rights, see Permissions.

Example

The following example demonstrates displaying UNIX-only properties in a Listing

[Visual Basic]
' Set server and user properties. This will allow us to call other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Ftp.List returns a Listing object
Dim list As Dart.PowerTCP.Ftp.Listing

' Get a listing
list = Ftp1.List("*", True)

' Check to be sure it is UNIX
If list.Format = Dart.PowerTCP.Ftp.ListingFormat.UNIX Then

   ' Display the fields that are only available in a UNIX listing

   ' Begin setting up the ListView diplay

   ' Show gridlines.
   listView1.GridLines = True

   ' Set View to Details
   listView1.View = View.Details

   ' Add column headings for the generic ListEntry properties.
   listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left)
   listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left)
   listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left)

   ' Add column headings for the UNIX only ListEntry properties
   listView1.Columns.Add("File Group", 100, System.Windows.Forms.HorizontalAlignment.Left)
   listView1.Columns.Add("File Owner", 100, System.Windows.Forms.HorizontalAlignment.Left)
   listView1.Columns.Add("File Permissions", 100, System.Windows.Forms.HorizontalAlignment.Left)

   ' Iterate through the listing, adding a row to the ListBox for each
   Dim le As Dart.PowerTCP.Ftp.ListEntry
   For Each le In list

      ' Display files only
         If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then

            Dim cols() As String = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp, le.Group, le.Owner, le.Permissions}
            listView1.Items.Add(New ListViewItem(cols))

         End If
   Next
End If

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Ftp.List returns a Listing object
Dart.PowerTCP.Ftp.Listing list;

// Get a listing
list = ftp1.List("*", true);

// Check to be sure it is UNIX
if(list.Format == Dart.PowerTCP.Ftp.ListingFormat.UNIX)
{
    // Display the fields that are only available in a UNIX listing

    // Begin setting up the ListView diplay

    // Show gridlines.
    listView1.GridLines = true;

    // Set View to Details
    listView1.View = View.Details;

    // Add column headings for the generic ListEntry properties.
    listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

    // Add column headings for the UNIX only ListEntry properties
    listView1.Columns.Add("File Group", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Owner", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Permissions", 100, System.Windows.Forms.HorizontalAlignment.Left);

    // Iterate through the listing, adding a row to the ListBox for each
    foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
    {
        // Display files only
        if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
        {
            string[] cols = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp, le.Group, le.Owner, le.Permissions };
            listView1.Items.Add(new ListViewItem(cols));
        }
    }

    // Close the connection
    ftp1.Close();

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


Name Property

ListEntry.Name Property

Gets or sets the file or directory name, depending on the value of the Type property. Can be set by the user when parsing the Text property.

[Visual Basic]
Public Property Name As String
[C#]
public string Name { get; set; }
[C++]
public: __property String* get_Name();
public: __property void set_Name(String* );
[JScript]
public function get Name() : String
public function set Name(String);

Property Value

A string representing the name of the file or directory.

Remarks

This property represents the name of the file only. To obtain the path, use the Path property.

If the Format is UNIX and the Type is Link, this property will contain the value of the link name. In this case to obtain the file the link is pointing to, see Destination.

Example

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Retrieve file list. Listing details will be contained in the Listing Object
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Begin setting up the ListView diplay
' Show gridlines.
ListView1.GridLines = True

' Set View to Details
ListView1.View = View.Details

' Add column headings for file name, size, and date.
ListView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left)

' Iterate through the listing, adding a row to the ListBox for each
Dim le As Dart.PowerTCP.Ftp.ListEntry
For Each le In list

   ' Display files only
   If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then
      Dim cols() As String = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp}
      ListView1.Items.Add(New ListViewItem(cols))
   End If
Next

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Retrieve file list. Listing details will be contained in the Listing Object
Dart.PowerTCP.Ftp.Listing list = ftp1.List("*", true);

// Begin setting up the ListView diplay

// Show gridlines.
listView1.GridLines = true;

// Set View to Details
listView1.View = View.Details;

// Add column headings for file name, size, and date.
listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

// Iterate through the listing, adding a row to the ListBox for each
foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
{
    // Display files only
    if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
    {
        string[] cols = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp};
        listView1.Items.Add(new ListViewItem(cols));
    }
}

// Close the connection
ftp1.Close();

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


Owner Property

ListEntry.Owner Property

When Format indicates a UNIX listing, gets the UNIX file owner name. Can be set by the user when parsing the Text property.

[Visual Basic]
Public Property Owner As String
[C#]
public string Owner { get; set; }
[C++]
public: __property String* get_Owner();
public: __property void set_Owner(String* );
[JScript]
public function get Owner() : String
public function set Owner(String);

Property Value

A string representing the UNIX file owner.

Remarks

This property will only have a value if the Format is UNIX. The owner is typically the person who created the file. Inspect Permissions to determine owner rights.

Example

The following example demonstrates displaying UNIX-only properties in a Listing

[Visual Basic]
' Set server and user properties. This will allow us to call other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Ftp.List returns a Listing object
Dim list As Dart.PowerTCP.Ftp.Listing

' Get a listing
list = Ftp1.List("*", True)

' Check to be sure it is UNIX
If list.Format = Dart.PowerTCP.Ftp.ListingFormat.UNIX Then

   ' Display the fields that are only available in a UNIX listing

   ' Begin setting up the ListView diplay

   ' Show gridlines.
   listView1.GridLines = True

   ' Set View to Details
   listView1.View = View.Details

   ' Add column headings for the generic ListEntry properties.
   listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left)
   listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left)
   listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left)

   ' Add column headings for the UNIX only ListEntry properties
   listView1.Columns.Add("File Group", 100, System.Windows.Forms.HorizontalAlignment.Left)
   listView1.Columns.Add("File Owner", 100, System.Windows.Forms.HorizontalAlignment.Left)
   listView1.Columns.Add("File Permissions", 100, System.Windows.Forms.HorizontalAlignment.Left)

   ' Iterate through the listing, adding a row to the ListBox for each
   Dim le As Dart.PowerTCP.Ftp.ListEntry
   For Each le In list

      ' Display files only
         If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then

            Dim cols() As String = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp, le.Group, le.Owner, le.Permissions}
            listView1.Items.Add(New ListViewItem(cols))

         End If
   Next
End If

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Ftp.List returns a Listing object
Dart.PowerTCP.Ftp.Listing list;

// Get a listing
list = ftp1.List("*", true);

// Check to be sure it is UNIX
if(list.Format == Dart.PowerTCP.Ftp.ListingFormat.UNIX)
{
    // Display the fields that are only available in a UNIX listing

    // Begin setting up the ListView diplay

    // Show gridlines.
    listView1.GridLines = true;

    // Set View to Details
    listView1.View = View.Details;

    // Add column headings for the generic ListEntry properties.
    listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

    // Add column headings for the UNIX only ListEntry properties
    listView1.Columns.Add("File Group", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Owner", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Permissions", 100, System.Windows.Forms.HorizontalAlignment.Left);

    // Iterate through the listing, adding a row to the ListBox for each
    foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
    {
        // Display files only
        if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
        {
            string[] cols = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp, le.Group, le.Owner, le.Permissions };
            listView1.Items.Add(new ListViewItem(cols));
        }
    }

    // Close the connection
    ftp1.Close();

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


Path Property

ListEntry.Path Property

Gets the path reported for files in sub-directories. Can be set by the user when parsing the Text property.

[Visual Basic]
Public Property Path As String
[C#]
public string Path { get; set; }
[C++]
public: __property String* get_Path();
public: __property void set_Path(String* );
[JScript]
public function get Path() : String
public function set Path(String);

Property Value

A string representing the path of the file.

Remarks

This property represents the path of the file only. To obtain the name, use the Name property.

This property will only have a value if:

  1. The List call is for a recursive listing: Ftp.List("-R", true)
  2. The server supports recursive listings, in the format of:
 ./hello: total 12 -rw-r----- 1 test users 5751 Jan 29 2003 links.txt ./newdir: total 12 -rw-r----- 1 test users 4339 Jan 29 2003 imapdebug2.txt -rw-r----- 1 test users 12 Jan 27 2003 rtv.txt

Example

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Retrieve file list. Listing details will be contained in the Listing Object
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Begin setting up the ListView diplay
' Show gridlines.
ListView1.GridLines = True

' Set View to Details
ListView1.View = View.Details

' Add column headings for file name, size, and date.
ListView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left)

' Iterate through the listing, adding a row to the ListBox for each
Dim le As Dart.PowerTCP.Ftp.ListEntry
For Each le In list

   ' Display files only
   If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then
      Dim cols() As String = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp}
      ListView1.Items.Add(New ListViewItem(cols))
   End If
Next

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Retrieve file list. Listing details will be contained in the Listing Object
Dart.PowerTCP.Ftp.Listing list = ftp1.List("*", true);

// Begin setting up the ListView diplay

// Show gridlines.
listView1.GridLines = true;

// Set View to Details
listView1.View = View.Details;

// Add column headings for file name, size, and date.
listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

// Iterate through the listing, adding a row to the ListBox for each
foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
{
    // Display files only
    if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
    {
        string[] cols = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp};
        listView1.Items.Add(new ListViewItem(cols));
    }
}

// Close the connection
ftp1.Close();

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


Permissions Property

ListEntry.Permissions Property

In UNIX, gets the file permissions for a ListEntry object. Can be set by the user when parsing the Text property.

[Visual Basic]
Public Property Permissions As String
[C#]
public string Permissions { get; set; }
[C++]
public: __property String* get_Permissions();
public: __property void set_Permissions(String* );
[JScript]
public function get Permissions() : String
public function set Permissions(String);

Property Value

A string representing the UNIX permissions.

Remarks

This property will only be valid if the Format is UNIX. Use the Permissions property if the server is returning a UNIX listing and you would like to know the permissions for a file.

Example

The following example demonstrates displaying UNIX-only properties in a Listing

[Visual Basic]
' Set server and user properties. This will allow us to call other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Ftp.List returns a Listing object
Dim list As Dart.PowerTCP.Ftp.Listing

' Get a listing
list = Ftp1.List("*", True)

' Check to be sure it is UNIX
If list.Format = Dart.PowerTCP.Ftp.ListingFormat.UNIX Then

   ' Display the fields that are only available in a UNIX listing

   ' Begin setting up the ListView diplay

   ' Show gridlines.
   listView1.GridLines = True

   ' Set View to Details
   listView1.View = View.Details

   ' Add column headings for the generic ListEntry properties.
   listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left)
   listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left)
   listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left)

   ' Add column headings for the UNIX only ListEntry properties
   listView1.Columns.Add("File Group", 100, System.Windows.Forms.HorizontalAlignment.Left)
   listView1.Columns.Add("File Owner", 100, System.Windows.Forms.HorizontalAlignment.Left)
   listView1.Columns.Add("File Permissions", 100, System.Windows.Forms.HorizontalAlignment.Left)

   ' Iterate through the listing, adding a row to the ListBox for each
   Dim le As Dart.PowerTCP.Ftp.ListEntry
   For Each le In list

      ' Display files only
         If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then

            Dim cols() As String = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp, le.Group, le.Owner, le.Permissions}
            listView1.Items.Add(New ListViewItem(cols))

         End If
   Next
End If

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Ftp.List returns a Listing object
Dart.PowerTCP.Ftp.Listing list;

// Get a listing
list = ftp1.List("*", true);

// Check to be sure it is UNIX
if(list.Format == Dart.PowerTCP.Ftp.ListingFormat.UNIX)
{
    // Display the fields that are only available in a UNIX listing

    // Begin setting up the ListView diplay

    // Show gridlines.
    listView1.GridLines = true;

    // Set View to Details
    listView1.View = View.Details;

    // Add column headings for the generic ListEntry properties.
    listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

    // Add column headings for the UNIX only ListEntry properties
    listView1.Columns.Add("File Group", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Owner", 100, System.Windows.Forms.HorizontalAlignment.Left);
    listView1.Columns.Add("File Permissions", 100, System.Windows.Forms.HorizontalAlignment.Left);

    // Iterate through the listing, adding a row to the ListBox for each
    foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
    {
        // Display files only
        if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
        {
            string[] cols = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp, le.Group, le.Owner, le.Permissions };
            listView1.Items.Add(new ListViewItem(cols));
        }
    }

    // Close the connection
    ftp1.Close();

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


Size Property

ListEntry.Size Property

Gets the size of the file in bytes. Can be set by the user when parsing the Text property.

[Visual Basic]
Public Property Size As Long
[C#]
public long Size { get; set; }
[C++]
public: __property __int64 get_Size();
public: __property void set_Size(__int64 );
[JScript]
public function get Size() : long
public function set Size(long);

Property Value

An integer value representing the size of the file or directory as reported by the server in the listing

Remarks

This value may not reflect the actual size of the file, as CRLF may not be included in the count by the server. To get the actual file size for any file, use GetSize.

Example

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Retrieve file list. Listing details will be contained in the Listing Object
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Begin setting up the ListView diplay
' Show gridlines.
ListView1.GridLines = True

' Set View to Details
ListView1.View = View.Details

' Add column headings for file name, size, and date.
ListView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left)

' Iterate through the listing, adding a row to the ListBox for each
Dim le As Dart.PowerTCP.Ftp.ListEntry
For Each le In list

   ' Display files only
   If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then
      Dim cols() As String = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp}
      ListView1.Items.Add(New ListViewItem(cols))
   End If
Next

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Retrieve file list. Listing details will be contained in the Listing Object
Dart.PowerTCP.Ftp.Listing list = ftp1.List("*", true);

// Begin setting up the ListView diplay

// Show gridlines.
listView1.GridLines = true;

// Set View to Details
listView1.View = View.Details;

// Add column headings for file name, size, and date.
listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

// Iterate through the listing, adding a row to the ListBox for each
foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
{
    // Display files only
    if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
    {
        string[] cols = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp};
        listView1.Items.Add(new ListViewItem(cols));
    }
}

// Close the connection
ftp1.Close();

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


Source Property

ListEntry.Source Property

When Format indicates a UNIX listing, and Type is Link, gets the name of the link. Can be set by the user when parsing the Text property.

[Visual Basic]
Public Property Source As String
[C#]
public string Source { get; set; }
[C++]
public: __property String* get_Source();
public: __property void set_Source(String* );
[JScript]
public function get Source() : String
public function set Source(String);

Property Value

A string representing the name of a UNIX link.

Remarks

UNIX links act as shortcuts to other files. For example, if there is a link named "MyLink" pointing to a file called "MyFile.txt", the Source property will be "MyLink". To get the actual file, you would have to access Destination, which would contain "MyFile.txt".

This property will only have a value if the Format is UNIX and the Type is Link.

Example

The following example demonstrates checking the ListEntry to determine if it is a link, and displaying appropriately.

[Visual Basic]
' In this example, a Listing is displayed. In the cases where a link
' is present, instead of displaying the link, the actual file the link
' is pointing to will be displayed

' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in/log out taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "MyPass"

' Retrieve listing
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Iterate through the ListEntries
Dim le As Dart.PowerTCP.Ftp.ListEntry
For Each le In list

    If le.Type = Dart.PowerTCP.Ftp.EntryType.Link Then
        ' It is a link, add the link to the ListBox
        listBox1.Items.Add(le.Source + "->" + le.Destination)
    else
        'It is not a link, display the file name
        listBox1.Items.Add(le.Name)
    End If
Next

' Close the connection
Ftp1.Close()

[C#]
// In this example, a Listing is displayed. In the cases where a link
// is present, instead of displaying the link, the actual file the link
// is pointing to will be displayed

// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in/log out taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "MyPass";

// Retrieve listing
Dart.PowerTCP.Ftp.Listing list =  ftp1.List("*", true);

// Iterate through the ListEntries
foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
{
    if(le.Type == Dart.PowerTCP.Ftp.EntryType.Link)
        // It is a link, add the link to the ListBox
        listBox1.Items.Add(le.Source + "->" + le.Destination);
    else
        // It is not a link, display the file name
        listBox1.Items.Add(le.Name);
}

// Close the connection
ftp1.Close();

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


Text Property

ListEntry.Text Property

Gets the raw list entry.

[Visual Basic]
Public Property ReadOnly Text As String
[C#]
public string Text { get; }
[C++]
public: __property String* get_Text();
[JScript]
public function get Text() : String

Property Value

A string value representing the raw text returned from the server for the particular list entry.

Remarks

Listings are automatically parsed for most common fields. However, many servers have proprietary fields. In cases such as this, for listing fields not contained within the ListEntry object, the raw listing can be retrieved using this property, and parsed.

The Text property is useful for diagnostics purposes, to see a raw ListEntry. It is also useful for dealing with servers that return a "proprietary" listing. For example, if the server may return a UNIX listing. This would look something like:

r-xr-xr-x   1 owner    group               20 Jan 10  2002 file1.txt

It also may return a DOS listing which would look something like:

01-10-02  10:18AM                    20 file1.txt

In either of these cases, the format would be detected and Format would be set appropriately. However, if the listing returned was a proprietary listing such as:

file1.txt   Jan-10-2002   20

The Ftp component would be unable to detect the type. You would have to get the raw text using the Text property, and parse it yourself.

Example

The following example demonstrates parsing a listing. This example demonstrates checking the format, and parsing if unknown.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Retrieve file list. Listing details will be contained in the Listing Object
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Check to see if the server returned an Unknown listing
If list.Format = Dart.PowerTCP.Ftp.ListingFormat.Unknown Then

   ' In this example, the server is returning a proprietary listing which looks like:
   '            myfile.txt     158     01-11-02     11:55

   ' Create a pattern to use as a RegularExpression which matches the above listing format
   Dim pattern As String
   pattern = "(?<filename>\S+)\s+(?<filesize>\S+)\s+(?<filedate>\S+)\s+(?<filetime>\S+)"

   ' Create new Regex object
   Dim regex As New System.Text.RegularExpressions.Regex(pattern)

   ' Iterate through ListEntries
   Dim l As Dart.PowerTCP.Ftp.ListEntry
   For Each l In list

      ' Get raw listing
      Dim raw As String = l.Text

      ' Attempt to match regular expression
      Dim match As System.Text.RegularExpressions.Match
      match = regex.Match(raw)

      ' Extract groupnames from Groups collection
      Dim filename As String = match.Groups["filename"].Value
      Dim filesize As String = match.Groups["filesize"].Value
      Dim filedate As String = match.Groups["filedate"].Value
      Dim filetime As String = match.Groups["filetime"].Value

      ' Display result
      Debug.WriteLine("Filename: " + filename)
      Debug.WriteLine("Filesize: " + filesize)
      Debug.WriteLine("Filedate: " + filedate)
      Debug.WriteLine("Filetime: " + filetime)
   Next

   'Close the connection
   Ftp1.Close()
End If

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// In this example, the server is returning a proprietary listing which looks like:
//            myfile.txt     158     01-11-02     11:55

// Create a pattern to use as a RegularExpression which matches the above listing format
string ppattern = @"(?<filename>\S+)\s+(?<filesize>\S+)\s+(?<filedate>\S+)\s+(?<filetime>\S+)";

// Retrieve file list. Listing details will be contained in the Listing Object
Dart.PowerTCP.Ftp.Listing list = ftp1.List("*", true);

// Check to see if the server returned an Unknown listing format
if(list.Format == Dart.PowerTCP.Ftp.ListingFormat.Unknown)
{
    // Create new Regex object
    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern);

    // Iterate through ListEntries
    foreach(Dart.PowerTCP.Ftp.ListEntry l in list)
    {
        // Get raw listing
        string raw = l.Text;

        // Attempt to match regular expression
        System.Text.RegularExpressions.Match match = regex.Match(raw);

        // Extract groupnames from Groups collection
        string filename = match.Groups["filename"].Value;
        string filesize = match.Groups["filesize"].Value;
        string filedate = match.Groups["filedate"].Value;
        string filetime = match.Groups["filetime"].Value;

        // Display result
        Debug.WriteLine("Filename: " + filename);
        Debug.WriteLine("Filesize: " + filesize);
        Debug.WriteLine("Filedate: " + filedate);
        Debug.WriteLine("Filetime: " + filetime);
    }

    // Close the connection
    ftp1.Close();
}

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


TimeStamp Property

ListEntry.TimeStamp Property

Gets the time/date the file was last modified. Can be set by the user when parsing the Text property.

[Visual Basic]
Public Property TimeStamp As String
[C#]
public string TimeStamp { get; set; }
[C++]
public: __property String* get_TimeStamp();
public: __property void set_TimeStamp(String* );
[JScript]
public function get TimeStamp() : String
public function set TimeStamp(String);

Property Value

A string representing the time/date the file was last modified.

Example

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Retrieve file list. Listing details will be contained in the Listing Object
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Begin setting up the ListView diplay
' Show gridlines.
ListView1.GridLines = True

' Set View to Details
ListView1.View = View.Details

' Add column headings for file name, size, and date.
ListView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left)

' Iterate through the listing, adding a row to the ListBox for each
Dim le As Dart.PowerTCP.Ftp.ListEntry
For Each le In list

   ' Display files only
   If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then
      Dim cols() As String = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp}
      ListView1.Items.Add(New ListViewItem(cols))
   End If
Next

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Retrieve file list. Listing details will be contained in the Listing Object
Dart.PowerTCP.Ftp.Listing list = ftp1.List("*", true);

// Begin setting up the ListView diplay

// Show gridlines.
listView1.GridLines = true;

// Set View to Details
listView1.View = View.Details;

// Add column headings for file name, size, and date.
listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

// Iterate through the listing, adding a row to the ListBox for each
foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
{
    // Display files only
    if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
    {
        string[] cols = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp};
        listView1.Items.Add(new ListViewItem(cols));
    }
}

// Close the connection
ftp1.Close();

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


Type Property

ListEntry.Type Property

Gets type of entry (File or Directory)

[Visual Basic]
Public Property ReadOnly Type As EntryType
[C#]
public EntryType Type { get; }
[C++]
public: __property EntryType get_Type();
[JScript]
public function get Type() : EntryType

Property Value

One of the EntryType values.

Remarks

The Type of Listing will either be EntryType.File, EntryType.Directory, or EntryType.Link. If the Type is EntryType.Link, the Source property will contain the link name and the Destination property will contain the file the link is pointing to.

Example

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Retrieve file list. Listing details will be contained in the Listing Object
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Begin setting up the ListView diplay
' Show gridlines.
ListView1.GridLines = True

' Set View to Details
ListView1.View = View.Details

' Add column headings for file name, size, and date.
ListView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left)

' Iterate through the listing, adding a row to the ListBox for each
Dim le As Dart.PowerTCP.Ftp.ListEntry
For Each le In list

   ' Display files only
   If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then
      Dim cols() As String = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp}
      ListView1.Items.Add(New ListViewItem(cols))
   End If
Next

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Retrieve file list. Listing details will be contained in the Listing Object
Dart.PowerTCP.Ftp.Listing list = ftp1.List("*", true);

// Begin setting up the ListView diplay

// Show gridlines.
listView1.GridLines = true;

// Set View to Details
listView1.View = View.Details;

// Add column headings for file name, size, and date.
listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

// Iterate through the listing, adding a row to the ListBox for each
foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
{
    // Display files only
    if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
    {
        string[] cols = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp};
        listView1.Items.Add(new ListViewItem(cols));
    }
}

// Close the connection
ftp1.Close();

See Also

ListEntry Class | Dart.PowerTCP.Ftp Namespace


ListEventArgs Class

This class is passed into the EndList event and provides data for this event.

For a list of all members of this type, see ListEventArgs Members.

System.Object
System.EventArgs
Dart.PowerTCP.Ftp.ListEventArgs

[Visual Basic]
Public Class ListEventArgs
    Inherits EventArgs
[C#]
public class ListEventArgs : EventArgs
[C++]
public __gc class ListEventArgs : public EventArgs
[JScript]
public class ListEventArgs extends EventArgs

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

A ListEventArgs object is passed into the EndList event after asynchronous list retrieval has taken place. This object contains a Listing object, which encapsulates an FTP listing, and an object. Iterate through the Listing property to access the individual ListEntry objects. The State object allows access to data and variables that were in use in the method from which BeginList was called in the EndList event. Simply pass whatever you wish as State.

If any error occurred during the asynchronous method call, it would be returned in the handling event. To trap the error, simply put a try/catch block around any access of the parameter e.

Example

The following example demonstrates using BeginList to retrieve a Listing asynchronously.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Get a listing for all text files in home/test. Upon completion the EndList
' event will fire, with the Listing passed in as an arg
 Ftp1.BeginList("/home/test/*.txt", True, Nothing)

' Because BeginList is asynchronous, this line will be immediately executed.
Debug.WriteLine("Retrieving Listing")

' When the BeginList operation has completed, the EndList Event will fire.
Private Sub Ftp1_EndList(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ListEventArgs) Handles Ftp1.EndList

   ' If an error occurred during the asynchronous method, it would be
   ' returned in the event. Be sure to check for it.
   if e.Exception Is Nothing Then

      ' Retrieve listing and display

      ' Begin setting up the ListView (listView1 is a standard ListView object) display

      ' Show gridlines.
      ListView1.GridLines = True

      ' Set View to Details
      ListView1.View = View.Details

      ' Add column headings for file name, size, and date.
      ListView1.Columns.Add("File Name", 100, HorizontalAlignment.Left)
      ListView1.Columns.Add("File Size", 100, HorizontalAlignment.Left)
      ListView1.Columns.Add("File Timestamp", 100, HorizontalAlignment.Left)

      ' Iterate through the listing, adding a row to the ListBox for each
      Dim le As Dart.PowerTCP.Ftp.ListEntry
      For Each le In e.Listing
         Dim cols() As String = {le.Name, le.Size.ToString(), le.TimeStamp}
         ListView1.Items.Add(New ListViewItem(cols))
      Next
  Else
     Debug.WriteLine(e.Exception.Message)
  End If

  ' Close the connection
  Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Get a listing for all text files in home/test. Upon completion the EndList
// event will fire, with the Listing passed in as an arg
ftp1.BeginList("/home/test/*.txt", true, null);

// Because BeginList is asynchronous, this line will be immediately executed.
Debug.WriteLine("Retrieving listing");

// When the BeginList operation has completed, the EndList Event will fire.

private void ftp1_EndList(object sender, Dart.PowerTCP.Ftp.ListEventArgs e)
{
    // If an error occurred during the asynchronous method, it would
    // be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
       // Retrieve listing and display

       // Begin setting up the ListView (listView1 is a standard ListView object) display

       // Show gridlines.
       listView1.GridLines = true;

       // Set View to Details
       listView1.View = View.Details;

       // Add column headings for file name, size, and date.
       listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
       listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
       listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

       // Iterate through the listing, adding a row to the ListBox for each
       foreach(Dart.PowerTCP.Ftp.ListEntry le in e.Listing)
       {
          string[] cols = {le.Name, le.Size.ToString(), le.TimeStamp};
          listView1.Items.Add(new ListViewItem(cols));
       }
    }
    else
    {
        Debug.WriteLine("Error: " + ex.Message);
    }

    // Close the connection
    ftp1.Close();
}

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

ListEventArgs Members | Dart.PowerTCP.Ftp Namespace


ListEventArgs Members

ListEventArgs overview

Public Instance Properties

Exception | Gets any exception which occurred during the asynchronous operation.
Listing | Gets the Listing object received from the server.
State | Gets the object that was included as part of the associated method call.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

ListEventArgs Class | Dart.PowerTCP.Ftp Namespace


ListEventArgs Properties

The properties of the ListEventArgs class are listed below. For a complete list of ListEventArgs class members, see the ListEventArgs Members topic.

Public Instance Properties

Exception | Gets any exception which occurred during the asynchronous operation.
Listing | Gets the Listing object received from the server.
State | Gets the object that was included as part of the associated method call.

See Also

ListEventArgs Class | Dart.PowerTCP.Ftp Namespace


Exception Property

ListEventArgs.Exception Property

Gets any exception which occurred during the asynchronous operation.

[Visual Basic]
Public Property ReadOnly Exception As Exception
[C#]
public Exception Exception { get; }
[C++]
public: __property Exception* get_Exception();
[JScript]
public function get Exception() : Exception

Property Value

If any exception occurred during the asynchronous operation, this property will contain an Exception object describing the exception.

Remarks

Check this property to tell if an exception occurred during the asynchronous operation. If this property is null, no exception occurred.

The exception property is useful for checking exceptions and handling them appropriately. For example, if a bad command was sent to the server, a ProtocolException may be thrown. You could check this property to see if it was of type ProtocolException, than handle appropriately.

Example

The following example demonstrates using BeginList to retrieve a Listing asynchronously.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Get a listing for all text files in home/test. Upon completion the EndList
' event will fire, with the Listing passed in as an arg
 Ftp1.BeginList("/home/test/*.txt", True, Nothing)

' Because BeginList is asynchronous, this line will be immediately executed.
Debug.WriteLine("Retrieving Listing")

' When the BeginList operation has completed, the EndList Event will fire.
Private Sub Ftp1_EndList(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ListEventArgs) Handles Ftp1.EndList

   ' If an error occurred during the asynchronous method, it would be
   ' returned in the event. Be sure to check for it.
   if e.Exception Is Nothing Then

      ' Retrieve listing and display

      ' Begin setting up the ListView (listView1 is a standard ListView object) display

      ' Show gridlines.
      ListView1.GridLines = True

      ' Set View to Details
      ListView1.View = View.Details

      ' Add column headings for file name, size, and date.
      ListView1.Columns.Add("File Name", 100, HorizontalAlignment.Left)
      ListView1.Columns.Add("File Size", 100, HorizontalAlignment.Left)
      ListView1.Columns.Add("File Timestamp", 100, HorizontalAlignment.Left)

      ' Iterate through the listing, adding a row to the ListBox for each
      Dim le As Dart.PowerTCP.Ftp.ListEntry
      For Each le In e.Listing
         Dim cols() As String = {le.Name, le.Size.ToString(), le.TimeStamp}
         ListView1.Items.Add(New ListViewItem(cols))
      Next
  Else
     Debug.WriteLine(e.Exception.Message)
  End If

  ' Close the connection
  Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Get a listing for all text files in home/test. Upon completion the EndList
// event will fire, with the Listing passed in as an arg
ftp1.BeginList("/home/test/*.txt", true, null);

// Because BeginList is asynchronous, this line will be immediately executed.
Debug.WriteLine("Retrieving listing");

// When the BeginList operation has completed, the EndList Event will fire.

private void ftp1_EndList(object sender, Dart.PowerTCP.Ftp.ListEventArgs e)
{
    // If an error occurred during the asynchronous method, it would
    // be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
       // Retrieve listing and display

       // Begin setting up the ListView (listView1 is a standard ListView object) display

       // Show gridlines.
       listView1.GridLines = true;

       // Set View to Details
       listView1.View = View.Details;

       // Add column headings for file name, size, and date.
       listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
       listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
       listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

       // Iterate through the listing, adding a row to the ListBox for each
       foreach(Dart.PowerTCP.Ftp.ListEntry le in e.Listing)
       {
          string[] cols = {le.Name, le.Size.ToString(), le.TimeStamp};
          listView1.Items.Add(new ListViewItem(cols));
       }
    }
    else
    {
        Debug.WriteLine("Error: " + ex.Message);
    }

    // Close the connection
    ftp1.Close();
}

See Also

ListEventArgs Class | Dart.PowerTCP.Ftp Namespace


Listing Property

ListEventArgs.Listing Property

Gets the Listing object received from the server.

[Visual Basic]
Public Property ReadOnly Listing As Listing
[C#]
public Listing Listing { get; }
[C++]
public: __property Listing* get_Listing();
[JScript]
public function get Listing() : Listing

Property Value

A Listing object encapsulating an FTP listing.

Remarks

After successful completion of an asynchronous BeginList, the Listing property will contain a representation of the FTP listing. This representation will include an array of ListEntry objects, representing each file/directory retrieved by the List method, and a Format property, containing the perceived format of the listing.

Example

The following example demonstrates using BeginList to retrieve a Listing asynchronously.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Get a listing for all text files in home/test. Upon completion the EndList
' event will fire, with the Listing passed in as an arg
 Ftp1.BeginList("/home/test/*.txt", True, Nothing)

' Because BeginList is asynchronous, this line will be immediately executed.
Debug.WriteLine("Retrieving Listing")

' When the BeginList operation has completed, the EndList Event will fire.
Private Sub Ftp1_EndList(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ListEventArgs) Handles Ftp1.EndList

   ' If an error occurred during the asynchronous method, it would be
   ' returned in the event. Be sure to check for it.
   if e.Exception Is Nothing Then

      ' Retrieve listing and display

      ' Begin setting up the ListView (listView1 is a standard ListView object) display

      ' Show gridlines.
      ListView1.GridLines = True

      ' Set View to Details
      ListView1.View = View.Details

      ' Add column headings for file name, size, and date.
      ListView1.Columns.Add("File Name", 100, HorizontalAlignment.Left)
      ListView1.Columns.Add("File Size", 100, HorizontalAlignment.Left)
      ListView1.Columns.Add("File Timestamp", 100, HorizontalAlignment.Left)

      ' Iterate through the listing, adding a row to the ListBox for each
      Dim le As Dart.PowerTCP.Ftp.ListEntry
      For Each le In e.Listing
         Dim cols() As String = {le.Name, le.Size.ToString(), le.TimeStamp}
         ListView1.Items.Add(New ListViewItem(cols))
      Next
  Else
     Debug.WriteLine(e.Exception.Message)
  End If

  ' Close the connection
  Ftp1.Close()
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Get a listing for all text files in home/test. Upon completion the EndList
// event will fire, with the Listing passed in as an arg
ftp1.BeginList("/home/test/*.txt", true, null);

// Because BeginList is asynchronous, this line will be immediately executed.
Debug.WriteLine("Retrieving listing");

// When the BeginList operation has completed, the EndList Event will fire.

private void ftp1_EndList(object sender, Dart.PowerTCP.Ftp.ListEventArgs e)
{
    // If an error occurred during the asynchronous method, it would
    // be returned in the event. Be sure to check for it.
    if(e.Exception == null)
    {
       // Retrieve listing and display

       // Begin setting up the ListView (listView1 is a standard ListView object) display

       // Show gridlines.
       listView1.GridLines = true;

       // Set View to Details
       listView1.View = View.Details;

       // Add column headings for file name, size, and date.
       listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
       listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
       listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

       // Iterate through the listing, adding a row to the ListBox for each
       foreach(Dart.PowerTCP.Ftp.ListEntry le in e.Listing)
       {
          string[] cols = {le.Name, le.Size.ToString(), le.TimeStamp};
          listView1.Items.Add(new ListViewItem(cols));
       }
    }
    else
    {
        Debug.WriteLine("Error: " + ex.Message);
    }

    // Close the connection
    ftp1.Close();
}

See Also

ListEventArgs Class | Dart.PowerTCP.Ftp Namespace


State Property

ListEventArgs.State Property

Gets the object that was included as part of the associated method call.

[Visual Basic]
Public Property ReadOnly State As Object
[C#]
public object State { get; }
[C++]
public: __property Object* get_State();
[JScript]
public function get State() : Object

Property Value

An object containing data passed into the calling asynchronous method.

Remarks

The EndEventArgs.State property can be used in the calling asynchronous method to make data accessible to the handling event.

This property is useful for making data accessible to the handling event. Since asynchronous methods are "disconnected" (meaning that when one is called, it executes on it's own and returns in the event handler) data that you were using in the code that called the asynchronous method may not be available in the event handler. Simply pass this data in as state when calling the asynchronous method (usually a BeginXXX method) and it is available in the event handler. If you do not wish to make an object accessible in the EndXXX event, simple pass in null as state.

See Also

ListEventArgs Class | Dart.PowerTCP.Ftp Namespace


ListEventHandler Delegate

Represents the method (event handler) that will be raised when the BeginList operation completes.

[Visual Basic]
Public Delegate Function Sub  ListEventHandler( _
   ByVal sender As Object, _
   ByVal e As ListEventArgs _
)
[C#]
public delegate void ListEventHandler(
   object sender,
   ListEventArgs e
)
[C++]
public __gc __delegate void ListEventHandler(
   Object* sender,
   ListEventArgs* e
)

[JScript] In JScript, you can use the delegates defined by a type, but you cannot define your own.

Parameters

sender
The source of the event.
e
A ListEventArgs object that contains the event data.

Remarks

As Microsoft describes in their MSDN documentation, the event model in the .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed:

  • A class that holds the event data. This class must derive from the base class EventArgs.
  • A delegate that points to a method that provides the response to the event.
When using the BeginList method, the class that holds the event data is the ListEventArgs class. A method must be created with the same signature as the delegate. If you are working within the Visual Studio.NET environment, this can be automatically done for you. See the "Using Events In PowerTCP" topic for more information. If you are not working within the Visual Studio.NET environment, you must do this yourself. In this example that would mean a method would have to be defined to accept two arguments (an object and a ListEventArgs) and return void. Once this has been done, the delegate must be "connected" to the handling event. This is done by adding an instance of the delegate to the event (see examples below).

For more information about event handler delegates, see the "Using Events In PowerTCP" topic.

Example

The following example demonstrates how to assign an event handler to an event.

[Visual Basic]
' *** EndList Event ***

' You can either use the AddHandler statement to associate an event with an event handler in your init code
AddHandler Ftp1.EndList, New Dart.PowerTCP.Ftp.ListEventHandler(AddressOf Ftp1_EndList)

' Or you can use the Handles keyword to associate an event handler with an event
Private Sub Ftp1_EndList(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.ListEventArgs) Handles Ftp1.EndList

[C#]
// EndList event
this.ftp1.EndList += new Dart.PowerTCP.Ftp.ListEventHandler(this.ftp1_EndList);

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


Listing Class

Represents the textual listing received from an FTP server.

For a list of all members of this type, see Listing Members.

System.Object
System.Collections.ArrayList
Dart.PowerTCP.Ftp.Listing

[Visual Basic]
Public Class Listing
    Inherits ArrayList
[C#]
public class Listing : ArrayList
[C++]
public __gc class Listing : public ArrayList
[JScript]
public class Listing extends ArrayList

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

The List and BeginList methods request a listing from the FTP server. When this listing is returned, it is encapsulated by the Listing object (representing the entire listing) which contains ListEntry objects (representing an individual list entry, such as a file). For example, the following code,

Dart.PowerTCP.Listing myList =  ftp1.List("*", true);

would return a listing that would be encapsulated by the Listing object myList. This object would be made up of many ListEntry objects describing each individual file/directory. For example, perhaps the raw listing returned from the above method call was as follows:

-rw-r--r--   1 test     users         240 Aug 10 09:23 file1.txt
-rw-r--r--   1 test     users         255 Aug 10 09:23 file2.txt

This would return a Listing object with two ListEntry objects. The values would look like the following:

Property | Value
myList.Format | UNIX
myList[0].Name | file1.txt
myList[0].Permissions | -rw-r--r--
etc... |

The above table shows the Ftp component was able to detect the listing format, which is contained in the Format property.

Example

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Retrieve file list. Listing details will be contained in the Listing Object
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Begin setting up the ListView diplay
' Show gridlines.
ListView1.GridLines = True

' Set View to Details
ListView1.View = View.Details

' Add column headings for file name, size, and date.
ListView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left)
ListView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left)

' Iterate through the listing, adding a row to the ListBox for each
Dim le As Dart.PowerTCP.Ftp.ListEntry
For Each le In list

   ' Display files only
   If le.Type = Dart.PowerTCP.Ftp.EntryType.File Then
      Dim cols() As String = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp}
      ListView1.Items.Add(New ListViewItem(cols))
   End If
Next

' Close the connection
Ftp1.Close()

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Retrieve file list. Listing details will be contained in the Listing Object
Dart.PowerTCP.Ftp.Listing list = ftp1.List("*", true);

// Begin setting up the ListView diplay

// Show gridlines.
listView1.GridLines = true;

// Set View to Details
listView1.View = View.Details;

// Add column headings for file name, size, and date.
listView1.Columns.Add("File Name", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Size", 100, System.Windows.Forms.HorizontalAlignment.Left);
listView1.Columns.Add("File Timestamp", 100, System.Windows.Forms.HorizontalAlignment.Left);

// Iterate through the listing, adding a row to the ListBox for each
foreach(Dart.PowerTCP.Ftp.ListEntry le in list)
{
    // Display files only
    if(le.Type == Dart.PowerTCP.Ftp.EntryType.File)
    {
        string[] cols = {le.Path + le.Name, le.Size.ToString(), le.TimeStamp};
        listView1.Items.Add(new ListViewItem(cols));
    }
}

// Close the connection
ftp1.Close();

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Listing Members | Dart.PowerTCP.Ftp Namespace


Listing Members

Listing overview

Public Instance Constructors

Listing Constructor Creates a Listing instance and populates it with the raw text listing.

Public Instance Properties

Capacity (inherited from ArrayList) | Gets or sets the number of elements that the ArrayList can contain.
Count (inherited from ArrayList) | Gets the number of elements actually contained in the ArrayList.
Format | Gets the format of the listing: ListingFormat.UNIX, ListingFormat.DOS or ListingFormat.Unknown.
IsFixedSize (inherited from ArrayList) | Gets a value indicating whether the ArrayList has a fixed size.
IsReadOnly (inherited from ArrayList) | Gets a value indicating whether the ArrayList is read-only.
IsSynchronized (inherited from ArrayList) | Gets a value indicating whether access to the ArrayList is synchronized (thread-safe).
Item | Overloaded. Gets or sets the element at the specified index.
SyncRoot (inherited from ArrayList) | Gets an object that can be used to synchronize access to the ArrayList.

Public Instance Methods

Add (inherited from ArrayList) | Overloaded. Adds an object to the end of the ArrayList.
Add | Overloaded. Add an object to the end of the collection.
AddRange (inherited from ArrayList) | Adds the elements of an ICollection to the end of the ArrayList.
BinarySearch (inherited from ArrayList) | Overloaded. Searches the entire sorted ArrayList for an element using the specified comparer and returns the zero-based index of the element.
Clear (inherited from ArrayList) | Removes all elements from the ArrayList.
Clone (inherited from ArrayList) | Creates a shallow copy of the ArrayList.
Contains (inherited from ArrayList) | Overloaded. Determines whether an element is in the ArrayList.
Contains | Overloaded. Determines whether an element is in the collection.
CopyTo (inherited from ArrayList) | Overloaded. Copies the entire ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array.
CopyTo | Overloaded. Copies the entire collection to a compatible one-dimensional Array, starting at the specified index of the target array.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetEnumerator (inherited from ArrayList) | Overloaded. Returns an enumerator for the entire ArrayList.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetRange (inherited from ArrayList) | Returns an ArrayList which represents a subset of the elements in the source ArrayList.
GetType (inherited from Object) | Gets the Type of the current instance.
IndexOf (inherited from ArrayList) | Overloaded. Searches for the specified Object and returns the zero-based index of the first occurrence within the entire ArrayList.
IndexOf | Overloaded. Searches for the specified value and returns the zero-based index of the first occurrence within the entire collection.
Insert (inherited from ArrayList) | Overloaded. Inserts an element into the ArrayList at the specified index.
Insert | Overloaded. Inserts an element into the collection at the specified index.
InsertRange (inherited from ArrayList) | Inserts the elements of a collection into the ArrayList at the specified index.
LastIndexOf (inherited from ArrayList) | Overloaded. Searches for the specified Object and returns the zero-based index of the last occurrence within the section of the ArrayList that contains the specified number of elements and ends at the specified index.
Remove (inherited from ArrayList) | Overloaded. Removes the first occurrence of a specific object from the ArrayList.
Remove | Overloaded. Removes the first occurrence of a specific object from the collection.
RemoveAt (inherited from ArrayList) | Removes the element at the specified index of the ArrayList.
RemoveRange (inherited from ArrayList) | Removes a range of elements from the ArrayList.
Reverse (inherited from ArrayList) | Overloaded. Reverses the order of the elements in the specified range.
SetRange (inherited from ArrayList) | Copies the elements of a collection over a range of elements in the ArrayList.
Sort (inherited from ArrayList) | Overloaded. Sorts the elements in a section of ArrayList using the specified comparer.
ToArray (inherited from ArrayList) | Overloaded. Copies the elements of the ArrayList to a new array of the specified type.
ToString | Overridden. Gets the raw listing test used to initialize the Listing object.
TrimToSize (inherited from ArrayList) | Sets the capacity to the actual number of elements in the ArrayList.

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace


Listing Constructor

Creates a Listing instance and populates it with the raw text listing.

[Visual Basic]
Public Sub New( _
   ByVal text As String, _
   ByVal full As Boolean _
)
[C#]
public Listing(
   string text,
   bool full
);
[C++]
public: Listing(
   String* text,
   bool full
);
[JScript]
public function Listing(
   String text,
   bool full
);

Parameters

text
Raw text listing.
full
True for a full listing, and false for a named list (NLST).

Remarks

The default constructor creates a Listing object.

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace


Listing Properties

The properties of the Listing class are listed below. For a complete list of Listing class members, see the Listing Members topic.

Public Instance Properties

Capacity (inherited from ArrayList) | Gets or sets the number of elements that the ArrayList can contain.
Count (inherited from ArrayList) | Gets the number of elements actually contained in the ArrayList.
Format | Gets the format of the listing: ListingFormat.UNIX, ListingFormat.DOS or ListingFormat.Unknown.
IsFixedSize (inherited from ArrayList) | Gets a value indicating whether the ArrayList has a fixed size.
IsReadOnly (inherited from ArrayList) | Gets a value indicating whether the ArrayList is read-only.
IsSynchronized (inherited from ArrayList) | Gets a value indicating whether access to the ArrayList is synchronized (thread-safe).
Item | Overloaded. Gets or sets the element at the specified index.
SyncRoot (inherited from ArrayList) | Gets an object that can be used to synchronize access to the ArrayList.

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace


Format Property

Listing.Format Property

Gets the format of the listing: ListingFormat.UNIX, ListingFormat.DOS or ListingFormat.Unknown.

[Visual Basic]
Public Property ReadOnly Format As ListingFormat
[C#]
public ListingFormat Format { get; }
[C++]
public: __property ListingFormat get_Format();
[JScript]
public function get Format() : ListingFormat

Property Value

One of the ListingFormat values.

Remarks

When a Listing object is created, the format of the listing is automatically detected. If the format is unable to be detected, ListingFormat.Unknown is returned.

The Listing.Text property is useful for seeing the perceived listing type, therefore being able to handle the listing accordingly. It is also useful for dealing with servers that return a "proprietary" listing. For example, if the server may return a UNIX listing. This would look something like:

r-xr-xr-x   1 owner    group               20 Jan 10  2002 file1.txt

It also may return a DOS listing which would look something like:

01-10-02  10:18AM                    20 file1.txt

In either of these cases, the format would be detected and Format would be set appropriately. However, if the listing returned was a proprietary listing such as:

file1.txt   Jan-10-2002   20

The Ftp component would be unable to detect the type. You would have to get the raw text (using ListEntry.Text), and parse it yourself.

Example

The following example demonstrates parsing a listing. This example demonstrates checking the format, and parsing if unknown.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Retrieve file list. Listing details will be contained in the Listing Object
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Check to see if the server returned an Unknown listing
If list.Format = Dart.PowerTCP.Ftp.ListingFormat.Unknown Then

   ' In this example, the server is returning a proprietary listing which looks like:
   '            myfile.txt     158     01-11-02     11:55

   ' Create a pattern to use as a RegularExpression which matches the above listing format
   Dim pattern As String
   pattern = "(?<filename>\S+)\s+(?<filesize>\S+)\s+(?<filedate>\S+)\s+(?<filetime>\S+)"

   ' Create new Regex object
   Dim regex As New System.Text.RegularExpressions.Regex(pattern)

   ' Iterate through ListEntries
   Dim l As Dart.PowerTCP.Ftp.ListEntry
   For Each l In list

      ' Get raw listing
      Dim raw As String = l.Text

      ' Attempt to match regular expression
      Dim match As System.Text.RegularExpressions.Match
      match = regex.Match(raw)

      ' Extract groupnames from Groups collection
      Dim filename As String = match.Groups["filename"].Value
      Dim filesize As String = match.Groups["filesize"].Value
      Dim filedate As String = match.Groups["filedate"].Value
      Dim filetime As String = match.Groups["filetime"].Value

      ' Display result
      Debug.WriteLine("Filename: " + filename)
      Debug.WriteLine("Filesize: " + filesize)
      Debug.WriteLine("Filedate: " + filedate)
      Debug.WriteLine("Filetime: " + filetime)
   Next

   'Close the connection
   Ftp1.Close()
End If

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// In this example, the server is returning a proprietary listing which looks like:
//            myfile.txt     158     01-11-02     11:55

// Create a pattern to use as a RegularExpression which matches the above listing format
string ppattern = @"(?<filename>\S+)\s+(?<filesize>\S+)\s+(?<filedate>\S+)\s+(?<filetime>\S+)";

// Retrieve file list. Listing details will be contained in the Listing Object
Dart.PowerTCP.Ftp.Listing list = ftp1.List("*", true);

// Check to see if the server returned an Unknown listing format
if(list.Format == Dart.PowerTCP.Ftp.ListingFormat.Unknown)
{
    // Create new Regex object
    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern);

    // Iterate through ListEntries
    foreach(Dart.PowerTCP.Ftp.ListEntry l in list)
    {
        // Get raw listing
        string raw = l.Text;

        // Attempt to match regular expression
        System.Text.RegularExpressions.Match match = regex.Match(raw);

        // Extract groupnames from Groups collection
        string filename = match.Groups["filename"].Value;
        string filesize = match.Groups["filesize"].Value;
        string filedate = match.Groups["filedate"].Value;
        string filetime = match.Groups["filetime"].Value;

        // Display result
        Debug.WriteLine("Filename: " + filename);
        Debug.WriteLine("Filesize: " + filesize);
        Debug.WriteLine("Filedate: " + filedate);
        Debug.WriteLine("Filetime: " + filetime);
    }

    // Close the connection
    ftp1.Close();
}

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace


Item Property

Listing.Item Property

Gets or sets the element at the specified index.

[C#] In C#, this property is the indexer for the Listing class.

[Visual Basic]
Public Default Property Item( _
   ByVal index As Integer _
) As ListEntry
[C#]
public ListEntry this[
   int index
] { get; set; }
[C++]
public: __property ListEntry* get_Item(
   int index
);
public: __property void set_Item(
   int index,
   ListEntry* newValue
);
[JScript]
returnValue = ListingObject.Item( index );
ListingObject.Item( index ) = newValue;
-or-
returnValue = ListingObject( index );
ListingObject( index ) = newValue;

[JScript] In JScript, you can use the default indexed properties defined by a type, but you cannot explicitly define your own. However, specifying the expando attribute on a class automatically provides a default indexed property whose type is Object and whose index type is String.

Parameters

index
The zero-based index of the element to get or set.

Property Value

The element at the specified index.

Remarks

This property provides the ability to access a specific element in the collection by using the following syntax:

myCollection[Index]

Note, intellisense may not work on members of objects referenced by using this indexer. If you would like intellisense to work, get the object referenced by the indexer into it's own variable.

Exceptions

Exception Type | Condition
ArgumentOutOfRangeException | Index is less than zero. -or- Index is equal to or greater than Count.

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace


Listing Methods

The methods of the Listing class are listed below. For a complete list of Listing class members, see the Listing Members topic.

Public Instance Methods

Add (inherited from ArrayList) | Overloaded. Adds an object to the end of the ArrayList.
Add | Overloaded. Add an object to the end of the collection.
AddRange (inherited from ArrayList) | Adds the elements of an ICollection to the end of the ArrayList.
BinarySearch (inherited from ArrayList) | Overloaded. Searches the entire sorted ArrayList for an element using the specified comparer and returns the zero-based index of the element.
Clear (inherited from ArrayList) | Removes all elements from the ArrayList.
Clone (inherited from ArrayList) | Creates a shallow copy of the ArrayList.
Contains (inherited from ArrayList) | Overloaded. Determines whether an element is in the ArrayList.
Contains | Overloaded. Determines whether an element is in the collection.
CopyTo (inherited from ArrayList) | Overloaded. Copies the entire ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array.
CopyTo | Overloaded. Copies the entire collection to a compatible one-dimensional Array, starting at the specified index of the target array.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetEnumerator (inherited from ArrayList) | Overloaded. Returns an enumerator for the entire ArrayList.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetRange (inherited from ArrayList) | Returns an ArrayList which represents a subset of the elements in the source ArrayList.
GetType (inherited from Object) | Gets the Type of the current instance.
IndexOf (inherited from ArrayList) | Overloaded. Searches for the specified Object and returns the zero-based index of the first occurrence within the entire ArrayList.
IndexOf | Overloaded. Searches for the specified value and returns the zero-based index of the first occurrence within the entire collection.
Insert (inherited from ArrayList) | Overloaded. Inserts an element into the ArrayList at the specified index.
Insert | Overloaded. Inserts an element into the collection at the specified index.
InsertRange (inherited from ArrayList) | Inserts the elements of a collection into the ArrayList at the specified index.
LastIndexOf (inherited from ArrayList) | Overloaded. Searches for the specified Object and returns the zero-based index of the last occurrence within the section of the ArrayList that contains the specified number of elements and ends at the specified index.
Remove (inherited from ArrayList) | Overloaded. Removes the first occurrence of a specific object from the ArrayList.
Remove | Overloaded. Removes the first occurrence of a specific object from the collection.
RemoveAt (inherited from ArrayList) | Removes the element at the specified index of the ArrayList.
RemoveRange (inherited from ArrayList) | Removes a range of elements from the ArrayList.
Reverse (inherited from ArrayList) | Overloaded. Reverses the order of the elements in the specified range.
SetRange (inherited from ArrayList) | Copies the elements of a collection over a range of elements in the ArrayList.
Sort (inherited from ArrayList) | Overloaded. Sorts the elements in a section of ArrayList using the specified comparer.
ToArray (inherited from ArrayList) | Overloaded. Copies the elements of the ArrayList to a new array of the specified type.
ToString | Overridden. Gets the raw listing test used to initialize the Listing object.
TrimToSize (inherited from ArrayList) | Sets the capacity to the actual number of elements in the ArrayList.

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace


Add Method

Listing.Add Method

Add an object to the end of the collection.

Overload List

Add an object to the end of the collection.

[Visual Basic] Public Function Add(ByVal ListEntry) As Integer
[C#] public int Add(ListEntry);
[C++] public: int Add(ListEntry*);
[JScript] public function Add(ListEntry): int;

Adds an object to the end of the ArrayList.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Function Add(ByVal Object) _ Implements IList.Add As Integer
[C#] public virtual int Add(object);
[C++] public: virtual int Add(Object*);
[JScript] public virtual function Add(Object): int;

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace


Add Method (ListEntry)

Listing.Add Method (ListEntry)

Add an object to the end of the collection.

[Visual Basic]
Public Function Add( _
   ByVal value As ListEntry _
) As Integer
[C#]
public int Add(
   ListEntry value
);
[C++]
public: int Add(
   ListEntry* value
);
[JScript]
public function Add(
   ListEntry value
): int;

Parameters

value
The object to add to the end of the collection.

Remarks

If Count already equals Capacity, the capacity of the list is doubled by automatically reallocating the internal array and copying the existing elements to the new array before the new element is added.

If Count is less than Capacity, this method is an O(1) operation. If the capacity needs to be increased to accommodate the new element, this method becomes an O(n) operation, where n is Count.

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace | Listing.Add Overload List


Contains Method

Listing.Contains Method

Determines whether an element is in the collection.

Overload List

Determines whether an element is in the collection.

[Visual Basic] Public Function Contains(ByVal ListEntry) As Boolean
[C#] public bool Contains(ListEntry);
[C++] public: bool Contains(ListEntry*);
[JScript] public function Contains(ListEntry): bool;

Determines whether an element is in the ArrayList.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Function Contains(ByVal Object) _ Implements IList.Contains As Boolean
[C#] public virtual bool Contains(object);
[C++] public: virtual bool Contains(Object*);
[JScript] public virtual function Contains(Object): bool;

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace


Contains Method (ListEntry)

Listing.Contains Method (ListEntry)

Determines whether an element is in the collection.

[Visual Basic]
Public Function Contains( _
   ByVal value As ListEntry _
) As Boolean
[C#]
public bool Contains(
   ListEntry value
);
[C++]
public: bool Contains(
   ListEntry* value
);
[JScript]
public function Contains(
   ListEntry value
): bool;

Parameters

value
The Object to locate in the collection. The element to locate can be a null reference (Nothing in Visual Basic).

Return Value

true if item is found in the collection; otherwise, false.

Remarks

This method performs a linear search; therefore, the average execution time is proportional to Count. That is, this method is an O(n) operation, where n is Count.

This method determines equality by calling Object.Equals.

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace | Listing.Contains Overload List


CopyTo Method

Listing.CopyTo Method

Copies the entire collection to a compatible one-dimensional Array, starting at the specified index of the target array.

Overload List

Copies the entire collection to a compatible one-dimensional Array, starting at the specified index of the target array.

[Visual Basic] Public Sub CopyTo(ByVal ListEntry(),ByVal Integer)
[C#] public void CopyTo(ListEntry[],int);
[C++] public: void CopyTo(ListEntry* __gc[],int);
[JScript] public function CopyTo(ListEntry[],int);

Copies the entire ArrayList to a compatible one-dimensional Array, starting at the beginning of the target array.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Sub CopyTo(ByVal Array)
[C#] public virtual void CopyTo(Array);
[C++] public: virtual void CopyTo(Array*);
[JScript] public virtual function CopyTo(Array);

Copies the entire ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Sub CopyTo(ByVal Array,ByVal Integer) _ Implements ICollection.CopyTo
[C#] public virtual void CopyTo(Array,int);
[C++] public: virtual void CopyTo(Array*,int);
[JScript] public virtual function CopyTo(Array,int);

Copies a range of elements from the ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Sub CopyTo(ByVal Integer,ByVal Array,ByVal Integer,ByVal Integer)
[C#] public virtual void CopyTo(int,Array,int,int);
[C++] public: virtual void CopyTo(int,Array*,int,int);
[JScript] public virtual function CopyTo(int,Array,int,int);

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace


CopyTo Method (ListEntry[], Int32)

Listing.CopyTo Method (ListEntry[], Int32)

Copies the entire collection to a compatible one-dimensional Array, starting at the specified index of the target array.

[Visual Basic]
Public Sub CopyTo( _
   ByVal array As ListEntry(), _
   ByVal index As Integer _
)
[C#]
public void CopyTo(
   ListEntry[] array,
   int index
);
[C++]
public: void CopyTo(
   ListEntry* array __gc[],
   int index
);
[JScript]
public function CopyTo(
   ListEntry[] array,
   int index
);

Parameters

array
The one-dimensional Array that is the destination of the elements copied from ArrayList. The Array must have zero-based indexing.
index
The zero-based index in array at which copying begins.

Remarks

The specified array must be of a compatible type.

This method uses Array.Copy to copy the elements.

Exceptions

Exception Type | Condition
ArgumentNullException | array is a null reference (Nothing in Visual Basic).
ArgumentException | array is multidimensional.
InvalidCastException | The type of the source ArrayList cannot be cast automatically to the type of the destination array.

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace | Listing.CopyTo Overload List


IndexOf Method

Listing.IndexOf Method

Searches for the specified value and returns the zero-based index of the first occurrence within the entire collection.

Overload List

Searches for the specified value and returns the zero-based index of the first occurrence within the entire collection.

[Visual Basic] Public Function IndexOf(ByVal ListEntry) As Integer
[C#] public int IndexOf(ListEntry);
[C++] public: int IndexOf(ListEntry*);
[JScript] public function IndexOf(ListEntry): int;

Searches for the specified Object and returns the zero-based index of the first occurrence within the entire ArrayList.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Function IndexOf(ByVal Object) _ Implements IList.IndexOf As Integer
[C#] public virtual int IndexOf(object);
[C++] public: virtual int IndexOf(Object*);
[JScript] public virtual function IndexOf(Object): int;

Searches for the specified Object and returns the zero-based index of the first occurrence within the section of the ArrayList that extends from the specified index to the last element.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Function IndexOf(ByVal Object,ByVal Integer) As Integer
[C#] public virtual int IndexOf(object,int);
[C++] public: virtual int IndexOf(Object*,int);
[JScript] public virtual function IndexOf(Object,int): int;

Searches for the specified Object and returns the zero-based index of the first occurrence within the section of the ArrayList that starts at the specified index and contains the specified number of elements.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Function IndexOf(ByVal Object,ByVal Integer,ByVal Integer) As Integer
[C#] public virtual int IndexOf(object,int,int);
[C++] public: virtual int IndexOf(Object*,int,int);
[JScript] public virtual function IndexOf(Object,int,int): int;

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace


IndexOf Method (ListEntry)

Listing.IndexOf Method (ListEntry)

Searches for the specified value and returns the zero-based index of the first occurrence within the entire collection.

[Visual Basic]
Public Function IndexOf( _
   ByVal value As ListEntry _
) As Integer
[C#]
public int IndexOf(
   ListEntry value
);
[C++]
public: int IndexOf(
   ListEntry* value
);
[JScript]
public function IndexOf(
   ListEntry value
): int;

Parameters

value
The Object to locate in the collection.

Return Value

The zero-based index of the first occurrence of value within the entire collection, if found; otherwise, -1.

Remarks

The collection is searched forward starting at the first element and ending at the last element.

This method performs a linear search. On average, this is an O(n/2) operation, where n is Count. The longest search is an O(n) operation.

This method determines equality by calling Object.Equals.

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace | Listing.IndexOf Overload List


Insert Method

Listing.Insert Method

Inserts an element into the collection at the specified index.

Overload List

Inserts an element into the collection at the specified index.

[Visual Basic] Public Sub Insert(ByVal Integer,ByVal ListEntry)
[C#] public void Insert(int,ListEntry);
[C++] public: void Insert(int,ListEntry*);
[JScript] public function Insert(int,ListEntry);

Inserts an element into the ArrayList at the specified index.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Sub Insert(ByVal Integer,ByVal Object) _ Implements IList.Insert
[C#] public virtual void Insert(int,object);
[C++] public: virtual void Insert(int,Object*);
[JScript] public virtual function Insert(int,Object);

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace


Insert Method (Int32, ListEntry)

Listing.Insert Method (Int32, ListEntry)

Inserts an element into the collection at the specified index.

[Visual Basic]
Public Sub Insert( _
   ByVal index As Integer, _
   ByVal value As ListEntry _
)
[C#]
public void Insert(
   int index,
   ListEntry value
);
[C++]
public: void Insert(
   int index,
   ListEntry* value
);
[JScript]
public function Insert(
   int index,
   ListEntry value
);

Parameters

index
The zero-based index at which value should be inserted.
value
The Object to insert.

Remarks

If Count already equals Capacity, the capacity of the list is doubled by automatically reallocating the internal array before the new element is inserted.

If index is equal to Count, value is added to the end of ArrayList.

In collections of contiguous elements, such as lists, the elements that follow the insertion point move down to accommodate the new element. If the collection is indexed, the indexes of the elements that are moved are also updated. This behavior does not apply to collections where elements are conceptually grouped into buckets, such as a hashtable.

Exceptions

Exception Type | Condition
ArgumentOutOfRangeException | index is less than zero. -or- index is greater than Count.
NotSupportedException | The ArrayList is read-only. -or- The ArrayList has a fixed size.

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace | Listing.Insert Overload List


Remove Method

Listing.Remove Method

Removes the first occurrence of a specific object from the collection.

Overload List

Removes the first occurrence of a specific object from the collection.

[Visual Basic] Public Sub Remove(ByVal ListEntry)
[C#] public void Remove(ListEntry);
[C++] public: void Remove(ListEntry*);
[JScript] public function Remove(ListEntry);

Removes the first occurrence of a specific object from the ArrayList.
Inherited from ArrayList.

[Visual Basic] Overridable OverloadsPublic Sub Remove(ByVal Object) _ Implements IList.Remove
[C#] public virtual void Remove(object);
[C++] public: virtual void Remove(Object*);
[JScript] public virtual function Remove(Object);

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace


Remove Method (ListEntry)

Listing.Remove Method (ListEntry)

Removes the first occurrence of a specific object from the collection.

[Visual Basic]
Public Sub Remove( _
   ByVal value As ListEntry _
)
[C#]
public void Remove(
   ListEntry value
);
[C++]
public: void Remove(
   ListEntry* value
);
[JScript]
public function Remove(
   ListEntry value
);

Parameters

value
The Object to remove from the collection.

Remarks

This method performs a linear search; therefore, the average execution time is proportional to Count. That is, this method is an O(n) operation, where n is Count.

This method determines equality by calling Object.Equals.

In collections of contiguous elements, such as lists, the elements that follow the removed element move up to occupy the vacated spot. If the collection is indexed, the indexes of the elements that are moved are also updated. This behavior does not apply to collections where elements are conceptually grouped into buckets, such as a hashtable.

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace | Listing.Remove Overload List


ToString Method

Listing.ToString Method

Gets the raw listing test used to initialize the Listing object.

[Visual Basic]
Overrides Public Function ToString() As String
[C#]
public override string ToString();
[C++]
public: String* ToString();
[JScript]
public override function ToString(): String;

Remarks

If you wish to access the raw text of each individual list entry, use the Text property. If you would like access to the raw text of the entire listing, use this property.

See Also

Listing Class | Dart.PowerTCP.Ftp Namespace


ListingFormat Enumeration

Enumerates the perceived format of the listing.

[Visual Basic]
Public Enum ListingFormat
[C#]
public enum ListingFormat
[C++]
public __value enum ListingFormat
[JScript]
public enum ListingFormat

Remarks

This enumeration is used by the Format property.

The Ftp component will automatically attempt to detect the format (UNIX or DOS) of the listing and display the appropriate type in the Format property. If the listing type is unable to be discerned, this property will be Unknown. If the ListingFormat used is unknown, you can still access the raw listing through the ToString method (for the entire listing) or the Text property (for the raw text of a single ListEntry), and parse it yourself.

Example

The following example demonstrates parsing a listing. This example demonstrates checking the format, and parsing if unknown.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Retrieve file list. Listing details will be contained in the Listing Object
Dim list As Dart.PowerTCP.Ftp.Listing
list = Ftp1.List("*", True)

' Check to see if the server returned an Unknown listing
If list.Format = Dart.PowerTCP.Ftp.ListingFormat.Unknown Then

   ' In this example, the server is returning a proprietary listing which looks like:
   '            myfile.txt     158     01-11-02     11:55

   ' Create a pattern to use as a RegularExpression which matches the above listing format
   Dim pattern As String
   pattern = "(?<filename>\S+)\s+(?<filesize>\S+)\s+(?<filedate>\S+)\s+(?<filetime>\S+)"

   ' Create new Regex object
   Dim regex As New System.Text.RegularExpressions.Regex(pattern)

   ' Iterate through ListEntries
   Dim l As Dart.PowerTCP.Ftp.ListEntry
   For Each l In list

      ' Get raw listing
      Dim raw As String = l.Text

      ' Attempt to match regular expression
      Dim match As System.Text.RegularExpressions.Match
      match = regex.Match(raw)

      ' Extract groupnames from Groups collection
      Dim filename As String = match.Groups["filename"].Value
      Dim filesize As String = match.Groups["filesize"].Value
      Dim filedate As String = match.Groups["filedate"].Value
      Dim filetime As String = match.Groups["filetime"].Value

      ' Display result
      Debug.WriteLine("Filename: " + filename)
      Debug.WriteLine("Filesize: " + filesize)
      Debug.WriteLine("Filedate: " + filedate)
      Debug.WriteLine("Filetime: " + filetime)
   Next

   'Close the connection
   Ftp1.Close()
End If

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// In this example, the server is returning a proprietary listing which looks like:
//            myfile.txt     158     01-11-02     11:55

// Create a pattern to use as a RegularExpression which matches the above listing format
string ppattern = @"(?<filename>\S+)\s+(?<filesize>\S+)\s+(?<filedate>\S+)\s+(?<filetime>\S+)";

// Retrieve file list. Listing details will be contained in the Listing Object
Dart.PowerTCP.Ftp.Listing list = ftp1.List("*", true);

// Check to see if the server returned an Unknown listing format
if(list.Format == Dart.PowerTCP.Ftp.ListingFormat.Unknown)
{
    // Create new Regex object
    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern);

    // Iterate through ListEntries
    foreach(Dart.PowerTCP.Ftp.ListEntry l in list)
    {
        // Get raw listing
        string raw = l.Text;

        // Attempt to match regular expression
        System.Text.RegularExpressions.Match match = regex.Match(raw);

        // Extract groupnames from Groups collection
        string filename = match.Groups["filename"].Value;
        string filesize = match.Groups["filesize"].Value;
        string filedate = match.Groups["filedate"].Value;
        string filetime = match.Groups["filetime"].Value;

        // Display result
        Debug.WriteLine("Filename: " + filename);
        Debug.WriteLine("Filesize: " + filesize);
        Debug.WriteLine("Filedate: " + filedate);
        Debug.WriteLine("Filetime: " + filetime);
    }

    // Close the connection
    ftp1.Close();
}

Members

Member Name | Description
UNIX | The perceived listing format is UNIX. UNIX is used by most UNIX-based operating systems.
DOS | The perceived listing format is DOS. Microsoft's server can be configured to provide a DOS-formatted listing.
Unknown | Listing format is unable to be determined. If the listing format cannot be determined, you can parse it by using the Listing.Text property.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


PipeStream Class

Represents a stream that wraps an internal stream.

For a list of all members of this type, see PipeStream Members.

System.Object
System.MarshalByRefObject
System.IO.Stream
Dart.PowerTCP.Ftp.EnhancedStream
Dart.PowerTCP.Ftp.PipeStream
Dart.PowerTCP.Ftp.SegmentedStream

[Visual Basic]
Public Class PipeStream
    Inherits EnhancedStream
[C#]
public class PipeStream : EnhancedStream
[C++]
public __gc class PipeStream : public EnhancedStream
[JScript]
public class PipeStream extends EnhancedStream

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

PipeStream wraps a stream that is filtered or encoded/decoded in some fashion, calling its methods and properties internally.

PipeStream provides the capability to perform buffered reads/writes. Typically, derived classes would perform a transformation (filtering/encoding) to the data passing through it.

PipeStream does not support seeking\.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

PipeStream Members | Dart.PowerTCP.Ftp Namespace


PipeStream Members

PipeStream overview

Public Instance Constructors

PipeStream Overloaded. Initializes a new instance of the PipeStream class.

Public Instance Properties

CanRead | Overridden. Gets a value indicating whether the current Stream supports reading.
CanSeek (inherited from EnhancedStream) | Gets a value indicating whether the current stream supports seeking.
CanWrite (inherited from EnhancedStream) | Gets a value indicating whether the current stream supports writing.
Charset (inherited from EnhancedStream) | Gets and sets the character set used for string/byte array conversions.
CoreStream | The internal stream to which all buffered reads/writes are being made.
Encoding (inherited from EnhancedStream) | Gets or sets the type of encoding to use.
Length | Overridden. Gets the length in bytes of the stream.
Position | Overridden. Gets or sets the position within the current stream

Public Instance Methods

BeginRead (inherited from Stream) | Begins an asynchronous read operation.
BeginWrite (inherited from Stream) | Begins an asynchronous write operation.
Close (inherited from Stream) | Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose (inherited from EnhancedStream) | Releases all resources associated with the object.
EndRead (inherited from Stream) | Waits for the pending asynchronous read to complete.
EndWrite (inherited from Stream) | Ends an asynchronous write operation.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
Flush | Overridden. Updates the underlying data source or repository with the current state of the buffer and then clears the buffer.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
Read | Overridden. Overloaded. Read data from the Stream.
Read (inherited from EnhancedStream) | Overloaded. Reads at least one byte of data from the Stream and copies it into the provided buffer.
ReadByte (inherited from Stream) | Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
Save (inherited from EnhancedStream) | Overloaded. Saves the data in the stream to the file specified by fileName.
Seek (inherited from EnhancedStream) | Overridden. Sets the position within the current Stream to the specified value. Always throws a NotSupportedException.
SetLength (inherited from EnhancedStream) | Overridden. Sets the length of the current Stream to the specified value. Always throws a NotSupportedException.
ToArray (inherited from EnhancedStream) | Returns the byte array representation of the Stream data.
ToString (inherited from EnhancedStream) | Overridden. Returns the string representation of the Stream data.
Write | Overridden. Overloaded. Writes data to the stream.
Write (inherited from EnhancedStream) | Overloaded. Writes a sequence of bytes to the Stream and returns when the operation is complete.
WriteByte (inherited from Stream) | Writes a byte to the current position in the stream and advances the position within the stream by one byte.
WriteTo (inherited from EnhancedStream) | Overloaded. Writes all of the data contained in this Stream to a destination Stream.

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace


PipeStream Constructor

Creates a new instance of PipeStream.

Overload List

Creates a new instance of PipeStream.

[Visual Basic] Public Sub New()
[C#] public PipeStream();
[C++] public: PipeStream();
[JScript] public function PipeStream();

Creates a new instance of PipeStream.

[Visual Basic] Public Sub New(ByVal Stream)
[C#] public PipeStream(Stream);
[C++] public: PipeStream(Stream*);
[JScript] public function PipeStream(Stream);

Creates a new instance of PipeStream.

[Visual Basic] Public Sub New(ByVal Stream,ByVal Encoding)
[C#] public PipeStream(Stream,Encoding);
[C++] public: PipeStream(Stream*,Encoding*);
[JScript] public function PipeStream(Stream,Encoding);

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace


PipeStream Constructor (Stream)

Creates a new instance of PipeStream.

[Visual Basic]
Public Sub New( _
   ByVal coreStream As Stream _
)
[C#]
public PipeStream(
   Stream coreStream
);
[C++]
public: PipeStream(
   Stream* coreStream
);
[JScript]
public function PipeStream(
   Stream coreStream
);

Parameters

coreStream
The Stream object to set as CoreStream.

Remarks

The default constructor creates a new instance of PipeStream, with CoreStream initialized to the Stream passed in as coreStream.

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace | PipeStream Constructor Overload List


PipeStream Constructor (Stream, Encoding)

Creates a new instance of PipeStream.

[Visual Basic]
Public Sub New( _
   ByVal coreStream As Stream, _
   ByVal encoding As Encoding _
)
[C#]
public PipeStream(
   Stream coreStream,
   Encoding encoding
);
[C++]
public: PipeStream(
   Stream* coreStream,
   Encoding* encoding
);
[JScript]
public function PipeStream(
   Stream coreStream,
   Encoding encoding
);

Parameters

coreStream
The Stream object to set as CoreStream.
encoding
The Encoding type to use for data transformations.

Remarks

The default constructor creates a new instance of PipeStream, with CoreStream initialized to the Stream passed in as coreStream.

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace | PipeStream Constructor Overload List


PipeStream Constructor ()

Creates a new instance of PipeStream.

[Visual Basic]
Public Sub New()
[C#]
public PipeStream();
[C++]
public: PipeStream();
[JScript]
public function PipeStream();

Remarks

This constructor is used by derived objects, which must set coreStream.

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace | PipeStream Constructor Overload List


PipeStream Properties

The properties of the PipeStream class are listed below. For a complete list of PipeStream class members, see the PipeStream Members topic.

Public Instance Properties

CanRead | Overridden. Gets a value indicating whether the current Stream supports reading.
CanSeek (inherited from EnhancedStream) | Gets a value indicating whether the current stream supports seeking.
CanWrite (inherited from EnhancedStream) | Gets a value indicating whether the current stream supports writing.
Charset (inherited from EnhancedStream) | Gets and sets the character set used for string/byte array conversions.
CoreStream | The internal stream to which all buffered reads/writes are being made.
Encoding (inherited from EnhancedStream) | Gets or sets the type of encoding to use.
Length | Overridden. Gets the length in bytes of the stream.
Position | Overridden. Gets or sets the position within the current stream

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace


CanRead Property

PipeStream.CanRead Property

Gets a value indicating whether the current Stream supports reading.

[Visual Basic]
Overrides Public Property ReadOnly CanRead As Boolean
[C#]
public override bool CanRead { get; }
[C++]
public: __property bool get_CanRead();
[JScript]
public override function get CanRead() : bool

Property Value

true if reading is currently allowed, and false if not.

Remarks

If Position < Length, this property returns true to indicate bytes are available to be read, otherwise false.

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace


CoreStream Property

PipeStream.CoreStream Property

The internal stream to which all buffered reads/writes are being made.

[Visual Basic]
Public Property ReadOnly CoreStream As Stream
[C#]
public Stream CoreStream { get; }
[C++]
public: __property Stream* get_CoreStream();
[JScript]
public function get CoreStream() : Stream

Remarks

This property returns the internal stream to which all buffered reads/writes are being made.

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace


Length Property

PipeStream.Length Property

Gets the length in bytes of the stream.

[Visual Basic]
Overrides Public Property ReadOnly Length As Long
[C#]
public override long Length { get; }
[C++]
public: __property __int64 get_Length();
[JScript]
public override function get Length() : long

Remarks

Returns PipeStream.CoreStream.Length if not writing, and Position, if writing.

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace


Position Property

PipeStream.Position Property

Gets or sets the position within the current stream

[Visual Basic]
Overrides Public Property Position As Long
[C#]
public override long Position { get; set; }
[C++]
public: __property __int64 get_Position();
public: __property void set_Position(__int64 );
[JScript]
public override function get Position() : long
public override function set Position(long);

Remarks

Returns PipeStream.CoreStream.Position if not writing, and the amount written to the stream, if writing. Attempting to set this property returns an InvalidOperationException unless it is set to 0, in which case the position of the PipeStream.CoreStream.Position will be set to 0, and this object is ready for reading.

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace


PipeStream Methods

The methods of the PipeStream class are listed below. For a complete list of PipeStream class members, see the PipeStream Members topic.

Public Instance Methods

BeginRead (inherited from Stream) | Begins an asynchronous read operation.
BeginWrite (inherited from Stream) | Begins an asynchronous write operation.
Close (inherited from Stream) | Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose (inherited from EnhancedStream) | Releases all resources associated with the object.
EndRead (inherited from Stream) | Waits for the pending asynchronous read to complete.
EndWrite (inherited from Stream) | Ends an asynchronous write operation.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
Flush | Overridden. Updates the underlying data source or repository with the current state of the buffer and then clears the buffer.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
Read | Overridden. Overloaded. Read data from the Stream.
Read (inherited from EnhancedStream) | Overloaded. Reads at least one byte of data from the Stream and copies it into the provided buffer.
ReadByte (inherited from Stream) | Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
Save (inherited from EnhancedStream) | Overloaded. Saves the data in the stream to the file specified by fileName.
Seek (inherited from EnhancedStream) | Overridden. Sets the position within the current Stream to the specified value. Always throws a NotSupportedException.
SetLength (inherited from EnhancedStream) | Overridden. Sets the length of the current Stream to the specified value. Always throws a NotSupportedException.
ToArray (inherited from EnhancedStream) | Returns the byte array representation of the Stream data.
ToString (inherited from EnhancedStream) | Overridden. Returns the string representation of the Stream data.
Write | Overridden. Overloaded. Writes data to the stream.
Write (inherited from EnhancedStream) | Overloaded. Writes a sequence of bytes to the Stream and returns when the operation is complete.
WriteByte (inherited from Stream) | Writes a byte to the current position in the stream and advances the position within the stream by one byte.
WriteTo (inherited from EnhancedStream) | Overloaded. Writes all of the data contained in this Stream to a destination Stream.

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace


Flush Method

PipeStream.Flush Method

Updates the underlying data source or repository with the current state of the buffer and then clears the buffer.

[Visual Basic]
Overrides Public Sub Flush()
[C#]
public override void Flush();
[C++]
public: void Flush();
[JScript]
public override function Flush();

Remarks

If the Stream contains any internal Streams as members, this method will also cause the Flush method of all internal Streams.

This method MUST be called when writing is complete for operations to operate properly. One example is when creating a message comprised of only headers. If Flush is not called, the headers will be lost.

Exceptions

Exception Type | Condition
IOException | An I/O error occurs.
ObjectDisposedException | The Stream is closed.

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace


Read Method

PipeStream.Read Method

Read data from the Stream.

Overload List

Reads at least one byte of data from the Stream and copies it into the provided buffer.
Inherited from EnhancedStream.

[Visual Basic] Public Function Read(ByVal Byte()) As Integer
[C#] public int Read(byte[]);
[C++] public: int Read(char __gc[]);
[JScript] public function Read(Byte[]): int;

Read data from the Stream.

[Visual Basic] Overrides OverloadsPublic Function Read(ByVal Byte(),ByVal Integer,ByVal Integer) As Integer
[C#] public override int Read(byte[],int,int);
[C++] public: int Read(char __gc[],int,int);
[JScript] public override function Read(Byte[],int,int): int;

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace


Read Method (Byte[], Int32, Int32)

PipeStream.Read Method (Byte[], Int32, Int32)

Read data from the Stream.

[Visual Basic]
Overrides  OverloadsPublic Function Read( _
   ByVal buffer As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer _
) As Integer
[C#]
public override int Read(
   byte[] buffer,
   int offset,
   int count
);
[C++]
public: int Read(
   char buffer __gc[],
   int offset,
   int count
);
[JScript]
public override function Read(
   Byte[] buffer,
   int offset,
   int count
): int;

Parameters

buffer
The storage location for the received data.
offset
The zero-based position in the buffer at which to store the received data.
count
The maximum number of bytes to read.

Return Value

The total number of bytes read into the buffer.

Remarks

This method actually calls PipeStream.CoreStream.Read, passing the data "through" the PipeStream and into buffer.

Exceptions

Exception Type | Condition
IOException | Thrown when the Stream is not readable.
ArgumentNullException | Thrown when the buffer or callback is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when count is less than or equal to zero.
ArgumentException | Thrown when the (offset + count) > buffer.Length.

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace | PipeStream.Read Overload List


Write Method

PipeStream.Write Method

Writes data to the stream.

Overload List

Writes a sequence of bytes to the Stream and returns when the operation is complete.
Inherited from EnhancedStream.

[Visual Basic] Public Sub Write(ByVal Byte())
[C#] public void Write(byte[]);
[C++] public: void Write(char __gc[]);
[JScript] public function Write(Byte[]);

Writes data to the stream.

[Visual Basic] Overrides OverloadsPublic Sub Write(ByVal Byte(),ByVal Integer,ByVal Integer)
[C#] public override void Write(byte[],int,int);
[C++] public: void Write(char __gc[],int,int);
[JScript] public override function Write(Byte[],int,int);

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace


Write Method (Byte[], Int32, Int32)

PipeStream.Write Method (Byte[], Int32, Int32)

Writes data to the stream.

[Visual Basic]
Overrides  OverloadsPublic Sub Write( _
   ByVal buffer As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer _
)
[C#]
public override void Write(
   byte[] buffer,
   int offset,
   int count
);
[C++]
public: void Write(
   char buffer __gc[],
   int offset,
   int count
);
[JScript]
public override function Write(
   Byte[] buffer,
   int offset,
   int count
);

Parameters

buffer
The storage location for the written data.
offset
The zero-based position in the buffer from which to begin writing from.
count
The exact number of bytes to write.

Remarks

This method actually calls PipeStream.CoreStream.Write, passing the data "through" the PipeStream and into CoreStream.

Exceptions

Exception Type | Condition
IOException | Thrown when the Stream is not writeable.
ArgumentNullException | Thrown when the buffer is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when count is less than or equal to zero.
ArgumentException | Thrown when the (offset + count) > buffer.Length.

See Also

PipeStream Class | Dart.PowerTCP.Ftp Namespace | PipeStream.Write Overload List


PreviewEventArgs Class

This class is passed into the Preview event and provides data for that event.

For a list of all members of this type, see PreviewEventArgs Members.

System.Object
System.EventArgs
Dart.PowerTCP.Ftp.PreviewEventArgs

[Visual Basic]
Public Class PreviewEventArgs
    Inherits EventArgs
[C#]
public class PreviewEventArgs : EventArgs
[C++]
public __gc class PreviewEventArgs : public EventArgs
[JScript]
public class PreviewEventArgs extends EventArgs

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

When a file transfer method is called (Get, Put, BeginGet, or BeginPut) the Preview event will be raised announcing each pending transfer. A PreviewEventArgs object is passed in containing information about the pending file transfer.

This class is useful for cancelling undesired file transfers.

If any error occurred during the asynchronous method call, it would be returned in the handling event. To trap the error, simply put a try/catch block around any access of the parameter e.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

PreviewEventArgs Members | Dart.PowerTCP.Ftp Namespace


PreviewEventArgs Members

PreviewEventArgs overview

Public Instance Properties

Cancel | Used to cancel the pending file transfer.
CurrentFile | Index of file being transferred.
FileName | Gets the pathname of the file to be transferred.
TotalFiles | Total number of files being transferred.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

PreviewEventArgs Class | Dart.PowerTCP.Ftp Namespace


PreviewEventArgs Properties

The properties of the PreviewEventArgs class are listed below. For a complete list of PreviewEventArgs class members, see the PreviewEventArgs Members topic.

Public Instance Properties

Cancel | Used to cancel the pending file transfer.
CurrentFile | Index of file being transferred.
FileName | Gets the pathname of the file to be transferred.
TotalFiles | Total number of files being transferred.

See Also

PreviewEventArgs Class | Dart.PowerTCP.Ftp Namespace


Cancel Property

PreviewEventArgs.Cancel Property

Used to cancel the pending file transfer.

[Visual Basic]
Public Property Cancel As Boolean
[C#]
public bool Cancel { get; set; }
[C++]
public: __property bool get_Cancel();
public: __property void set_Cancel(bool );
[JScript]
public function get Cancel() : bool
public function set Cancel(bool);

Property Value

A bool that may be read or set.

See Also

PreviewEventArgs Class | Dart.PowerTCP.Ftp Namespace


CurrentFile Property

PreviewEventArgs.CurrentFile Property

Index of file being transferred.

[Visual Basic]
Public Property ReadOnly CurrentFile As Long
[C#]
public long CurrentFile { get; }
[C++]
public: __property __int64 get_CurrentFile();
[JScript]
public function get CurrentFile() : long

Property Value

A long representing the index of the current file being transferred.

Remarks

If transferring multiple files, this property will contain the index of the currently transferring file. If transferring a single file, this property will always be 1.

This property is useful for displaying multiple file transfer progress to the user. For example, the application could have two ProgressBar objects, one to track the file transfer progress of individual files, one to track the progress of all files (for an MPUT or MGET).

See Also

PreviewEventArgs Class | Dart.PowerTCP.Ftp Namespace


FileName Property

PreviewEventArgs.FileName Property

Gets the pathname of the file to be transferred.

[Visual Basic]
Public Property ReadOnly FileName As String
[C#]
public string FileName { get; }
[C++]
public: __property String* get_FileName();
[JScript]
public function get FileName() : String

Property Value

A string representing the path and name of the file being transferred.

Remarks

When storing or retrieving files or streams, this property will contain the name of the file on the server. When storing multiple files, this property will contain the pathname of the file being transferred.

See Also

PreviewEventArgs Class | Dart.PowerTCP.Ftp Namespace


TotalFiles Property

PreviewEventArgs.TotalFiles Property

Total number of files being transferred.

[Visual Basic]
Public Property ReadOnly TotalFiles As Long
[C#]
public long TotalFiles { get; }
[C++]
public: __property __int64 get_TotalFiles();
[JScript]
public function get TotalFiles() : long

Property Value

A long representing the total number of files being transferred.

Remarks

If transferring multiple files, this property will contain the total number of all files being transferred. If transferring a single file, this property will always be 1.

This property is useful for displaying multiple file transfer progress to the user. For example, the application could have two ProgressBar objects, one to track the file transfer progress of individual files, one to track the progress of all files transferred (for an MPUT or MGET).

See Also

PreviewEventArgs Class | Dart.PowerTCP.Ftp Namespace


PreviewEventHandler Delegate

Represents the method (event handler) that will be raised to preview the next file transfer.

[Visual Basic]
Public Delegate Function Sub  PreviewEventHandler( _
   ByVal sender As Object, _
   ByVal e As PreviewEventArgs _
)
[C#]
public delegate void PreviewEventHandler(
   object sender,
   PreviewEventArgs e
)
[C++]
public __gc __delegate void PreviewEventHandler(
   Object* sender,
   PreviewEventArgs* e
)

[JScript] In JScript, you can use the delegates defined by a type, but you cannot define your own.

Parameters

sender
The source of the event.
e
A PreviewEventArgs object that contains the event data.

Remarks

As Microsoft describes in their MSDN documentation, the event model in the .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed:

  • A class that holds the event data. This class must derive from the base class EventArgs.
  • A delegate that points to a method that provides the response to the event.

When capturing file transfer preview information is desired, the class that holds the event data is the PreviewEventArgs class. A method must be created with the same signature as the delegate. If you are working within the Visual Studio.NET environment, this can be automatically done for you. See the "Using Events In PowerTCP" topic for more information. If you are not working within the Visual Studio.NET environment, you must do this yourself. In this example that would mean a method would have to be defined to accept two arguments (an object and a PreviewEventArgs) and return void. Once this has been done, the delegate must be "connected" to the handling event. This is done by adding an instance of the delegate to the event (see examples below).

For more information about event handler delegates, see the "Using Events In PowerTCP" topic.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


ProtocolException Class

Used to throw protocol exceptions for upper-layer protocols like FTP, SMTP and POP3.

For a list of all members of this type, see ProtocolException Members.

System.Object
System.Exception
System.ApplicationException
Dart.PowerTCP.Ftp.ProtocolException

[Visual Basic]
Public Class ProtocolException
    Inherits ApplicationException
[C#]
public class ProtocolException : ApplicationException
[C++]
public __gc class ProtocolException : public ApplicationException
[JScript]
public class ProtocolException extends ApplicationException

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

This exception is thrown when a server response is negative. For example, if the server returned "500" (indicating a syntax error) as response to a command being sent, a ProtocolException would be thrown.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

ProtocolException Members | Dart.PowerTCP.Ftp Namespace


ProtocolException Members

ProtocolException overview

Public Instance Constructors

ProtocolException Overloaded. Initializes a new instance of the ProtocolException class.

Public Instance Properties

HelpLink (inherited from Exception) | Gets or sets a link to the help file associated with this exception.
InnerException (inherited from Exception) | Gets the Exception instance that caused the current exception.
Message (inherited from Exception) | Gets a message that describes the current exception.
Source (inherited from Exception) | Gets or sets the name of the application or the object that causes the error.
StackTrace (inherited from Exception) | Gets a string representation of the frames on the call stack at the time the current exception was thrown.
TargetSite (inherited from Exception) | Gets the method that throws the current exception.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetBaseException (inherited from Exception) | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetObjectData (inherited from Exception) | When overridden in a derived class, sets the SerializationInfo with information about the exception.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Exception) | Overridden. Creates and returns a string representation of the current exception.

See Also

ProtocolException Class | Dart.PowerTCP.Ftp Namespace


ProtocolException Constructor

Initializes a new instance of the ProtocolException class.

Overload List

Initializes a new instance of the ProtocolException class.

[Visual Basic] Public Sub New()
[C#] public ProtocolException();
[C++] public: ProtocolException();
[JScript] public function ProtocolException();

Initializes a new instance of the ProtocolException class.

[Visual Basic] Public Sub New(ByVal String)
[C#] public ProtocolException(string);
[C++] public: ProtocolException(String*);
[JScript] public function ProtocolException(String);

Initializes a new instance of the ProtocolException class.

[Visual Basic] Public Sub New(ByVal String,ByVal Exception)
[C#] public ProtocolException(string,Exception);
[C++] public: ProtocolException(String*,Exception*);
[JScript] public function ProtocolException(String,Exception);

See Also

ProtocolException Class | Dart.PowerTCP.Ftp Namespace


ProtocolException Constructor ()

Initializes a new instance of the ProtocolException class.

[Visual Basic]
Public Sub New()
[C#]
public ProtocolException();
[C++]
public: ProtocolException();
[JScript]
public function ProtocolException();

See Also

ProtocolException Class | Dart.PowerTCP.Ftp Namespace | ProtocolException Constructor Overload List


ProtocolException Constructor (String)

Initializes a new instance of the ProtocolException class.

[Visual Basic]
Public Sub New( _
   ByVal message As String _
)
[C#]
public ProtocolException(
   string message
);
[C++]
public: ProtocolException(
   String* message
);
[JScript]
public function ProtocolException(
   String message
);

See Also

ProtocolException Class | Dart.PowerTCP.Ftp Namespace | ProtocolException Constructor Overload List


ProtocolException Constructor (String, Exception)

Initializes a new instance of the ProtocolException class.

[Visual Basic]
Public Sub New( _
   ByVal message As String, _
   ByVal e As Exception _
)
[C#]
public ProtocolException(
   string message,
   Exception e
);
[C++]
public: ProtocolException(
   String* message,
   Exception* e
);
[JScript]
public function ProtocolException(
   String message,
   Exception e
);

See Also

ProtocolException Class | Dart.PowerTCP.Ftp Namespace | ProtocolException Constructor Overload List


Proxy Class

Provides an easy way to manage communication with proxy servers

For a list of all members of this type, see Proxy Members.

System.Object
Dart.PowerTCP.Ftp.Proxy

[Visual Basic]
Public Class Proxy
[C#]
public class Proxy
[C++]
public __gc class Proxy
[JScript]
public class Proxy

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

The Proxy class provides extensive native support for proxy servers. Simply set the appropriate properties of the Proxy class and proxy communication occurs transparently.

When using PowerTCP components that use the Tcp component for the underlying connection, you can set the Proxy properties by using the object.Connection property, which exposes the Tcp component. When using the Tcp component, simple set the Proxy property.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Proxy Members | Dart.PowerTCP.Ftp Namespace


Proxy Members

Proxy overview

Public Instance Constructors

Proxy Constructor Initializes a new instance of the Proxy class.

Public Instance Properties

Password | Password to use when authenticating to a proxy.
Server | Get or set a value which specifies the proxy server to use.
ServerPort | Port to use when connecting to a proxy server.
Type | Type of proxy.
Username | User name to use when authenticating to a proxy.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

Proxy Class | Dart.PowerTCP.Ftp Namespace


Proxy Constructor

Initializes a new instance of the Proxy class.

[Visual Basic]
Public Sub New()
[C#]
public Proxy();
[C++]
public: Proxy();
[JScript]
public function Proxy();

Remarks

The default constructor initializes a new instance of the Proxy class.

See Also

Proxy Class | Dart.PowerTCP.Ftp Namespace


Proxy Properties

The properties of the Proxy class are listed below. For a complete list of Proxy class members, see the Proxy Members topic.

Public Instance Properties

Password | Password to use when authenticating to a proxy.
Server | Get or set a value which specifies the proxy server to use.
ServerPort | Port to use when connecting to a proxy server.
Type | Type of proxy.
Username | User name to use when authenticating to a proxy.

See Also

Proxy Class | Dart.PowerTCP.Ftp Namespace


Password Property

Proxy.Password Property

Password to use when authenticating to a proxy.

[Visual Basic]
Public Property Password As String
[C#]
public string Password { get; set; }
[C++]
public: __property String* get_Password();
public: __property void set_Password(String* );
[JScript]
public function get Password() : String
public function set Password(String);

Property Value

A string value representing the password used to access the a proxy.

Remarks

Specifies the password to use for authentication on some proxies.

See Also

Proxy Class | Dart.PowerTCP.Ftp Namespace


Server Property

Proxy.Server Property

Get or set a value which specifies the proxy server to use.

[Visual Basic]
Public Property Server As String
[C#]
public string Server { get; set; }
[C++]
public: __property String* get_Server();
public: __property void set_Server(String* );
[JScript]
public function get Server() : String
public function set Server(String);

Property Value

A string representing the proxy server to use.

Remarks

Specifies the hostname of the proxy server. Specify the server either in dot notation ("111.111.111.111") or by host name ("myserver").

See Also

Proxy Class | Dart.PowerTCP.Ftp Namespace


ServerPort Property

Proxy.ServerPort Property

Port to use when connecting to a proxy server.

[Visual Basic]
Public Property ServerPort As Integer
[C#]
public int ServerPort { get; set; }
[C++]
public: __property int get_ServerPort();
public: __property void set_ServerPort(int );
[JScript]
public function get ServerPort() : int
public function set ServerPort(int);

Property Value

An integer value representing a proxy port to connect to.

Remarks

Specifies the port to use when connecting to the proxy server.

See Also

Proxy Class | Dart.PowerTCP.Ftp Namespace


Type Property

Proxy.Type Property

Type of proxy.

[Visual Basic]
Public Property Type As ProxyType
[C#]
public ProxyType Type { get; set; }
[C++]
public: __property ProxyType get_Type();
public: __property void set_Type(ProxyType );
[JScript]
public function get Type() : ProxyType
public function set Type(ProxyType);

Property Value

One of the ProxyType values.

Remarks

Specifies the type of proxy used.

See Also

Proxy Class | Dart.PowerTCP.Ftp Namespace


Username Property

Proxy.Username Property

User name to use when authenticating to a proxy.

[Visual Basic]
Public Property Username As String
[C#]
public string Username { get; set; }
[C++]
public: __property String* get_Username();
public: __property void set_Username(String* );
[JScript]
public function get Username() : String
public function set Username(String);

Property Value

A string value representing the user name used to access a proxy.

Remarks

Specifies the username to use for authentication on some proxies.

See Also

Proxy Class | Dart.PowerTCP.Ftp Namespace


ProxyType Enumeration

Enumerates the supported proxy types.

[Visual Basic]
Public Enum ProxyType
[C#]
public enum ProxyType
[C++]
public __value enum ProxyType
[JScript]
public enum ProxyType

Remarks

This enumeration is used by the Proxy property.

Set the Type property to the proper ProxyType of your proxy server before calling any method that requires communication with the server.

Members

Member Name | Description
None | No proxy server is used.
Socks4 | SOCKS v4 proxy.
Socks5 | SOCKS v5 proxy.
HttpConnect | Added Http-Connect proxy support 9-16-05, issue 3466

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


Response Class

Presents the response portion from an Internet protocol Request/Response pair.

For a list of all members of this type, see Response Members.

System.Object
Dart.PowerTCP.Ftp.Response

[Visual Basic]
Public Class Response
[C#]
public class Response
[C++]
public __gc class Response
[JScript]
public class Response

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

Often, protocols define that commands be responded to with responses made up of a response code and response text. For example(using the FTP protocol as an example), the FTP protocol defines a command "CWD" which is a request to change the working directory. If command sent to the server was "CWD MYDIR" (a request to change to a directory called "MYDIR"), the response back from the server may be something like "200 Working Directory Changed". In PowerTCP this response is encapsulated by the Response object, allowing access to the code (through the Code property), the text (through the Text property), or the raw response (through the ToString method). The Response object is usually a member of the Invoke object, which represents a request/response pair.

Example

The following example demonstrates closing a connection.

[Visual Basic]
' First, check to see if currently connected
If Ftp1.Connected Then

   ' Close method returns an Invoke object
   Dim invoke As Dart.PowerTCP.Ftp.Invoke

   ' Attempt to close the connection by using the Close method
   Try
      invoke = Ftp1.Close()
   Catch ex As Exception
      ' An error occurred during the close attempt
      Debug.WriteLine(ex.Message)
   End Try

   If Ftp1.Connected Then
      ' For some reason the Close method did not work. Just perform a harsh abort
      Ftp1.Dispose()
      Debug.WriteLine("Unable to QUIT, connection aborted")
   Else
      Debug.WriteLine("Close successful.")
      Debug.WriteLine("Response Code From Server: " + invoke.Response.Code.ToString())
      Debug.WriteLine("Response Text From Server: " + invoke.Response.Text)
   End If

Else
   Debug.WriteLine("You are not connected")
End If

[C#]
// First, check to see if currently connected
if(ftp1.Connected)
{
    // Close method returns an Invoke object
    Dart.PowerTCP.Ftp.Invoke invoke;

    // Attempt to Close the connection by using the Close method
    try
    {
        invoke = ftp1.Close();
    }
    catch(Exception ex)
    {
        // An error occurred during the close attempt
        Debug.WriteLine(ex.Message);
    }
    if(ftp1.Connected)
    {
        // For some reason the QUIT command did not work, just perform a "harsh" abort
        ftp1.Dispose();
        Debug.WriteLine("Unable to QUIT, connection aborted");
    }
    else
    {
      Debug.WriteLine("Close successful.");
      Debug.WriteLine("Response Code From Server: " + invoke.Response.Code.ToString());
      Debug.WriteLine("Response Text From Server: " + invoke.Response.Text);
    }
}
else{Debug.WriteLine("You are not connected");}

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Response Members | Dart.PowerTCP.Ftp Namespace


Response Members

Response overview

Public Instance Constructors

Response Constructor Initializes a new instance of the Response class.

Public Instance Properties

Code | Gets the 3-digit response code from the response string.
Text | Gets the textual response without the 3-digit response code and CR/LF's.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString | Overridden. Returns the complete response string received.

See Also

Response Class | Dart.PowerTCP.Ftp Namespace


Response Constructor

Initializes a new instance of the Response class.

[Visual Basic]
Public Sub New( _
   ByVal response As String _
)
[C#]
public Response(
   string response
);
[C++]
public: Response(
   String* response
);
[JScript]
public function Response(
   String response
);

See Also

Response Class | Dart.PowerTCP.Ftp Namespace


Response Properties

The properties of the Response class are listed below. For a complete list of Response class members, see the Response Members topic.

Public Instance Properties

Code | Gets the 3-digit response code from the response string.
Text | Gets the textual response without the 3-digit response code and CR/LF's.

See Also

Response Class | Dart.PowerTCP.Ftp Namespace


Code Property

Response.Code Property

Gets the 3-digit response code from the response string.

[Visual Basic]
Public Property ReadOnly Code As Integer
[C#]
public int Code { get; }
[C++]
public: __property int get_Code();
[JScript]
public function get Code() : int

Property Value

An integer representing the response code parsed from the raw response.

Remarks

The Response.Code property allows easy access to the code parsed from the raw response. To retrieve the raw response, simply use the ToString method.

This property is useful because it allows checking of the code received from the server without parsing. For example, if you are checking for a response code between 200 and 299, you can simply say:

if(Invoke.Response.Code < 200 && Invoke.Response.Code > 300)
   // Take action here

This is helpful because you don't have to explicitly parse the raw response, and because the value is already an integer, allowing numerical comparison.

Example

The following example demonstrates closing a connection.

[Visual Basic]
' First, check to see if currently connected
If Ftp1.Connected Then

   ' Close method returns an Invoke object
   Dim invoke As Dart.PowerTCP.Ftp.Invoke

   ' Attempt to close the connection by using the Close method
   Try
      invoke = Ftp1.Close()
   Catch ex As Exception
      ' An error occurred during the close attempt
      Debug.WriteLine(ex.Message)
   End Try

   If Ftp1.Connected Then
      ' For some reason the Close method did not work. Just perform a harsh abort
      Ftp1.Dispose()
      Debug.WriteLine("Unable to QUIT, connection aborted")
   Else
      Debug.WriteLine("Close successful.")
      Debug.WriteLine("Response Code From Server: " + invoke.Response.Code.ToString())
      Debug.WriteLine("Response Text From Server: " + invoke.Response.Text)
   End If

Else
   Debug.WriteLine("You are not connected")
End If

[C#]
// First, check to see if currently connected
if(ftp1.Connected)
{
    // Close method returns an Invoke object
    Dart.PowerTCP.Ftp.Invoke invoke;

    // Attempt to Close the connection by using the Close method
    try
    {
        invoke = ftp1.Close();
    }
    catch(Exception ex)
    {
        // An error occurred during the close attempt
        Debug.WriteLine(ex.Message);
    }
    if(ftp1.Connected)
    {
        // For some reason the QUIT command did not work, just perform a "harsh" abort
        ftp1.Dispose();
        Debug.WriteLine("Unable to QUIT, connection aborted");
    }
    else
    {
      Debug.WriteLine("Close successful.");
      Debug.WriteLine("Response Code From Server: " + invoke.Response.Code.ToString());
      Debug.WriteLine("Response Text From Server: " + invoke.Response.Text);
    }
}
else{Debug.WriteLine("You are not connected");}

See Also

Response Class | Dart.PowerTCP.Ftp Namespace


Text Property

Response.Text Property

Gets the textual response without the 3-digit response code and CR/LF's.

[Visual Basic]
Public Property ReadOnly Text As String
[C#]
public string Text { get; }
[C++]
public: __property String* get_Text();
[JScript]
public function get Text() : String

Property Value

A string representing the test response parsed from the raw response.

Remarks

The Response.Text property allows easy access to the text (the response from the server minus the response code and CRLFs) parsed from the raw response. To retrieve the raw response, simply use the ToString method.

This property is useful because it allows access to the response string from the server without having to parse.

If the response from the server was "200 Working Directory Changed", this property would contain "Working Directory Changed".

Example

The following example demonstrates using Invoke to send a custom command.

[Visual Basic]
' Set server and user properties. This will allow us to call other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Invoke a command
Dim invoke as Dart.PowerTCP.Ftp.Invoke

' Use Invoke(FtpCommand.Null) to send a proprietary command

Try
   invoke = Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "MYFILECOMMAND file1.txt")
Catch ex As Exception
   Debug.WriteLine("Error: " + ex.Message)
   Exit Sub
End Try

' Success. Print response.
Debug.WriteLine("Response from server : " + invoke.Response.Text)
Ftp1.Close()

[C#]
// Set server and user properties. This will allow us to call other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Use Invoke(FtpCommand.Null) to send a proprietary command
try
{
   Dart.PowerTCP.Ftp.Invoke invoke = ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Null, "MYFILECOMMAND file1.txt");
}
catch(Exception ex)
{
   Debug.WriteLine("Error: " + ex.Message);
   return;
}

// Success. Print response
Debug.WriteLine("Response from server : " + invoke.Response.Text);

// Close connection
ftp1.Close();

See Also

Response Class | Dart.PowerTCP.Ftp Namespace


Response Methods

The methods of the Response class are listed below. For a complete list of Response class members, see the Response Members topic.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString | Overridden. Returns the complete response string received.

See Also

Response Class | Dart.PowerTCP.Ftp Namespace


ToString Method

Response.ToString Method

Returns the complete response string received.

[Visual Basic]
Overrides Public Function ToString() As String
[C#]
public override string ToString();
[C++]
public: String* ToString();
[JScript]
public override function ToString(): String;

Return Value

A string representing the unparsed response from the server.

Remarks

The String.ToString method is overridden to allow access to the entire unparsed string. To retrieve a parsed listing of the response code or text, use the Code or Text property, respectively.

This property is useful if you wish to see the entire response string returned from the server without any formatting applied.

Example

The following example demonstrates the ConnectedChanged event, and how using the AutoClose property effects the connection status.

[Visual Basic]
' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Create Invoke object
Dim f As Dart.PowerTCP.Ftp.Invoke

' Call a couple of methods. The ConnectedChange event should only fire once , to connect
Debug.WriteLine("Sending a PWD command. The ConnectedChanged Event should fire once for this (log in)")
f = Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.PrintDir)
Debug.WriteLine("Response from server: " + f.Response.ToString())

' Because the connection is maintained, the ConnectedChanged event will not fire for other methods called
Debug.WriteLine("Sending a HELP command. The ConnectedChanged Event should not fire for this.")
f = Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Help)
Debug.WriteLine("Response from server: " + f.Response.ToString())

' Be sure to close the connection. The ConnectedChanged event should fire once more
Ftp1.Close()

' Monitor the connection status using the ConnectedChanged event
Private Sub Ftp1_ConnectedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Ftp1.ConnectedChanged

   ' The state of the connection has changed. Check current state.
   If Ftp1.Connected Then
      Debug.WriteLine("FTP Control connection connected")
   Else
      Debug.WriteLine("FTP Control connection disconnected")
   End If
End Sub

[C#]
// Set server and user properties. This will allow calling of other
// Ftp Component methods with the log in taking place "behind the scenes"
ftp1.Server = "MyFTPServer";
ftp1.Username = "blah";
ftp1.Password = "mypass";

// Create Invoke object

Dart.PowerTCP.Ftp.Invoke f;

// Call a couple of methods. The ConnectedChange event should only fire once , to connect
Debug.WriteLine("Sending a PWD command. The ConnectedChanged Event should fire once for this (log in)");
f = ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.PrintDir);
Debug.WriteLine("Response from server: " + f.Response.ToString());

// Because the connection is maintained, the ConnectedChanged event will not fire for other methods called
Debug.WriteLine("Sending a HELP command. The ConnectedChanged Event should not fire for this.");
f = ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Help);
Debug.WriteLine("Response from server: " + f.Response.ToString());

// Be sure to close the connection. The ConnectedChanged event should fire once more
ftp1.Close();

// Monitor the connection status using the ConnectedChanged event.

private void ftp1_ConnectedChanged(object sender, System.EventArgs e)
{

    // The state of the connection has changed. Check current state.
    if(ftp1.Connected)
        Debug.WriteLine("FTP control connection connected.");
    else
        Debug.WriteLine("FTP control connection disconnected.");
}

See Also

Response Class | Dart.PowerTCP.Ftp Namespace


SecureProtocol Enumeration

Enumerates the type of encryption used in the secure product.

[Visual Basic]
Public Enum SecureProtocol
[C#]
public enum SecureProtocol
[C++]
public __value enum SecureProtocol
[JScript]
public enum SecureProtocol

Remarks

The current security standard is SSL3.

Members

Member Name | Description
Auto | Automatically negotiate the security protocol.
Ssl3 | Use SSL 3.0 as the security protocol.
Ssl2 | Use SSL 2.0 as the security protocol.
Pct | Use PCT 1.0 as the security protocol.
Tls | Use TLS 1.0 (Transport Level Security - SSL 3.1) as the security protocol.
None | No security.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


Security Enumeration

Enumerates the security protocol and authentication types which can be used.

[Visual Basic]
Public Enum Security
[C#]
public enum Security
[C++]
public __value enum Security
[JScript]
public enum Security

Remarks

This enumeration is used by the Security property of the Ftp component. Set this property to the type of security protocol and authentication type used by the FTP server. For example, if explicit SSL is used, set the Security property to Security.Explicit, Security.ExplicitControlOnly, or Security.ExplicitControlOptional and connect to the secure FTP server. Typically, you will connect to the well-known port of 21 in this case. If implicit SSL is used, set the Security property to Security.Implicit, Security.ControlOnly or Security.DataOnly and connect to the secure FTP server. Typically, you will connect to the well-known port of 990 in this case.

For more information about implicit and explicit SSL, see the topic Explicit vs Implicit SSL.

Example

The following example demonstrates receiving a remote certificate.

[Visual Basic]
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Use Implicit Secure FTP
        Ftp1.Security = Security.Implicit

        'Do not ignore problems with remote certificates
        Ftp1.UseAuthentication = True

        'Login and get working directory
        Ftp1.Server = "myServer"
        Ftp1.Username = "myUser"
        Ftp1.Password = "myPassword"
        Ftp1.Invoke(FtpCommand.PrintDir)
    End Sub

    Private Sub Ftp1_CertificateReceived(ByVal sender As Object, ByVal e As CertificateReceivedEventArgs) Handles Ftp1.CertificateReceived
        'Fires during SSL handshake when server presents its certificate
        Dim msg As String = "The server could not be validated for the following reason(s):"
        e.Accept = True

        'Security checks
        If (Not e.TrustedRoot) Then
            msg = msg + vbCrLf + "    -The certificate CA was not trusted"
            e.Accept = False
        End If
        If (Not e.ValidName) Then
            msg = msg + vbCrLf + "    -The certificate name was invalid"
            e.Accept = False
        End If
        If (Not e.ValidDate) Then
            msg = msg + vbCrLf + "   -The certificate date was invalid"
            e.Accept = False
        End If

        'If Validation failed, show message to user
        If (e.Accept = False) Then
            msg = msg + vbCrLf + vbCrLf + "Do you wish to override the security check?"
            If (MessageBox.Show(msg, "Security Alert: Server could not be validated", _
             MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = DialogResult.Yes) Then e.Accept = True
        End If
    End Sub

[C#]
private void button1_Click(object sender, System.EventArgs e)
{
    //Use Implicit Secure FTP
    ftp1.Security = Security.Implicit;

    //Do not ignore problems with remote certificates
    ftp1.UseAuthentication = true;

    //Login and get working directory
    ftp1.Server = "myServer";
    ftp1.Username = "myUser";
    ftp1.Password = "myPassword";
    ftp1.Invoke(FtpCommand.PrintDir);
}

private void ftp1_CertificateReceived(object sender, CertificateReceivedEventArgs e)
{
    //Fires during SSL handshake when server presents its certificate
    string msg = "The server could not be validated for the following reason(s):";
    e.Accept = true;

    //Security checks
    if (!e.TrustedRoot)
    {
        msg = msg + "\r\n    -The certificate CA was not trusted";
        e.Accept = false;
    }
    if (!e.ValidName)
    {
        msg = msg + "\r\n    -The certificate name was invalid";
        e.Accept = false;
    }
    if (!e.ValidDate)
    {
        msg = msg + "\r\n    -The certificate date was invalid";
        e.Accept = false;
    }

    //If Validation failed, show message to user
    if (e.Accept == false)
    {
        msg = msg + "\r\n\r\nDo you wish to override the security check?";
        if (MessageBox.Show(msg, "Security Alert: Server could not be validated",
            MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            e.Accept = true;
    }
}

Members

Member Name | Description
None | No encryption on either Control or Data connection.
Implicit | Implicit encryption on Control and Data connections.
Explicit | Require explicit "AUTH SSL" on Control connection and implicit encryption on Data connection.
ExplicitControlOnly | Require explicit "AUTH SSL" on Control connection.
ExplicitControlOptional | Try to use explicit "AUTH SSL" on Control connection.
ControlOnly | Implicit encryption on Control connection only.
DataOnly | Implicit encryption on Data connection only.
ImplicitLogin | Implicit encryption on Data and Control until the user is logged in, then no encryption on control.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


Segment Class

Provides a reference to a data segment where data is sent or received over a TCP stream.

For a list of all members of this type, see Segment Members.

System.Object
Dart.PowerTCP.Ftp.Segment

[Visual Basic]
Public Class Segment
[C#]
public class Segment
[C++]
public __gc class Segment
[JScript]
public class Segment

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

When data is sent or received when using the Tcp component (which may be by using the Tcp component directly, or by using another component that uses the Tcp component for the underlying connection), a Segment object is returned. This Segment object will contain data such as the data sent or received and the amount of bytes sent or received. To use the data, simply access the Buffer property using the offset specified by the Offset property. As a shortcut, the ToString method can be used to simply return all data sent or received as a string.

The Segment object is also used by other components beside the Tcp component. For example, several components have a Trace event which allows access to any data sent or received over the control connection. A SegmentEventArgs class is made accessible in this event, containing a Segment object describing the data sent or received.

Example

The following example demonstrates connecting to a server while specifying a local interface to use.

[Visual Basic]
' Connect to the server, specifying the local interface to use
Tcp1.Connect("atropos", 13, "192.168.0.83", 8888)

' Since connection was to DAYTIME port (13), simply receive the time
Dim seg As Segment = Tcp1.Receive()

Debug.WriteLine("Time reported by server: " + seg.ToString())

[C#]
// Connect to the server, specifying the local interface to use
tcp1.Connect("atropos", 13, "192.168.0.83", 8888);

// Since connection was to DAYTIME port (13), simply receive the time
Segment seg = tcp1.Receive();

Debug.WriteLine("Time reported by server: " + seg.ToString());

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Segment Members | Dart.PowerTCP.Ftp Namespace


Segment Members

Segment overview

Public Instance Properties

Buffer | The buffer containing the data that was sent/received.
Count | The amount of bytes that were sent/received.
Offset | The offset into the buffer.
Sent | Indicates whether the data was sent or received.
SocketFlags | Gets the SocketFlags associated with the Segment.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString | Overridden. Returns all data sent/received as a string.

See Also

Segment Class | Dart.PowerTCP.Ftp Namespace


Segment Properties

The properties of the Segment class are listed below. For a complete list of Segment class members, see the Segment Members topic.

Public Instance Properties

Buffer | The buffer containing the data that was sent/received.
Count | The amount of bytes that were sent/received.
Offset | The offset into the buffer.
Sent | Indicates whether the data was sent or received.
SocketFlags | Gets the SocketFlags associated with the Segment.

See Also

Segment Class | Dart.PowerTCP.Ftp Namespace


Buffer Property

Segment.Buffer Property

The buffer containing the data that was sent/received.

[Visual Basic]
Public Property ReadOnly Buffer As Byte()
[C#]
public byte[] Buffer { get; }
[C++]
public: __property char get_Buffer() __gc[];
[JScript]
public function get Buffer() : Byte[]

Property Value

A byte array containing data that was sent/received over the socket.

Remarks

When using the Tcp component, using Send or Receive will return a Segment object. The data sent/received is available through Buffer.

When using the Udp component, using Udp.Send or Udp.Receive will return a Datagram object. The data sent/received is available through Datagram.Buffer.

When using other PowerTCP components, a Segment or Datagram object (which one depends on if TCP or UDP is used as the transport protocol) is made available to describe data sent or received, often in a Trace event. The Buffer or Datagram.Buffer property contains the actual data sent or received.

Example

The following example demonstrates connecting to a server while specifying a local interface to use.

[Visual Basic]
' Connect to the server, specifying the local interface to use
Tcp1.Connect("atropos", 13, "192.168.0.83", 8888)

' Since connection was to DAYTIME port (13), simply receive the time
Dim seg As Segment = Tcp1.Receive()

Debug.WriteLine("Time reported by server: " + seg.ToString())

[C#]
// Connect to the server, specifying the local interface to use
tcp1.Connect("atropos", 13, "192.168.0.83", 8888);

// Since connection was to DAYTIME port (13), simply receive the time
Segment seg = tcp1.Receive();

Debug.WriteLine("Time reported by server: " + seg.ToString());

See Also

Segment Class | Dart.PowerTCP.Ftp Namespace


Count Property

Segment.Count Property

The amount of bytes that were sent/received.

[Visual Basic]
Public Property ReadOnly Count As Integer
[C#]
public int Count { get; }
[C++]
public: __property int get_Count();
[JScript]
public function get Count() : int

Property Value

An integer value representing the amount of bytes that were sent/received.

Remarks

When using the Tcp component, using Send or Receive will return a Segment object. The amount of bytes transferred is available through Offset.

When using the Udp component, using Udp.Send or Udp.Receive will return a Datagram object. The amount of bytes transferred is available through Datagram.Offset.

When using other PowerTCP components, a Segment or Datagram object (which one depends on if TCP or UDP is used as the transport protocol) is made available to describe data sent or received, often in a Trace event. The Count or Datagram.Count property contains the amount of bytes transferred.

Example

The following example demonstrates connecting to a server while specifying a local interface to use.

[Visual Basic]
' Connect to the server, specifying the local interface to use
Tcp1.Connect("atropos", 13, "192.168.0.83", 8888)

' Since connection was to DAYTIME port (13), simply receive the time
Dim seg As Segment = Tcp1.Receive()

Debug.WriteLine("Time reported by server: " + seg.ToString())

[C#]
// Connect to the server, specifying the local interface to use
tcp1.Connect("atropos", 13, "192.168.0.83", 8888);

// Since connection was to DAYTIME port (13), simply receive the time
Segment seg = tcp1.Receive();

Debug.WriteLine("Time reported by server: " + seg.ToString());

See Also

Segment Class | Dart.PowerTCP.Ftp Namespace


Offset Property

Segment.Offset Property

The offset into the buffer.

[Visual Basic]
Public Property ReadOnly Offset As Integer
[C#]
public int Offset { get; }
[C++]
public: __property int get_Offset();
[JScript]
public function get Offset() : int

Property Value

An integer representing the offset into the buffer.

Remarks

Use this property to access offset parameter of the Receive and Send methods.

When using the Tcp component, using Send or Receive will return a Segment object. The buffer offset is available through Offset.

When using the Udp component, using Udp.Send or Udp.Receive will return a Datagram object. The buffer offset is available through Datagram.Offset.

Use this property to properly access the data available in Buffer or Datagram.Buffer.

When using other PowerTCP components, a Segment or Datagram object (which one depends on if TCP or UDP is used as the transport protocol) is made available to describe data sent or received, often in a Trace event. The Offset or Datagram.Offset property contains the offset into the buffer.

Example

The following example demonstrates connecting to a server while specifying a local interface to use.

[Visual Basic]
' Connect to the server, specifying the local interface to use
Tcp1.Connect("atropos", 13, "192.168.0.83", 8888)

' Since connection was to DAYTIME port (13), simply receive the time
Dim seg As Segment = Tcp1.Receive()

Debug.WriteLine("Time reported by server: " + seg.ToString())

[C#]
// Connect to the server, specifying the local interface to use
tcp1.Connect("atropos", 13, "192.168.0.83", 8888);

// Since connection was to DAYTIME port (13), simply receive the time
Segment seg = tcp1.Receive();

Debug.WriteLine("Time reported by server: " + seg.ToString());

See Also

Segment Class | Dart.PowerTCP.Ftp Namespace


Sent Property

Segment.Sent Property

Indicates whether the data was sent or received.

[Visual Basic]
Public Property ReadOnly Sent As Boolean
[C#]
public bool Sent { get; }
[C++]
public: __property bool get_Sent();
[JScript]
public function get Sent() : bool

Property Value

true if the data was sent, false otherwise.

Remarks

When using the Tcp component, all data sent or received with Send or Receive will return a Segment object. The Sent property indicates whether data was sent or received. If this property is true, then the Segment object was created because data was sent; false, the Segment object was created because data was received.

When using the Udp component, all data sent or received with Udp.Send or Udp.Receive will return a Datagram object. The Datagram.Sent property indicates whether data was sent or received. If this property is true, then the Datagram object was created because data was sent; false, the Datagram object was created because data was received.

When using other PowerTCP components, a Segment or Datagram object is made available to describe data sent or received, often in a Trace event. Access the Sent property to determine if the Trace event was raised because data was sent or received.

Example

The following example demonstrates connecting to a server while specifying a local interface to use.

[Visual Basic]
' Connect to the server, specifying the local interface to use
Tcp1.Connect("atropos", 13, "192.168.0.83", 8888)

' Since connection was to DAYTIME port (13), simply receive the time
Dim seg As Segment = Tcp1.Receive()

Debug.WriteLine("Time reported by server: " + seg.ToString())

[C#]
// Connect to the server, specifying the local interface to use
tcp1.Connect("atropos", 13, "192.168.0.83", 8888);

// Since connection was to DAYTIME port (13), simply receive the time
Segment seg = tcp1.Receive();

Debug.WriteLine("Time reported by server: " + seg.ToString());

See Also

Segment Class | Dart.PowerTCP.Ftp Namespace


SocketFlags Property

Segment.SocketFlags Property

Gets the SocketFlags associated with the Segment.

[Visual Basic]
Public Property ReadOnly SocketFlags As SocketFlags
[C#]
public SocketFlags SocketFlags { get; }
[C++]
public: __property SocketFlags get_SocketFlags();
[JScript]
public function get SocketFlags() : SocketFlags

Property Value

The SocketFlags associated with the Segment.

Remarks

Indicates the flags used when Send or Receive are used. See the SocketFlags topic within the MSDN documentation for more info.

See Also

Segment Class | Dart.PowerTCP.Ftp Namespace


Segment Methods

The methods of the Segment class are listed below. For a complete list of Segment class members, see the Segment Members topic.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString | Overridden. Returns all data sent/received as a string.

See Also

Segment Class | Dart.PowerTCP.Ftp Namespace


ToString Method

Segment.ToString Method

Returns all data sent/received as a string.

[Visual Basic]
Overrides Public Function ToString() As String
[C#]
public override string ToString();
[C++]
public: String* ToString();
[JScript]
public override function ToString(): String;

Return Value

A string representing all data sent or received.

Example

The following example demonstrates connecting to a server while specifying a local interface to use.

[Visual Basic]
' Connect to the server, specifying the local interface to use
Tcp1.Connect("atropos", 13, "192.168.0.83", 8888)

' Since connection was to DAYTIME port (13), simply receive the time
Dim seg As Segment = Tcp1.Receive()

Debug.WriteLine("Time reported by server: " + seg.ToString())

[C#]
// Connect to the server, specifying the local interface to use
tcp1.Connect("atropos", 13, "192.168.0.83", 8888);

// Since connection was to DAYTIME port (13), simply receive the time
Segment seg = tcp1.Receive();

Debug.WriteLine("Time reported by server: " + seg.ToString());

See Also

Segment Class | Dart.PowerTCP.Ftp Namespace


SegmentedStream Class

Used to provide advanced reading/writing capabilities to Stream-based objects.

For a list of all members of this type, see SegmentedStream Members.

System.Object
System.MarshalByRefObject
System.IO.Stream
Dart.PowerTCP.Ftp.EnhancedStream
Dart.PowerTCP.Ftp.PipeStream
Dart.PowerTCP.Ftp.SegmentedStream

[Visual Basic]
Public Class SegmentedStream
    Inherits PipeStream
[C#]
public class SegmentedStream : PipeStream
[C++]
public __gc class SegmentedStream : public PipeStream
[JScript]
public class SegmentedStream extends PipeStream

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

SegmentedStream provides a way to read/write a segment of bytes to/from a backing store. To improve performance, SegmentedStream buffers reads and writes to the underlying stream and provides asynchronous read and write capability.

The SegmentedStream object is used within PowerTCP to read/write network data. The following examples further illustrate how SegmentedStream is used:

  • When using the Tcp or Telnet components, the TCP stream is exposed through the Object.Stream property (which is a SegmentedStream object). To write or read directly to the TCP stream, call Object.Stream.Read or Object.Stream.Write.
  • The SegmentedStream object is also used to access the TCP stream when using other Internet components as well. For example, when using the Ftp component, Get or Put can be called, making accessible a SegmentedStream object. Read and Write can then be called to read and write directly to the data connection.

Example

The following example demonstrates connecting implementing the SMTP protocol using the Tcp component's stream interface to send a simple message.

[Visual Basic]
' The following code assumes that good responses are always received from
' the server. More robust code should check each response and handle appropriately.

' Connect to SMTP port
Tcp1.Connect("mail", 25)

' Send the EHLO command
Tcp1.Stream.Write("EHLO myserver\r\n")

' Get response from the server
Dim s As String = Tcp1.Stream.Read()

' Send MAIL FROM command
Tcp1.Stream.Write("MAIL FROM: test@dart.com" + vbCrLf)

' Get response from the server
s = Tcp1.Stream.Read()

' Send RCPT TO command
Tcp1.Stream.Write("RCPT TO: cranford@dart.com" + vbCrLf)

' Get response from the server
s = Tcp1.Stream.Read()

' Send DATA command
Tcp1.Stream.Write("DATA" + vbCrLf)

' Get response from the server
s = Tcp1.Stream.Read()

' Send DATA
Tcp1.Stream.Write("Test Message" + vbCrLf + "." + vbCrLf)

' Receive response from the server
s = Tcp1.Stream.Read()

' Write output
Debug.WriteLine("Operation complete. The following information")
Debug.WriteLine("was reported by the server:")
Debug.WriteLine(s)

[C#]
// The following code assumes that good responses are always received from
// the server. More robust code should check each response and handle appropriately.

// Connect to SMTP port
tcp1.Connect("mail", 25);

// Send the EHLO command
tcp1.Stream.Write("EHLO myserver\r\n");

// Get response from the server
string s = tcp1.Stream.Read();

// Send MAIL FROM command
tcp1.Stream.Write("MAIL FROM: test@dart.com\r\n");

// Get response from the server
s = tcp1.Stream.Read();

// Send RCPT TO command
tcp1.Stream.Write("RCPT TO: cranford@dart.com\r\n");

// Get response from the server
s = tcp1.Stream.Read();

// Send DATA command
tcp1.Stream.Write("DATA\r\n");

// Get response from the server
s = tcp1.Stream.Read();

// Send DATA
tcp1.Stream.Write("Test Message\r\n.\r\n");

// Receive response from the server
s = tcp1.Stream.Read();

// Write output
Debug.WriteLine("Operation complete. The following information");
Debug.WriteLine("was reported by the server:");
Debug.WriteLine(s);

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

SegmentedStream Members | Dart.PowerTCP.Ftp Namespace


SegmentedStream Members

SegmentedStream overview

Public Instance Constructors

SegmentedStream Overloaded. Initializes a new instance of the SegmentedStream class.

Public Instance Properties

Available | Gets the amount of bytes of data that has been received from the network and is available to be read.
CanRead | Overridden. Indicates that data can be read from the stream.
CanSeek | Overridden. Indicates that the stream can seek a specific location in the stream.
CanWrite | Overridden. Indicates that data can be written to the stream.
Charset (inherited from EnhancedStream) | Gets and sets the character set used for string/byte array conversions.
CoreStream (inherited from PipeStream) | The internal stream to which all buffered reads/writes are being made.
Encoding (inherited from EnhancedStream) | Gets or sets the type of encoding to use.
Length (inherited from PipeStream) | Gets the length in bytes of the stream.
Position | Overridden. Gets or sets the position in the stream.

Public Instance Methods

BeginRead | Overloaded. Begins an asynchronous read from the stream that completes when the provided delimiter is found, count bytes have been read, or end of stream is reached.
BeginWrite (inherited from Stream) | Begins an asynchronous write operation.
Close | Overridden. Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose (inherited from EnhancedStream) | Releases all resources associated with the object.
EndRead | Overridden. Ends a pending asynchronous BeginRead request.
EndWrite (inherited from Stream) | Ends an asynchronous write operation.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
Flush | Overridden. Updates the underlying data source or repository with the current state of the buffer and then clears the buffer unless the internal Stream requires flushing..
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
Read | Overloaded. Read data from the stream into a byte array.
Read (inherited from EnhancedStream) | Overloaded. Reads at least one byte of data from the Stream and copies it into the provided buffer.
ReadByte (inherited from Stream) | Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
Save (inherited from EnhancedStream) | Overloaded. Saves the data in the stream to the file specified by fileName.
Seek | Overridden. Seeks a specific position in the stream.
SetLength | Overridden. Sets the length of the Stream. This method always throws a NotSupportedException.
ToArray (inherited from EnhancedStream) | Returns the byte array representation of the Stream data.
ToString (inherited from EnhancedStream) | Overridden. Returns the string representation of the Stream data.
Write | Overloaded. Writes data to the stream.
Write (inherited from EnhancedStream) | Overloaded. Writes a sequence of bytes to the Stream and returns when the operation is complete.
WriteByte (inherited from Stream) | Writes a byte to the current position in the stream and advances the position within the stream by one byte.
WriteTo (inherited from EnhancedStream) | Overloaded. Writes all of the data contained in this Stream to a destination Stream.

Public Instance Events

Trace

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


SegmentedStream Constructor

Initializes a new instance of the SegmentedStream class for the specified stream object.

Overload List

Initializes a new instance of the SegmentedStream class for the specified stream object.

[Visual Basic] Public Sub New(ByVal Stream)
[C#] public SegmentedStream(Stream);
[C++] public: SegmentedStream(Stream*);
[JScript] public function SegmentedStream(Stream);

Initializes a new instance of the SegmentedStream class for the specified stream object.

[Visual Basic] Public Sub New(ByVal Stream,ByVal Encoding)
[C#] public SegmentedStream(Stream,Encoding);
[C++] public: SegmentedStream(Stream*,Encoding*);
[JScript] public function SegmentedStream(Stream,Encoding);

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


SegmentedStream Constructor (Stream)

Initializes a new instance of the SegmentedStream class for the specified stream object.

[Visual Basic]
Public Sub New( _
   ByVal stream As Stream _
)
[C#]
public SegmentedStream(
   Stream stream
);
[C++]
public: SegmentedStream(
   Stream* stream
);
[JScript]
public function SegmentedStream(
   Stream stream
);

Parameters

stream
The source stream to Read/Write.

Remarks

Although any type of stream can be used to initialize a SegmentedStream (a FileStream or a MemoryStream, for example) the intended use is to initialize a SegmentedStream with some form of network stream (such as a TcpStream). You will not usually need to create a SegmentedStream object, as the SegmentedStream object currently accessing the TCP stream is made accessible (either as a property of the component, or as an object accessible in an event or returned from a method). For example, if you wish to send/receive data to/from a server using a stream interface, simply use Connect to connect to the server and call Tcp.Stream.Write or Tcp.Stream.Read to send/receive data.

Example

The following example demonstrates initializing a new instance of a SegmentedStream object to a TcpStream.

[Visual Basic]
' Connect to a server
Tcp1.Connect("atropos", 7)

' Initialize a SegmentedStream to the NetworkStream
Dim sstream As New SegmentedStream(new TcpStream(Tcp1))

' Send data
sstream.Write("hello")

' Receive data
Dim s As String = sstream.Read()

[C#]
// Connect to a server
tcp1.Connect("atropos", 7);

// Initialize a SegmentedStream to the NetworkStream
SegmentedStream sstream = new SegmentedStream(new TcpStream(tcp1));

// Send data
sstream.Write("hello");

// Receive data
string s = sstream.Read();

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream Constructor Overload List


SegmentedStream Constructor (Stream, Encoding)

Initializes a new instance of the SegmentedStream class for the specified stream object.

[Visual Basic]
Public Sub New( _
   ByVal stream As Stream, _
   ByVal encoding As Encoding _
)
[C#]
public SegmentedStream(
   Stream stream,
   Encoding encoding
);
[C++]
public: SegmentedStream(
   Stream* stream,
   Encoding* encoding
);
[JScript]
public function SegmentedStream(
   Stream stream,
   Encoding encoding
);

Parameters

stream
The source stream to Read/Write.
encoding
The encoding type to use when working with strings.

Remarks

Although any type of stream can be used to initialize a SegmentedStream (a FileStream or a MemoryStream, for example) the intended use is to initialize a SegmentedStream with some form of network stream (such as a TcpStream). You will not usually need to create a SegmentedStream object, as the SegmentedStream object currently accessing the TCP stream is made accessible (either as a property of the component, or as an object accessible in an event or returned from a method). For example, if you wish to send/receive data to/from a server using a stream interface, simply use Connect to connect to the server and call Tcp.Stream.Write or Tcp.Stream.Read to send/receive data.

Example

The following example demonstrates initializing a new instance of a SegmentedStream object to a TcpStream.

[Visual Basic]
' Connect to a server
Tcp1.Connect("atropos", 7)

' Initialize a SegmentedStream to the NetworkStream
Dim sstream As New SegmentedStream(new TcpStream(Tcp1))

' Send data
sstream.Write("hello")

' Receive data
Dim s As String = sstream.Read()

[C#]
// Connect to a server
tcp1.Connect("atropos", 7);

// Initialize a SegmentedStream to the NetworkStream
SegmentedStream sstream = new SegmentedStream(new TcpStream(tcp1));

// Send data
sstream.Write("hello");

// Receive data
string s = sstream.Read();

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream Constructor Overload List


SegmentedStream Properties

The properties of the SegmentedStream class are listed below. For a complete list of SegmentedStream class members, see the SegmentedStream Members topic.

Public Instance Properties

Available | Gets the amount of bytes of data that has been received from the network and is available to be read.
CanRead | Overridden. Indicates that data can be read from the stream.
CanSeek | Overridden. Indicates that the stream can seek a specific location in the stream.
CanWrite | Overridden. Indicates that data can be written to the stream.
Charset (inherited from EnhancedStream) | Gets and sets the character set used for string/byte array conversions.
CoreStream (inherited from PipeStream) | The internal stream to which all buffered reads/writes are being made.
Encoding (inherited from EnhancedStream) | Gets or sets the type of encoding to use.
Length (inherited from PipeStream) | Gets the length in bytes of the stream.
Position | Overridden. Gets or sets the position in the stream.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


Available Property

SegmentedStream.Available Property

Gets the amount of bytes of data that has been received from the network and is available to be read.

[Visual Basic]
Public Property ReadOnly Available As Integer
[C#]
public int Available { get; }
[C++]
public: __property int get_Available();
[JScript]
public function get Available() : int

Remarks

A positive number indicates that data has been received from the network. Call Read to access this data. 0 indicates that no data is available to be read.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


CanRead Property

SegmentedStream.CanRead Property

Indicates that data can be read from the stream.

[Visual Basic]
Overrides Public Property ReadOnly CanRead As Boolean
[C#]
public override bool CanRead { get; }
[C++]
public: __property bool get_CanRead();
[JScript]
public override function get CanRead() : bool

Remarks

If the stream is closed, this property returns false.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


CanSeek Property

SegmentedStream.CanSeek Property

Indicates that the stream can seek a specific location in the stream.

[Visual Basic]
Overrides Public Property ReadOnly CanSeek As Boolean
[C#]
public override bool CanSeek { get; }
[C++]
public: __property bool get_CanSeek();
[JScript]
public override function get CanSeek() : bool

Remarks

This property always returns false.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


CanWrite Property

SegmentedStream.CanWrite Property

Indicates that data can be written to the stream.

[Visual Basic]
Overrides Public Property ReadOnly CanWrite As Boolean
[C#]
public override bool CanWrite { get; }
[C++]
public: __property bool get_CanWrite();
[JScript]
public override function get CanWrite() : bool

Remarks

If the stream is closed, this property returns false.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


Position Property

SegmentedStream.Position Property

Gets or sets the position in the stream.

[Visual Basic]
Overrides Public Property Position As Long
[C#]
public override long Position { get; set; }
[C++]
public: __property __int64 get_Position();
public: __property void set_Position(__int64 );
[JScript]
public override function get Position() : long
public override function set Position(long);

Remarks

Returns the value of CoreStream.Position. If a Tcp socket is the source of the stream, then a NotSupportedException is thrown.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


SegmentedStream Methods

The methods of the SegmentedStream class are listed below. For a complete list of SegmentedStream class members, see the SegmentedStream Members topic.

Public Instance Methods

BeginRead | Overloaded. Begins an asynchronous read from the stream that completes when the provided delimiter is found, count bytes have been read, or end of stream is reached.
BeginWrite (inherited from Stream) | Begins an asynchronous write operation.
Close | Overridden. Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose (inherited from EnhancedStream) | Releases all resources associated with the object.
EndRead | Overridden. Ends a pending asynchronous BeginRead request.
EndWrite (inherited from Stream) | Ends an asynchronous write operation.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
Flush | Overridden. Updates the underlying data source or repository with the current state of the buffer and then clears the buffer unless the internal Stream requires flushing..
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
Read | Overloaded. Read data from the stream into a byte array.
Read (inherited from EnhancedStream) | Overloaded. Reads at least one byte of data from the Stream and copies it into the provided buffer.
ReadByte (inherited from Stream) | Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
Save (inherited from EnhancedStream) | Overloaded. Saves the data in the stream to the file specified by fileName.
Seek | Overridden. Seeks a specific position in the stream.
SetLength | Overridden. Sets the length of the Stream. This method always throws a NotSupportedException.
ToArray (inherited from EnhancedStream) | Returns the byte array representation of the Stream data.
ToString (inherited from EnhancedStream) | Overridden. Returns the string representation of the Stream data.
Write | Overloaded. Writes data to the stream.
Write (inherited from EnhancedStream) | Overloaded. Writes a sequence of bytes to the Stream and returns when the operation is complete.
WriteByte (inherited from Stream) | Writes a byte to the current position in the stream and advances the position within the stream by one byte.
WriteTo (inherited from EnhancedStream) | Overloaded. Writes all of the data contained in this Stream to a destination Stream.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


BeginRead Method

SegmentedStream.BeginRead Method

Begins an asynchronous read from the stream that completes when the provided delimiter is found, count bytes have been read, or end of stream is reached.

Overload List

Begins an asynchronous read from the stream that completes when the provided delimiter is found, count bytes have been read, or end of stream is reached.

[Visual Basic] Overridable OverloadsPublic Function BeginRead(ByVal Byte(),ByVal Byte(),ByVal Integer,ByVal Integer,ByRef Boolean,ByVal AsyncCallback,ByVal Object) As IAsyncResult
[C#] public virtual IAsyncResult BeginRead(byte[],byte[],int,int,ref bool,AsyncCallback,object);
[C++] public: virtual IAsyncResult* BeginRead(char __gc[],char __gc[],int,int,* bool,AsyncCallback*,Object*);
[JScript] public virtual function BeginRead(Byte[],Byte[],int,int,bool,AsyncCallback,Object): IAsyncResult;

Begins an asynchronous read from the stream that complete when at least one byte is read. This operation reads at most count bytes.

[Visual Basic] Overrides OverloadsPublic Function BeginRead(ByVal Byte(),ByVal Integer,ByVal Integer,ByVal AsyncCallback,ByVal Object) As IAsyncResult
[C#] public override IAsyncResult BeginRead(byte[],int,int,AsyncCallback,object);
[C++] public: IAsyncResult* BeginRead(char __gc[],int,int,AsyncCallback*,Object*);
[JScript] public override function BeginRead(Byte[],int,int,AsyncCallback,Object): IAsyncResult;

Begins an asynchronous read from the stream that completes when the provided buffer is completely full, the number of bytes requested is read, or end of stream is reached.

[Visual Basic] Overridable OverloadsPublic Function BeginRead(ByVal Byte(),ByVal Integer,ByVal Integer,ByVal Boolean,ByVal AsyncCallback,ByVal Object) As IAsyncResult
[C#] public virtual IAsyncResult BeginRead(byte[],int,int,bool,AsyncCallback,object);
[C++] public: virtual IAsyncResult* BeginRead(char __gc[],int,int,bool,AsyncCallback*,Object*);
[JScript] public virtual function BeginRead(Byte[],int,int,bool,AsyncCallback,Object): IAsyncResult;

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


BeginRead Method (Byte[], Byte[], Int32, Int32, Boolean, AsyncCallback, Object)

SegmentedStream.BeginRead Method (Byte[], Byte[], Int32, Int32, Boolean, AsyncCallback, Object)

Begins an asynchronous read from the stream that completes when the provided delimiter is found, count bytes have been read, or end of stream is reached.

[Visual Basic]
Overridable  OverloadsPublic Function BeginRead( _
   ByVal buffer As Byte(), _
   ByVal delimiter As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer, _
   ByRef found As Boolean, _
   ByVal callback As AsyncCallback, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public virtual IAsyncResult BeginRead(
   byte[] buffer,
   byte[] delimiter,
   int offset,
   int count,
   ref bool found,
   AsyncCallback callback,
   object state
);
[C++]
public: virtual IAsyncResult* BeginRead(
   char buffer __gc[],
   char delimiter __gc[],
   int offset,
   int count,
   * bool found,
   AsyncCallback* callback,
   Object* state
);
[JScript]
public virtual function BeginRead(
   Byte[] buffer,
   Byte[] delimiter,
   int offset,
   int count,
   bool found,
   AsyncCallback callback,
   Object state
): IAsyncResult;

Parameters

buffer
The storage location for the received data.
delimiter
The token that is used to determine a segment was read.
offset
The zero-based position in the buffer at which to store the received data.
count
The maximum number of bytes to read.
found
callback
The AsyncCallback delegate to be called when the operation is complete.
state
An object containing state information for this operation.

Return Value

An IAsyncResult representing the asynchronous operation. To determine how many bytes were read, you must pass this IAsyncResult to the EndRead method of the stream. This should be done within your AsyncCallback event handler.

Remarks

The purpose of this method is to provide a convenient way to read a variable-length record from the stream. The EndRead method should be called when your AsyncCallback delegate is raised.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Readable.
ArgumentNullException | Thrown when the buffer, delimiter or callback is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when count is less than or equal to zero.
ArgumentException | Thrown when the (offset + count) > buffer.Length, or delimiter.Length == 0, or delimiter.length > count.

Example

The following example demonstrates asynchronously reading from the server using the stream interface. This involves creating a callback method in which the response is handled. If you would like to use fully asynchronous methods with events already implemented, try the low-level interface (Tcp.BeginRead & Tcp.BeginWrite).

[Visual Basic]

[C#]
private void AsynchronousReadTest()
{
   // Connect to the server
   tcp1.Connect("atropos", 13);

   // DAYTIME protocol (port 13) sends data and closes, receive data.
   // This demonstrates receiving data asynchronously using the stream interface.

   // data buffer is a global variable
   databuffer = new byte[tcp1.ReceiveBufferSize];

   // Begin the asynchronous Read operation.
   tcp1.Stream.BeginRead(databuffer, 0, tcp1.ReceiveBufferSize, new System.AsyncCallback(MyCallback), null);
}

private void MyCallback(System.IAsyncResult ar)
{
   // End pending asynchronous request.
   if(ar.IsCompleted)
      tcp1.Stream.EndRead(ar);

   // Write result
   Debug.WriteLine(System.Text.Encoding.Default.GetString(databuffer));
}

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.BeginRead Overload List


BeginRead Method (Byte[], Int32, Int32, AsyncCallback, Object)

SegmentedStream.BeginRead Method (Byte[], Int32, Int32, AsyncCallback, Object)

Begins an asynchronous read from the stream that complete when at least one byte is read. This operation reads at most count bytes.

[Visual Basic]
Overrides  OverloadsPublic Function BeginRead( _
   ByVal buffer As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer, _
   ByVal callback As AsyncCallback, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public override IAsyncResult BeginRead(
   byte[] buffer,
   int offset,
   int count,
   AsyncCallback callback,
   object state
);
[C++]
public: IAsyncResult* BeginRead(
   char buffer __gc[],
   int offset,
   int count,
   AsyncCallback* callback,
   Object* state
);
[JScript]
public override function BeginRead(
   Byte[] buffer,
   int offset,
   int count,
   AsyncCallback callback,
   Object state
): IAsyncResult;

Parameters

buffer
The storage location for the received data.
offset
The zero-based position in the buffer at which to store the received data.
count
The maximum number of bytes to read.
callback
The AsyncCallback delegate to be called when the operation is complete.
state
An object containing state information for this operation.

Return Value

An IAsyncResult representing the asynchronous operation. To determine how many bytes were read, you must pass this IAsyncResult to the EndRead method of the stream. This should be done within your AsyncCallback event handler.

Remarks

This is the standard method to use when reading a stream asynchronously. If a fixed-length record buffer is being read, use the overloaded Read() method that includes the 'bool fill' parameter. If a variable-length record segment is being read, use the overloaded Read() method that includes the 'byte[] delimiter' parameter.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Readable.
ArgumentNullException | Thrown when the buffer or callback is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when count is less than or equal to zero.
ArgumentException | Thrown when the (offset + count) > buffer.Length.

Example

The following example demonstrates asynchronously reading from the server using the stream interface. This involves creating a callback method in which the response is handled. If you would like to use fully asynchronous methods with events already implemented, try the low-level interface (Tcp.BeginRead & Tcp.BeginWrite).

[Visual Basic]

[C#]
private void AsynchronousReadTest()
{
   // Connect to the server
   tcp1.Connect("atropos", 13);

   // DAYTIME protocol (port 13) sends data and closes, receive data.
   // This demonstrates receiving data asynchronously using the stream interface.

   // data buffer is a global variable
   databuffer = new byte[tcp1.ReceiveBufferSize];

   // Begin the asynchronous Read operation.
   tcp1.Stream.BeginRead(databuffer, 0, tcp1.ReceiveBufferSize, new System.AsyncCallback(MyCallback), null);
}

private void MyCallback(System.IAsyncResult ar)
{
   // End pending asynchronous request.
   if(ar.IsCompleted)
      tcp1.Stream.EndRead(ar);

   // Write result
   Debug.WriteLine(System.Text.Encoding.Default.GetString(databuffer));
}

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.BeginRead Overload List


BeginRead Method (Byte[], Int32, Int32, Boolean, AsyncCallback, Object)

SegmentedStream.BeginRead Method (Byte[], Int32, Int32, Boolean, AsyncCallback, Object)

Begins an asynchronous read from the stream that completes when the provided buffer is completely full, the number of bytes requested is read, or end of stream is reached.

[Visual Basic]
Overridable  OverloadsPublic Function BeginRead( _
   ByVal buffer As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer, _
   ByVal fill As Boolean, _
   ByVal callback As AsyncCallback, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public virtual IAsyncResult BeginRead(
   byte[] buffer,
   int offset,
   int count,
   bool fill,
   AsyncCallback callback,
   object state
);
[C++]
public: virtual IAsyncResult* BeginRead(
   char buffer __gc[],
   int offset,
   int count,
   bool fill,
   AsyncCallback* callback,
   Object* state
);
[JScript]
public virtual function BeginRead(
   Byte[] buffer,
   int offset,
   int count,
   bool fill,
   AsyncCallback callback,
   Object state
): IAsyncResult;

Parameters

buffer
The storage location for the received data.
offset
The zero-based position in the buffer at which to store the received data.
count
The exact number of bytes to read.
fill
Always true, use this version of BeginRead to completely fill the buffer
callback
The AsyncCallback delegate to be called when the operation is complete.
state
An object containing state information for this operation.

Return Value

An IAsyncResult representing the asynchronous operation. To determine how many bytes were read, you must pass this IAsyncResult to the EndRead method of the stream. This should be done within your AsyncCallback event handler.

Remarks

The purpose of this method is to provide a convenient way to read a fixed-length record from the stream. The EndRead method should be called when your AsyncCallback delegate is raised.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Readable.
ArgumentNullException | Thrown when the buffer or callback is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when count is less than or equal to zero.
ArgumentException | Thrown when the (offset + count) > (buffer.Length).

Example

The following example demonstrates asynchronously reading from the server using the stream interface. This involves creating a callback method in which the response is handled. If you would like to use fully asynchronous methods with events already implemented, try the low-level interface (Tcp.BeginRead & Tcp.BeginWrite).

[Visual Basic]

[C#]
private void AsynchronousReadTest()
{
   // Connect to the server
   tcp1.Connect("atropos", 13);

   // DAYTIME protocol (port 13) sends data and closes, receive data.
   // This demonstrates receiving data asynchronously using the stream interface.

   // data buffer is a global variable
   databuffer = new byte[tcp1.ReceiveBufferSize];

   // Begin the asynchronous Read operation.
   tcp1.Stream.BeginRead(databuffer, 0, tcp1.ReceiveBufferSize, new System.AsyncCallback(MyCallback), null);
}

private void MyCallback(System.IAsyncResult ar)
{
   // End pending asynchronous request.
   if(ar.IsCompleted)
      tcp1.Stream.EndRead(ar);

   // Write result
   Debug.WriteLine(System.Text.Encoding.Default.GetString(databuffer));
}

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.BeginRead Overload List


Close Method

SegmentedStream.Close Method

Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.

[Visual Basic]
Overrides Public Sub Close()
[C#]
public override void Close();
[C++]
public: void Close();
[JScript]
public override function Close();

Remarks

This method closes the SegmentedStream and frees resources associated with the SegmentedStream.

Exceptions

Exception Type | Condition
ObjectDisposedException | A member was accessed while the stream was closed.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


EndRead Method

SegmentedStream.EndRead Method

Ends a pending asynchronous BeginRead request.

[Visual Basic]
Overrides Public Function EndRead( _
   ByVal ar As IAsyncResult _
) As Integer
[C#]
public override int EndRead(
   IAsyncResult ar
);
[C++]
public: int EndRead(
   IAsyncResult* ar
);
[JScript]
public override function EndRead(
   IAsyncResult ar
): int;

Parameters

ar
Reference to the pending asynchronous request that is returned from BeginRead().

Return Value

The number of bytes read from the stream and copied into the user's buffer. Will return 0 at the end of the stream to indicate the stream has closed and all data has been read.

Remarks

You will normally call this method from within your AsyncCallback event handler to complete your asynchronous read request, but it can be called anytime to cancel an outstanding request.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Readable.
ArgumentNullException | asyncResult is a null reference.
ArgumentException | asyncResult is not a valid reference.
EndOfStreamException | The end of the stream was found before the required byte count was received, or the end of the stream was found before the delimiter was found.
InternalBufferOverflowException | The delimiter was not found within the maximum number of bytes (count) specified.

Example

The following example demonstrates asynchronously reading from the server using the stream interface. This involves creating a callback method in which the response is handled. If you would like to use fully asynchronous methods with events already implemented, try the low-level interface (Tcp.BeginRead & Tcp.BeginWrite).

[Visual Basic]

[C#]
private void AsynchronousReadTest()
{
   // Connect to the server
   tcp1.Connect("atropos", 13);

   // DAYTIME protocol (port 13) sends data and closes, receive data.
   // This demonstrates receiving data asynchronously using the stream interface.

   // data buffer is a global variable
   databuffer = new byte[tcp1.ReceiveBufferSize];

   // Begin the asynchronous Read operation.
   tcp1.Stream.BeginRead(databuffer, 0, tcp1.ReceiveBufferSize, new System.AsyncCallback(MyCallback), null);
}

private void MyCallback(System.IAsyncResult ar)
{
   // End pending asynchronous request.
   if(ar.IsCompleted)
      tcp1.Stream.EndRead(ar);

   // Write result
   Debug.WriteLine(System.Text.Encoding.Default.GetString(databuffer));
}

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


Flush Method

SegmentedStream.Flush Method

Updates the underlying data source or repository with the current state of the buffer and then clears the buffer unless the internal Stream requires flushing..

[Visual Basic]
Overrides Public Sub Flush()
[C#]
public override void Flush();
[C++]
public: void Flush();
[JScript]
public override function Flush();

Remarks

All the read and write methods of SegmentedStream automatically maintain the buffer, so there is no need to invoke Flush when switching back and forth between reading and writing.

Example

The following example demonstrates writing data until a delimiter is reached.

[Visual Basic]
' Create test data
Dim buffer As Byte() = System.Text.Encoding.Default.GetBytes("acbdefghijklmnopqrstuvwxyz" + vbCrLf)
Dim delimiter As Byte() = System.Text.Encoding.Default.GetBytes("ghi")

Dim offset As Integer = 0
Dim count As Integer = buffer.Length

' Connect to echo port
Tcp1.Connect("atropos", 7)

' Send data until the delimiter is reached.
Dim found As Boolean = Tcp1.Stream.Write(buffer, delimiter, offset, count)

' Flush the rest of the data
Tcp1.Stream.Flush()

' Recieve data.
Dim s As String = Tcp1.Stream.Read()

Debug.WriteLine(s)

'* Output
'* -----------------------
'* abcdef

[C#]
// Create test data
byte[] buffer = System.Text.Encoding.Default.GetBytes("acbdefghijklmnopqrstuvwxyz\r\n");
byte[] delimiter = System.Text.Encoding.Default.GetBytes("ghi");
int offset = 0;
int count = buffer.Length;

// Connect to echo port
tcp1.Connect("atropos", 7);

// Send data until the delimiter is reached.
bool found = tcp1.Stream.Write(buffer, delimiter, ref offset, ref count);

// Flush the rest of the data
tcp1.Stream.Flush();

// Recieve data.
string s = tcp1.Stream.Read();

Debug.WriteLine(s);

/* Output
 * -----------------------
 * abcdef
 */

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


Read Method

SegmentedStream.Read Method

Read data from the stream into a string.

Overload List

Read data from the stream into a string.

[Visual Basic] Public Function Read() As String
[C#] public string Read();
[C++] public: String* Read();
[JScript] public function Read(): String;

Reads at least one byte of data from the Stream and copies it into the provided buffer.
Inherited from EnhancedStream.

[Visual Basic] Public Function Read(ByVal Byte()) As Integer
[C#] public int Read(byte[]);
[C++] public: int Read(char __gc[]);
[JScript] public function Read(Byte[]): int;

Read data from the stream until a byte array is filled.

[Visual Basic] Public Function Read(ByVal Byte(),ByVal Boolean) As Integer
[C#] public int Read(byte[],bool);
[C++] public: int Read(char __gc[],bool);
[JScript] public function Read(Byte[],bool): int;

Read data from the stream until a delimiter is reached.

[Visual Basic] Public Function Read(ByVal Byte(),ByVal Byte(),ByRef Boolean) As Integer
[C#] public int Read(byte[],byte[],ref bool);
[C++] public: int Read(char __gc[],char __gc[],* bool);
[JScript] public function Read(Byte[],Byte[],bool): int;

Read data from the stream.

[Visual Basic] Public Function Read(ByVal Byte(),ByVal Byte(),ByVal Integer,ByVal Integer,ByRef Boolean) As Integer
[C#] public int Read(byte[],byte[],int,int,ref bool);
[C++] public: int Read(char __gc[],char __gc[],int,int,* bool);
[JScript] public function Read(Byte[],Byte[],int,int,bool): int;

Read data from the stream until one of the specified delimiters is found.

[Visual Basic] Public Function Read(ByVal Byte(),ByVal ArrayList,ByVal Integer,ByVal Integer,ByRef Boolean) As Integer
[C#] public int Read(byte[],ArrayList,int,int,ref bool);
[C++] public: int Read(char __gc[],ArrayList*,int,int,* bool);
[JScript] public function Read(Byte[],ArrayList,int,int,bool): int;

Read data from the stream into a byte array.

[Visual Basic] Overrides OverloadsPublic Function Read(ByVal Byte(),ByVal Integer,ByVal Integer) As Integer
[C#] public override int Read(byte[],int,int);
[C++] public: int Read(char __gc[],int,int);
[JScript] public override function Read(Byte[],int,int): int;

Read data from the stream until a byte array is filled.

[Visual Basic] Public Function Read(ByVal Byte(),ByVal Integer,ByVal Integer,ByVal Boolean) As Integer
[C#] public int Read(byte[],int,int,bool);
[C++] public: int Read(char __gc[],int,int,bool);
[JScript] public function Read(Byte[],int,int,bool): int;

Read data from the stream into a string.

[Visual Basic] Public Function Read(ByVal Integer) As String
[C#] public string Read(int);
[C++] public: String* Read(int);
[JScript] public function Read(int): String;

Reads stream, accumulating string data, until delimiter is reached or timeout is reached.

[Visual Basic] Public Function Read(ByVal String) As String
[C#] public string Read(string);
[C++] public: String* Read(String*);
[JScript] public function Read(String): String;

Read data from the stream until a delimiter is reached.

[Visual Basic] Public Function Read(ByVal String,ByVal Integer,ByRef Boolean) As String
[C#] public string Read(string,int,ref bool);
[C++] public: String* Read(String*,int,* bool);
[JScript] public function Read(String,int,bool): String;

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


Read Method ()

SegmentedStream.Read Method ()

Read data from the stream into a string.

[Visual Basic]
Public Function Read() As String
[C#]
public string Read();
[C++]
public: String* Read();
[JScript]
public function Read(): String;

Return Value

A string containing the data read from the stream.

Remarks

This method will block (for ReceiveTimeout) until at least 1 byte is available for reading, or the connection is closed by the server, in which case an empty string is returned. The Charset property is used to convert from bytes to unicode characters, which allows unicode characters to be passed over the network.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Readable.
ArgumentNullException | Thrown when the receiving buffer is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when count is less than or equal to zero.
ArgumentException | Thrown when (offset + count) > buffer.Length.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Read Overload List


Read Method (Byte[], Boolean)

SegmentedStream.Read Method (Byte[], Boolean)

Read data from the stream until a byte array is filled.

[Visual Basic]
Public Function Read( _
   ByVal buffer As Byte(), _
   ByVal fill As Boolean _
) As Integer
[C#]
public int Read(
   byte[] buffer,
   bool fill
);
[C++]
public: int Read(
   char buffer __gc[],
   bool fill
);
[JScript]
public function Read(
   Byte[] buffer,
   bool fill
): int;

Parameters

buffer
The storage location for the received data.
fill
Always true, use this version of Read to completely fill the buffer

Return Value

The total number of bytes read into the buffer. This will either be the value of the count parameter, or zero if the stream has closed.

Remarks

This method reads data from the stream and returns when the provided buffer is completely full or end of stream is reached. This method is a good way to read fixed-length data. An example of this is with HTTP chunking, which occurs when the server breaks up the HTTP response into fixed-size chunks. Each chunk is preceded with a hexidecimal value notifying the receiver of the size of the data chunk to follow. Initialize a byte array to this value, then call this method to fill the byte array.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Readable.
ArgumentNullException | Thrown when the receiving buffer is null.
EndOfStreamException | Thrown when the end of the stream was found before the required byte count was received. When this occurs the Available property will indicate how much data may be read and the CanRead Property will return true.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Read Overload List


Read Method (Byte[], Byte[], Boolean)

SegmentedStream.Read Method (Byte[], Byte[], Boolean)

Read data from the stream until a delimiter is reached.

[Visual Basic]
Public Function Read( _
   ByVal buffer As Byte(), _
   ByVal delimiter As Byte(), _
   ByRef found As Boolean _
) As Integer
[C#]
public int Read(
   byte[] buffer,
   byte[] delimiter,
   ref bool found
);
[C++]
public: int Read(
   char buffer __gc[],
   char delimiter __gc[],
   * bool found
);
[JScript]
public function Read(
   Byte[] buffer,
   Byte[] delimiter,
   bool found
): int;

Parameters

buffer
The storage location for the received data.
delimiter
The token that is used to determine a segment was read.
found
True if delimiter is found; false otherwise.

Return Value

The total number of bytes read into the buffer, which will normally be less than buffer.length. Returns 0 if end of stream is reached and there is no data left to return.

Remarks

This method reads from the stream and returns when the provided delimiter is found, buffer.length bytes have been read, or end of stream is reached.

The purpose of this method is to provide a convenient way to read a variable-length record from the stream. This is the only kind of Read that uses internal buffering.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not readable.
ArgumentNullException | Thrown when the receiving buffer is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when count is less than or equal to zero.
ArgumentException | Thrown when (offset + count) > buffer.Length.
EndOfStreamException | At least one byte was read without finding the delimiter before end of stream was reached.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Read Overload List


Read Method (Byte[], Byte[], Int32, Int32, Boolean)

SegmentedStream.Read Method (Byte[], Byte[], Int32, Int32, Boolean)

Read data from the stream.

[Visual Basic]
Public Function Read( _
   ByVal buffer As Byte(), _
   ByVal delimiter As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer, _
   ByRef found As Boolean _
) As Integer
[C#]
public int Read(
   byte[] buffer,
   byte[] delimiter,
   int offset,
   int count,
   ref bool found
);
[C++]
public: int Read(
   char buffer __gc[],
   char delimiter __gc[],
   int offset,
   int count,
   * bool found
);
[JScript]
public function Read(
   Byte[] buffer,
   Byte[] delimiter,
   int offset,
   int count,
   bool found
): int;

Parameters

buffer
The storage location for the received data.
delimiter
The token that is used to determine a segment was read.
offset
The zero-based position in the buffer at which to store the received data.
count
The maximum number of bytes to read.
found
True if delimiter is found; false otherwise.

Return Value

The total number of bytes read into the buffer, which will normally be less than count. Returns 0 if end of stream is reached and there is no data left to return.

Remarks

This method reads from the stream and returns when the provided delimiter is found, count bytes have been read, or end of stream is reached.

The purpose of this method is to provide a convenient way to read a variable-length record from the stream.

If the delimiter is found, found is true, otherwise found is false.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not readable.
ArgumentNullException | Thrown when the receiving buffer is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when count is less than or equal to zero.
ArgumentException | Thrown when (offset + count) > buffer.Length.
EndOfStreamException | At least one byte was read without finding the delimiter before end of stream was reached.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Read Overload List


Read Method (Byte[], ArrayList, Int32, Int32, Boolean)

SegmentedStream.Read Method (Byte[], ArrayList, Int32, Int32, Boolean)

Read data from the stream until one of the specified delimiters is found.

[Visual Basic]
Public Function Read( _
   ByVal buffer As Byte(), _
   ByVal delimiters As ArrayList, _
   ByVal offset As Integer, _
   ByVal count As Integer, _
   ByRef found As Boolean _
) As Integer
[C#]
public int Read(
   byte[] buffer,
   ArrayList delimiters,
   int offset,
   int count,
   ref bool found
);
[C++]
public: int Read(
   char buffer __gc[],
   ArrayList* delimiters,
   int offset,
   int count,
   * bool found
);
[JScript]
public function Read(
   Byte[] buffer,
   ArrayList delimiters,
   int offset,
   int count,
   bool found
): int;

Parameters

buffer
The storage location for the received data.
delimiters
The list of tokens to search for.
offset
The zero-based position in the buffer at which to store the received data.
count
The maximum number of bytes to read.
found
True if delimiteris found; false otherwise.

Return Value

The total number of bytes read into the buffer, which will normally be less than count. Returns 0 if end of stream is reached and there is no data left to return.

Remarks

This method reads from the stream and returns when one of the provided delimiters is found, count bytes have been read, or end of stream is reached.

The purpose of this method is to provide a convenient way to read a variable-length record from the stream. The delimiters list must consist of byte arrays.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not readable.
ArgumentNullException | Thrown when the receiving buffer is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when count is less than or equal to zero.
ArgumentException | Thrown when (offset + count) > buffer.Length.
EndOfStreamException | At least one byte was read without finding a delimiter before end of stream was reached.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Read Overload List


Read Method (Byte[], Int32, Int32)

SegmentedStream.Read Method (Byte[], Int32, Int32)

Read data from the stream into a byte array.

[Visual Basic]
Overrides  OverloadsPublic Function Read( _
   ByVal buffer As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer _
) As Integer
[C#]
public override int Read(
   byte[] buffer,
   int offset,
   int count
);
[C++]
public: int Read(
   char buffer __gc[],
   int offset,
   int count
);
[JScript]
public override function Read(
   Byte[] buffer,
   int offset,
   int count
): int;

Parameters

buffer
The storage location for the received data.
offset
The zero-based position in the buffer at which to store the received data.
count
The maximum number of bytes to read.

Return Value

The total number of bytes read into the buffer.

Remarks

This method will block (for ReceiveTimeout) until at least 1 byte is available for reading, or the connection is closed by the server, in which case an empty string is returned. The Charset property is used to convert from bytes to unicode characters, which allows unicode characters to be passed over the network.

The value returned may be less than the number of bytes requested if that many bytes are not currently available, or zero if the end of the stream has been reached. Applications must check this value to know how many bytes were read into the buffer.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Readable.
ArgumentNullException | Thrown when the receiving buffer is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when count is less than or equal to zero.
ArgumentException | Thrown when the (offset + count) > buffer.Length.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Read Overload List


Read Method (Byte[], Int32, Int32, Boolean)

SegmentedStream.Read Method (Byte[], Int32, Int32, Boolean)

Read data from the stream until a byte array is filled.

[Visual Basic]
Public Function Read( _
   ByVal buffer As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer, _
   ByVal fill As Boolean _
) As Integer
[C#]
public int Read(
   byte[] buffer,
   int offset,
   int count,
   bool fill
);
[C++]
public: int Read(
   char buffer __gc[],
   int offset,
   int count,
   bool fill
);
[JScript]
public function Read(
   Byte[] buffer,
   int offset,
   int count,
   bool fill
): int;

Parameters

buffer
The storage location for the received data.
offset
The zero-based position in the buffer at which to store the received data.
count
The exact number of bytes to read.
fill
Always true, use this version of Read to completely fill the buffer

Return Value

The total number of bytes read into the buffer. This will either be the value of the count parameter, or zero if the stream has closed.

Remarks

This method reads data from the stream and returns when the provided buffer is completely full or end of stream is reached. This method is a good way to read fixed-length data. An example of this is with HTTP chunking, which occurs when the server breaks up the HTTP response into fixed-size chunks. Each chunk is preceded with a hexidecimal value notifying the receiver of the size of the data chunk to follow. Initialize a byte array to this value, then call this method to fill the byte array.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Readable.
ArgumentNullException | Thrown when the receiving buffer is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when count is less than or equal to zero.
ArgumentException | Thrown when (offset + count) > buffer.Length.
EndOfStreamException | Thrown when the end of the stream was found before the required byte count was received. When this occurs the Available property will indicate how much data may be read and the CanRead Property will return true.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Read Overload List


Read Method (Int32)

SegmentedStream.Read Method (Int32)

Read data from the stream into a string.

[Visual Basic]
Public Function Read( _
   ByVal maxLength As Integer _
) As String
[C#]
public string Read(
   int maxLength
);
[C++]
public: String* Read(
   int maxLength
);
[JScript]
public function Read(
   int maxLength
): String;

Parameters

maxLength
The maximum length of the string returned.

Return Value

A string value representing the data read from the stream.

Remarks

This method reads data from the stream until at least 1 byte has been read or the end of the stream has been reached.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Readable.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Read Overload List


Read Method (String)

SegmentedStream.Read Method (String)

Reads stream, accumulating string data, until delimiter is reached or timeout is reached.

[Visual Basic]
Public Function Read( _
   ByVal delimiter As String _
) As String
[C#]
public string Read(
   string delimiter
);
[C++]
public: String* Read(
   String* delimiter
);
[JScript]
public function Read(
   String delimiter
): String;

Parameters

delimiter
The sequence to find.

Return Value

The accumulated string data read from the stream.

Remarks

This method is useful when implementing high-level protocols.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Read Overload List


Read Method (String, Int32, Boolean)

SegmentedStream.Read Method (String, Int32, Boolean)

Read data from the stream until a delimiter is reached.

[Visual Basic]
Public Function Read( _
   ByVal delimiter As String, _
   ByVal maxLength As Integer, _
   ByRef found As Boolean _
) As String
[C#]
public string Read(
   string delimiter,
   int maxLength,
   ref bool found
);
[C++]
public: String* Read(
   String* delimiter,
   int maxLength,
   * bool found
);
[JScript]
public function Read(
   String delimiter,
   int maxLength,
   bool found
): String;

Parameters

delimiter
The sequence to find.
maxLength
The maximum length of the string returned.
found
Will be set to true if sequence is found; false otherwise.

Return Value

A string representation of the bytes read.

Remarks

This method reads data from the stream until delimiter is found or the end of the stream is reached.

This method is useful for reading until a sequence of characters is found. A good example of this is receiving an email message when using the POP protocol. When sending a POP mail message, a POP server will delimit the end of the message with <CRLF>.<CRLF>. Using this method you could simply read the data until this sequence is found, at which point the method would return.

If the delimiter is found, found is true, otherwise found is false.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Readable.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Read Overload List


Seek Method

SegmentedStream.Seek Method

Seeks a specific position in the stream.

[Visual Basic]
Overrides Public Function Seek( _
   ByVal offset As Long, _
   ByVal origin As SeekOrigin _
) As Long
[C#]
public override long Seek(
   long offset,
   SeekOrigin origin
);
[C++]
public: __int64 Seek(
   __int64 offset,
   SeekOrigin origin
);
[JScript]
public override function Seek(
   long offset,
   SeekOrigin origin
): long;

Parameters

offset
A byte offset relative to origin.
origin
A value of type SeekOrigin indicating the reference point used to obtain the new position.

Return Value

The number of bytes that were sought.

Remarks

Returns value of CoreStream.Seek. TcpStream.Seek throws a NotSupportedException.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


SetLength Method

SegmentedStream.SetLength Method

Sets the length of the Stream. This method always throws a NotSupportedException.

[Visual Basic]
Overrides Public Sub SetLength( _
   ByVal value As Long _
)
[C#]
public override void SetLength(
   long value
);
[C++]
public: void SetLength(
   __int64 value
);
[JScript]
public override function SetLength(
   long value
);

Parameters

value
The desired length of the current stream in bytes.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


Write Method

SegmentedStream.Write Method

Write data to the stream while carrying out a bytewise find/replace.

Overload List

Writes a sequence of bytes to the Stream and returns when the operation is complete.
Inherited from EnhancedStream.

[Visual Basic] Public Sub Write(ByVal Byte())
[C#] public void Write(byte[]);
[C++] public: void Write(char __gc[]);
[JScript] public function Write(Byte[]);

Write data to the stream while carrying out a bytewise find/replace.

[Visual Basic] Public Sub Write(ByVal Byte(),ByVal Byte(),ByVal Byte(),ByVal Integer,ByVal Integer)
[C#] public void Write(byte[],byte[],byte[],int,int);
[C++] public: void Write(char __gc[],char __gc[],char __gc[],int,int);
[JScript] public function Write(Byte[],Byte[],Byte[],int,int);

Write data to the stream until a delimiter is reached.

[Visual Basic] Public Function Write(ByVal Byte(),ByVal Byte(),ByRef Integer,ByRef Integer) As Boolean
[C#] public bool Write(byte[],byte[],ref int,ref int);
[C++] public: bool Write(char __gc[],char __gc[],* int,* int);
[JScript] public function Write(Byte[],Byte[],int,int): bool;

Writes data to the stream.

[Visual Basic] Overrides OverloadsPublic Sub Write(ByVal Byte(),ByVal Integer,ByVal Integer)
[C#] public override void Write(byte[],int,int);
[C++] public: void Write(char __gc[],int,int);
[JScript] public override function Write(Byte[],int,int);

Write a string to the stream.

[Visual Basic] Public Sub Write(ByVal String)
[C#] public void Write(string);
[C++] public: void Write(String*);
[JScript] public function Write(String);

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


Write Method (Byte[], Byte[], Byte[], Int32, Int32)

SegmentedStream.Write Method (Byte[], Byte[], Byte[], Int32, Int32)

Write data to the stream while carrying out a bytewise find/replace.

[Visual Basic]
Public Sub Write( _
   ByVal buffer As Byte(), _
   ByVal originalSequence As Byte(), _
   ByVal replacementSequence As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer _
)
[C#]
public void Write(
   byte[] buffer,
   byte[] originalSequence,
   byte[] replacementSequence,
   int offset,
   int count
);
[C++]
public: void Write(
   char buffer __gc[],
   char originalSequence __gc[],
   char replacementSequence __gc[],
   int offset,
   int count
);
[JScript]
public function Write(
   Byte[] buffer,
   Byte[] originalSequence,
   Byte[] replacementSequence,
   int offset,
   int count
);

Parameters

buffer
The storage location of the data.
originalSequence
The sequence to find.
replacementSequence
The sequence to replace.
offset
The zero-based position in the buffer from which to begin writing from.
count
The number of bytes from buffer that should be processed using the byte replacement desired.

Remarks

Carries out a bytewise find/replace of all occurrences found in buffer of originalSequence with replacementSequence. This method is useful for performing simple encoding of data before sending.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Write Overload List


Write Method (Byte[], Byte[], Int32, Int32)

SegmentedStream.Write Method (Byte[], Byte[], Int32, Int32)

Write data to the stream until a delimiter is reached.

[Visual Basic]
Public Function Write( _
   ByVal buffer As Byte(), _
   ByVal delimiter As Byte(), _
   ByRef offset As Integer, _
   ByRef count As Integer _
) As Boolean
[C#]
public bool Write(
   byte[] buffer,
   byte[] delimiter,
   ref int offset,
   ref int count
);
[C++]
public: bool Write(
   char buffer __gc[],
   char delimiter __gc[],
   * int offset,
   * int count
);
[JScript]
public function Write(
   Byte[] buffer,
   Byte[] delimiter,
   int offset,
   int count
): bool;

Parameters

buffer
The storage location of the data.
delimiter
The sequence to find.
offset
The zero-based position in the buffer from which to begin writing from.
count
The exact number of bytes to write.

Return Value

true if delimiter is found; false otherwise.

Remarks

This method writes data until the delimiter is found (returning true and not writing the delimiter) or writes the entire buffer (returning false).

Flush must be called after writing if this method is being used.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Write Overload List


Write Method (Byte[], Int32, Int32)

SegmentedStream.Write Method (Byte[], Int32, Int32)

Writes data to the stream.

[Visual Basic]
Overrides  OverloadsPublic Sub Write( _
   ByVal buffer As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer _
)
[C#]
public override void Write(
   byte[] buffer,
   int offset,
   int count
);
[C++]
public: void Write(
   char buffer __gc[],
   int offset,
   int count
);
[JScript]
public override function Write(
   Byte[] buffer,
   int offset,
   int count
);

Parameters

buffer
The storage location of the data to be sent.
offset
The zero-based position in the buffer from which to begin writing from.
count
The exact number of bytes to write.

Remarks

This method writes a sequence of bytes to the stream and returns when the operation is complete.

Use the CanWrite property to determine whether the current instance supports writing.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Writeable.
ArgumentNullException | Thrown when buffer is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when count is less than or equal to zero.
ArgumentException | Thrown when the (offset + count) > buffer.Length.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Write Overload List


Write Method (String)

SegmentedStream.Write Method (String)

Write a string to the stream.

[Visual Basic]
Public Sub Write( _
   ByVal buffer As String _
)
[C#]
public void Write(
   string buffer
);
[C++]
public: void Write(
   String* buffer
);
[JScript]
public function Write(
   String buffer
);

Parameters

buffer
The storage location of the data to be sent.

Remarks

This method writes a string to the stream and returns from complete. Since this method writes a string (doing a byte array conversion behind-the-scenes using the Object.Charset to convert unicode characters to bytes) to the stream, it is useful for such purposes as sending protocol commands to a server.

Use the CanWrite property to determine whether the current instance supports writing.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Writeable.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace | SegmentedStream.Write Overload List


SegmentedStream Events

The events of the SegmentedStream class are listed below. For a complete list of SegmentedStream class members, see the SegmentedStream Members topic.

Public Instance Events

Trace

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


Trace Event

SegmentedStream.Trace Event

[Visual Basic]
Public Event Trace As SegmentEventHandler
[C#]
public event SegmentEventHandler Trace;
[C++]
public: __event SegmentEventHandler* Trace;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type SegmentEventArgs containing data related to this event. The following SegmentEventArgs properties provide information specific to this event.

Property | Description
Exception | Gets any exception which occurred during the asynchronous operation.
Segment | The Segment object referencing the data that was sent or received.
State | Gets the object that was included as part of the associated method call.

See Also

SegmentedStream Class | Dart.PowerTCP.Ftp Namespace


SegmentEventArgs Class

Provides data for any event where data is sent or received.

For a list of all members of this type, see SegmentEventArgs Members.

System.Object
System.EventArgs
Dart.PowerTCP.Ftp.SegmentEventArgs

[Visual Basic]
Public Class SegmentEventArgs
    Inherits EventArgs
[C#]
public class SegmentEventArgs : EventArgs
[C++]
public __gc class SegmentEventArgs : public EventArgs
[JScript]
public class SegmentEventArgs extends EventArgs

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

A SegmentEventArgs object is passed as a parameter to all events that report the transfer of data. This object contains a Segment object that references the data sent/received.

If your code causes an exception, it would be returned to the handling event without you seeing it. To preclude such a condition, you should ALWAYS use a try/ catch block around your event-handling code.

Example

The following example demonstrates asynchronous receiving and sending of data.

[Visual Basic]
Private Sub AsynchTcpDemo()

   ' Attempt to connect to an echo port.
   Try
      Tcp1.Connect("myserver", 7)
   Catch ex As Exception
      Return
   End Try

   ' Send data, since we are connected to an echo port, the same data should be returned.
   ' The following code demonstrates asynchronously sending data. When data has been sent
   ' the EndSend event will be raised.

   Dim buffer() As Byte = System.Text.Encoding.Default.GetBytes("a")
   Tcp1.BeginSend(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)
End Sub

Private Sub Tcp1_EndSend(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndSend
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Send is complete. Display info about the data sent.
      Debug.WriteLine("Byte count sent: " + e.Segment.Count)
      Debug.WriteLine("Data sent: " + e.Segment.ToString())

      Dim buffer(Tcp1.ReceiveBufferSize) As Byte

      ' Receive the data. The EndReceive event will be raised upon completion.
      Tcp1.BeginReceive(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)

    End If
End Sub

Private Sub Tcp1_EndReceive(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndReceive
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Receive is complete. Display info about the data sent.
      Debug.WriteLine("Byte count received: " + e.Segment.Count)
      Debug.WriteLine("Data received: " + e.Segment.ToString())

      ' Close the connection
      Tcp1.Close()
    End If
End Sub

[C#]
private void AsynchTcpDemo()
{
    // Attempt to connect to an echo port.
    try
    {
        tcp1.Connect("myserver", 7);
    }
    catch(Exception ex)
    {return;}

    // Send data, since we are connected to an echo port, the same data should be returned.
    // The following code demonstrates asynchronously sending data. When data has been sent
    // the EndSend event will be raised.

    byte[] buffer = System.Text.Encoding.Default.GetBytes("a");
    tcp1.BeginSend(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
}

private void tcp1_EndSend(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Send is complete. Display info about the data sent.
        Debug.WriteLine("Byte count sent: " + e.Segment.Count);
        Debug.WriteLine("Data sent: " + e.Segment.ToString());

        byte[] buffer = new byte[tcp1.ReceiveBufferSize];

        // Receive the data. The EndReceive event will be raised upon completion.
        tcp1.BeginReceive(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
    }
}

private void tcp1_EndReceive(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Receive is complete. Display info about the data sent.
        Debug.WriteLine("Byte count received: " + e.Segment.Count);
        Debug.WriteLine("Data received: " + e.Segment.ToString());

        // Close the connection
        tcp1.Close();
    }
}

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

SegmentEventArgs Members | Dart.PowerTCP.Ftp Namespace


SegmentEventArgs Members

SegmentEventArgs overview

Public Instance Properties

Exception | Gets any exception which occurred during the asynchronous operation.
Segment | The Segment object referencing the data that was sent or received.
State | Gets the object that was included as part of the associated method call.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

SegmentEventArgs Class | Dart.PowerTCP.Ftp Namespace


SegmentEventArgs Properties

The properties of the SegmentEventArgs class are listed below. For a complete list of SegmentEventArgs class members, see the SegmentEventArgs Members topic.

Public Instance Properties

Exception | Gets any exception which occurred during the asynchronous operation.
Segment | The Segment object referencing the data that was sent or received.
State | Gets the object that was included as part of the associated method call.

See Also

SegmentEventArgs Class | Dart.PowerTCP.Ftp Namespace


Exception Property

SegmentEventArgs.Exception Property

Gets any exception which occurred during the asynchronous operation.

[Visual Basic]
Public Property ReadOnly Exception As Exception
[C#]
public Exception Exception { get; }
[C++]
public: __property Exception* get_Exception();
[JScript]
public function get Exception() : Exception

Property Value

If any exception occurred during the asynchronous operation, this property will contain an Exception object describing the exception.

Remarks

Check this property to tell if an exception occurred during the asynchronous operation. If this property is null, no exception occurred.

The exception property is useful for checking exceptions and handling them appropriately. For example, if a bad command was sent to the server, a ProtocolException may be thrown. You could check this property to see if it was of type ProtocolException, than handle appropriately.

Example

The following example demonstrates asynchronous receiving and sending of data.

[Visual Basic]
Private Sub AsynchTcpDemo()

   ' Attempt to connect to an echo port.
   Try
      Tcp1.Connect("myserver", 7)
   Catch ex As Exception
      Return
   End Try

   ' Send data, since we are connected to an echo port, the same data should be returned.
   ' The following code demonstrates asynchronously sending data. When data has been sent
   ' the EndSend event will be raised.

   Dim buffer() As Byte = System.Text.Encoding.Default.GetBytes("a")
   Tcp1.BeginSend(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)
End Sub

Private Sub Tcp1_EndSend(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndSend
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Send is complete. Display info about the data sent.
      Debug.WriteLine("Byte count sent: " + e.Segment.Count)
      Debug.WriteLine("Data sent: " + e.Segment.ToString())

      Dim buffer(Tcp1.ReceiveBufferSize) As Byte

      ' Receive the data. The EndReceive event will be raised upon completion.
      Tcp1.BeginReceive(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)

    End If
End Sub

Private Sub Tcp1_EndReceive(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndReceive
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Receive is complete. Display info about the data sent.
      Debug.WriteLine("Byte count received: " + e.Segment.Count)
      Debug.WriteLine("Data received: " + e.Segment.ToString())

      ' Close the connection
      Tcp1.Close()
    End If
End Sub

[C#]
private void AsynchTcpDemo()
{
    // Attempt to connect to an echo port.
    try
    {
        tcp1.Connect("myserver", 7);
    }
    catch(Exception ex)
    {return;}

    // Send data, since we are connected to an echo port, the same data should be returned.
    // The following code demonstrates asynchronously sending data. When data has been sent
    // the EndSend event will be raised.

    byte[] buffer = System.Text.Encoding.Default.GetBytes("a");
    tcp1.BeginSend(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
}

private void tcp1_EndSend(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Send is complete. Display info about the data sent.
        Debug.WriteLine("Byte count sent: " + e.Segment.Count);
        Debug.WriteLine("Data sent: " + e.Segment.ToString());

        byte[] buffer = new byte[tcp1.ReceiveBufferSize];

        // Receive the data. The EndReceive event will be raised upon completion.
        tcp1.BeginReceive(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
    }
}

private void tcp1_EndReceive(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Receive is complete. Display info about the data sent.
        Debug.WriteLine("Byte count received: " + e.Segment.Count);
        Debug.WriteLine("Data received: " + e.Segment.ToString());

        // Close the connection
        tcp1.Close();
    }
}

See Also

SegmentEventArgs Class | Dart.PowerTCP.Ftp Namespace


Segment Property

SegmentEventArgs.Segment Property

The Segment object referencing the data that was sent or received.

[Visual Basic]
Public Property ReadOnly Segment As Segment
[C#]
public Segment Segment { get; }
[C++]
public: __property Segment* get_Segment();
[JScript]
public function get Segment() : Segment

Property Value

A Segment object referencing the data that was sent or received.

Remarks

The Segment object will contain data describing the data that was sent or received. For example, the Segment object will contain the data itself, the amount of bytes sent,' and whether the Segment object was created as a result of data being sent or received.

To access the data contained within the Segment object, simply access the properties of the Segment object. As a shortcut, you can simply get all data contained within the Segment object by using the ToString method.

Example

The following example demonstrates asynchronous receiving and sending of data.

[Visual Basic]
Private Sub AsynchTcpDemo()

   ' Attempt to connect to an echo port.
   Try
      Tcp1.Connect("myserver", 7)
   Catch ex As Exception
      Return
   End Try

   ' Send data, since we are connected to an echo port, the same data should be returned.
   ' The following code demonstrates asynchronously sending data. When data has been sent
   ' the EndSend event will be raised.

   Dim buffer() As Byte = System.Text.Encoding.Default.GetBytes("a")
   Tcp1.BeginSend(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)
End Sub

Private Sub Tcp1_EndSend(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndSend
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Send is complete. Display info about the data sent.
      Debug.WriteLine("Byte count sent: " + e.Segment.Count)
      Debug.WriteLine("Data sent: " + e.Segment.ToString())

      Dim buffer(Tcp1.ReceiveBufferSize) As Byte

      ' Receive the data. The EndReceive event will be raised upon completion.
      Tcp1.BeginReceive(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)

    End If
End Sub

Private Sub Tcp1_EndReceive(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndReceive
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Receive is complete. Display info about the data sent.
      Debug.WriteLine("Byte count received: " + e.Segment.Count)
      Debug.WriteLine("Data received: " + e.Segment.ToString())

      ' Close the connection
      Tcp1.Close()
    End If
End Sub

[C#]
private void AsynchTcpDemo()
{
    // Attempt to connect to an echo port.
    try
    {
        tcp1.Connect("myserver", 7);
    }
    catch(Exception ex)
    {return;}

    // Send data, since we are connected to an echo port, the same data should be returned.
    // The following code demonstrates asynchronously sending data. When data has been sent
    // the EndSend event will be raised.

    byte[] buffer = System.Text.Encoding.Default.GetBytes("a");
    tcp1.BeginSend(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
}

private void tcp1_EndSend(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Send is complete. Display info about the data sent.
        Debug.WriteLine("Byte count sent: " + e.Segment.Count);
        Debug.WriteLine("Data sent: " + e.Segment.ToString());

        byte[] buffer = new byte[tcp1.ReceiveBufferSize];

        // Receive the data. The EndReceive event will be raised upon completion.
        tcp1.BeginReceive(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
    }
}

private void tcp1_EndReceive(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Receive is complete. Display info about the data sent.
        Debug.WriteLine("Byte count received: " + e.Segment.Count);
        Debug.WriteLine("Data received: " + e.Segment.ToString());

        // Close the connection
        tcp1.Close();
    }
}

See Also

SegmentEventArgs Class | Dart.PowerTCP.Ftp Namespace


State Property

SegmentEventArgs.State Property

Gets the object that was included as part of the associated method call.

[Visual Basic]
Public Property ReadOnly State As Object
[C#]
public object State { get; }
[C++]
public: __property Object* get_State();
[JScript]
public function get State() : Object

Property Value

An object containing data passed into the calling asynchronous method.

Remarks

The EndEventArgs.State property can be used in the calling asynchronous method to make data accessible to the handling event.

This property is useful for making data accessible to the handling event. Since asynchronous methods are "disconnected" (meaning that when one is called, it executes on it's own and returns in the event handler) data that you were using in the code that called the asynchronous method may not be available in the event handler. Simply pass this data in as state when calling the asynchronous method (usually a BeginXXX method) and it is available in the event handler. If you do not wish to make an object accessible in the EndXXX event, simple pass in null as state.

See Also

SegmentEventArgs Class | Dart.PowerTCP.Ftp Namespace


SegmentEventHandler Delegate

Represents the method (event handler) that is raised when data is received or sent.

[Visual Basic]
Public Delegate Function Sub  SegmentEventHandler( _
   ByVal sender As Object, _
   ByVal e As SegmentEventArgs _
)
[C#]
public delegate void SegmentEventHandler(
   object sender,
   SegmentEventArgs e
)
[C++]
public __gc __delegate void SegmentEventHandler(
   Object* sender,
   SegmentEventArgs* e
)

[JScript] In JScript, you can use the delegates defined by a type, but you cannot define your own.

Parameters

sender
The source of the event.
e
A SegmentEventArgs object that contains the event data.

Remarks

As Microsoft describes in their MSDN documentation, the event model in the .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed:

  • A class that holds the event data. This class must derive from the base class EventArgs.
  • A delegate that points to a method that provides the response to the event.
When sending or receiving data, the class that holds the event data is the SegmentEventArgs class. A method must be created with the same signature as the delegate. In this example that would mean a method would have to be defined to accept two arguments (an object and a SegmentEventArgs) and return void. Once this has been done, the delegate must be "connected" to the handling event. This is done by adding an instance of the delegate to the event.

For more information about event handler delegates, see the Using Events in PowerTCP topic.

If your code causes an exception, it would be returned to the handling event without you seeing it. To preclude such a condition, you should ALWAYS use a try/ catch block around your event-handling code.

Example

The following example demonstrates using the Log event to create a text log of all data sent over the control connection.

[Visual Basic]
' The Trace Event will fire whenever data is sent/received over the control connection.
Private Sub Ftp1_Log(ByVal sender As Object, ByVal e As Dart.PowerTCP.Ftp.SegmentEventArgs) Handles Ftp1.Log
   ' Create FileStream to write to log file
   Dim stream1 As New System.IO.FileStream("c:\FtpTest\mylog.log", IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite)

   ' Create text to precede sent/received data.
   Dim recv() As Byte = System.Text.Encoding.ASCII.GetBytes(vbCrLf + "Received <--" + vbCrLf)
   Dim sent() As Byte = System.Text.Encoding.ASCII.GetBytes(vbCrLf + "Sent -->" + vbCrLf)

   ' Set the stream position to append.
   stream1.Position = stream1.Length

   ' Check if data is incoming or outgoing and write appropriate data
   If e.Sent = True Then
      stream1.Write(sent, 0, sent.Length)
   Else
      stream1.Write(recv, 0, recv.Length)
   End If

   ' Write the data
   stream1.Write(e.Segment.Buffer, e.Segment.Offset, e.Segment.Count)

   ' Close the stream
   stream1.Close()

End Sub

[C#]
// The Trace Event will fire whenever data is sent/received.

private void Ftp1_Trace(object sender, Dart.PowerTCP.Ftp.SegmentEventArgs e)
{

    // Create FileStream to write to log file
    System.IO.FileStream stream1 = new System.IO.FileStream("c:\\FtpTest\\log.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);

    // Create text to precede sent/received data.
    byte[] recv = System.Text.ASCIIEncoding.ASCII.GetBytes("\r\nReceived <-- \r\n");
    byte[] sent = System.Text.ASCIIEncoding.ASCII.GetBytes("\r\nSent --> \r\n");

    // Set the stream position to append.
    stream1.Position = stream1.Length;

    // Check if data is incoming or outgoing and write appropriate data
    if(e.Sent == true)
        stream1.Write(sent, 0, sent.Length);
    else
        stream1.Write(recv, 0, recv.Length);

    // Write the data
    stream1.Write(e.Segment.Buffer, e.Segment.Offset, e.Segment.Count);

    // Close the stream
    stream1.Close();

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


StoreType Enumeration

Enumerates how a stored file should be treated if a file exists with the same name.

[Visual Basic]
Public Enum StoreType
[C#]
public enum StoreType
[C++]
public __value enum StoreType
[JScript]
public enum StoreType

Remarks

This enumeration is used by the StoreType property, specifying what happens when files are put to the server that have an existing file with the same name. Use StoreType.Replace to overwrite an existing file with the same name, StoreType.Append to add the new file to the end of the existing file, and StoreType.Unique to store the file with a unique name. The unique name will be returned in the response.

Example

The following example demonstrates file synchronization between a local root and a remote root. First, filenames from both the local root and remote root are retrieved using ExpandLocalFiles and ExpandRemoteFiles. Then extraneous files are deleted from the server. Then StoreType is set to Replace to assure that the files on the client will replace those on the server. Finally all files on the local root are put to the server.

[Visual Basic]
Private Sub SynchronizeFiles(ByVal LocalRoot As String, ByVal RemoteRoot As String)

' This sub demonstrates synchronization of files between a local root
' and a root on the FTP server, to get all files on the FTP Server to
' be the same as on the local root

' Set server and user properties. This will allow calling of other
' Ftp Component methods with the log in taking place "behind the scenes"
Ftp1.Server = "MyFTPServer"
Ftp1.Username = "blah"
Ftp1.Password = "mypass"

' Get listing of local files
Dim lFiles() As String
lFiles = Ftp1.ExpandLocalFiles(LocalRoot + "*", False)

' Get a listing of remote files
Dim rFiles() As String
rFiles = Ftp1.ExpandRemoteFiles(RemoteRoot + "*", False)

Dim found As Boolean
Dim i As Integer

' Iterate though list of files on the server and compare to local files.
' If it does not exist locally, delete it
For i = 0 To rFiles.Length - 1

   found = False
   Dim j As Integer

   For j = 0 To lFiles.Length - 1

      ' Create FileInfo objects to parse filename
      Dim rFileInfo As New System.IO.FileInfo(rFiles(i))
      Dim lFileInfo As New System.IO.FileInfo(lFiles(i))

      ' Compare file names
      If (rFileInfo.Name = lFileInfo.Name) Then
         found = True
         Exit For
      End If
   Next

   If Not found Then
      Debug.WriteLine("Deleting " + rFiles(i) + " from server")
      Ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Delete, rFiles(i))
   End If
Next

' Now MPUT all files in LocalRoot and both directories are synched

' First, make sure old files are replaced
Ftp1.StoreType = Dart.PowerTCP.Ftp.StoreType.Replace

' Then MPUT
Debug.WriteLine("Uploading all files")
Ftp1.Put(LocalRoot, "*", RemoteRoot, False)
Debug.WriteLine(LocalRoot + " and " + RemoteRoot + " are synched")

' Close the connection
Ftp1.Close()

End Sub

[C#]
private void SynchronizeFiles(string LocalRoot, string RemoteRoot)
{
    // This sub demonstrates synchronization of files between a local root
    // and a root on the FTP server, to get all files on the FTP Server to
    // be the same as on the local root

    // Set server and user properties. This will allow calling of other
    // Ftp Component methods with the log in taking place "behind the scenes"
    ftp1.Server = "MyFTPServer";
    ftp1.Username = "blah";
    ftp1.Password = "mypass";

    // Get list of local files
    string[] lfiles = ftp1.ExpandLocalFiles(LocalRoot + "*", false);

    // Get list of remote files
    string[] rfiles = ftp1.ExpandRemoteFiles(RemoteRoot + "*", false);

    bool found;

    // Iterate though list of files on the server and compare to local files.
    // If it does not exist locally, delete it
    for(int i = 0; i < lfiles.Length; i++)
    {
        found = false;
        for(int j = 0; j < lfiles.Length; j++)
        {
            // Compare filenames
            if(new System.IO.FileInfo(rfiles[i]).Name == new System.IO.FileInfo(lfiles[j]).Name)
            {
                found = true;
                break;
            }
        }

        if(!found) // Delete the file from the server.
        {
            Debug.WriteLine("Deleting " + rfiles[i] + " from server");
            ftp1.Invoke(Dart.PowerTCP.Ftp.FtpCommand.Delete, rfiles[i]);
        }
    }

    // Now just MPUT all files in the local root and everything is synched.

    // First, make sure old files are replaced
    ftp1.StoreType = Dart.PowerTCP.Ftp.StoreType.Replace;

    // Then MPUT
    Debug.WriteLine("Uploading all files");
    ftp1.Put(LocalRoot, "*", RemoteRoot, false);
    Debug.WriteLine(LocalRoot + " and " + RemoteRoot + " are synched.");

    // Close connection
    ftp1.Close();
}

Members

Member Name | Description
Replace | Over-write any existing file.
Unique | If an existing file is present, store the file using a unique name.
Append | If an existing file is present, append the stored file to it.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Dart.PowerTCP.Ftp Namespace


Tcp Class

The Tcp component provides comprehensive Transmission Control Protocol support.

For a list of all members of this type, see Tcp Members.

System.Object
System.MarshalByRefObject
System.ComponentModel.Component
Dart.PowerTCP.Ftp.Tcp

[Visual Basic]
Public Class Tcp
    Inherits Component
[C#]
public class Tcp : Component
[C++]
public __gc class Tcp : public Component
[JScript]
public class Tcp extends Component

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

Use the Tcp Component to establish and manage socket-level streams of data. It simplifies the use of TCP communications by providing methods to establish connections, send and receive data, and terminate connections. Synchronous and asynchronous use is fully supported.

Using the Tcp Component

What follows are short usage descriptions. For more information, see the appropriate member topic.

Low-level interface vs stream interface: Choose between sending data directly over the socket using a low-level interface, or use the stream interface to send/receive data with additional, stream-specific functionality. If you wish to use the low-level interface, you would use the Send and Receive methods. If you wish to use the stream-interface, use the Tcp.Stream.Read and Tcp.Stream.Write methods.

Connecting: To connect to a host, use either Connect (to connect synchronously) or BeginConnect (to connect asynchronously), specifying a remote host and port to connect to. Both of these methods are overloaded to allow the specification of a local interface/port as well.

Sending data using the low-level interface: After connecting, send data by using either Send (to send data synchronously) or BeginSend (to send data asynchronously). These methods are overloaded to allow sending of strings or byte arrays. A Segment object is returned from all Send operations, containing information about the data sent.

Sending data using the stream interface: To send data using the stream interface, use Tcp.Stream.Write. The stream interface offers additional functionality over the low-level interface for sending data such as sending data up to a delimiter and sending data while replacing characters.

Receiving data using the low-level interface: To receive data, use either Receive (to receive data synchronously) or BeginReceive (to receive data asynchronously). This method is most useful when you either want to receive all available data in the buffer.

Receiving data using the stream-interface: To receive data using the stream interface, use Tcp.Stream.Read. The stream interface offers additional functionality over the low-level interface for receiving data such as receiving up to a delimiter or filling a fixed-size buffer.

Event notification: The Tcp component provides full event support including the Trace event, raised when data is sent or received, the ConnectedChanged event, raised when the value of Connected changes.

Socket option configuration: The Tcp component enables socket option configuration (such as KeepAlive and NoDelay socket options, for example) by simply setting properties of the Tcp component. In addition, buffer-size/socket timeout configuration is possible by setting both the sending or receiving buffer size, and the sending and receiving timeout value.

Example

The following example demonstrates connecting implementing the SMTP protocol using the Tcp component to send a simple message.

[Visual Basic]
Private Sub TcpDemo()

   ' The following code assumes that good responses are always received from
   ' the server. More robust code should check each response and handle appropriately.

   ' Connect to SMTP port
   Tcp1.Connect("mail", 25)

   ' Send the EHLO command
   Tcp1.Send("EHLO myserver" + vbCrLf)

   ' Get response from the server
   Dim seg As Segment = Tcp1.Receive()

   ' Send MAIL FROM command
   Tcp1.Send("MAIL FROM: test@myserver.com" + vbCrLf)

   ' Get response from the server
   seg = Tcp1.Receive()

   ' Send RCPT TO command
   Tcp1.Send("RCPT TO: you@yourserver.com" + vbCrLf)

   ' Get response from the server
   seg = Tcp1.Receive()

   ' Send DATA command
   Tcp1.Send("DATA" + vbCrLf)

   ' Get response from the server
   seg = Tcp1.Receive()

   ' Send DATA
   Tcp1.Send("Test Message" + vbCrLf + "." + vbCrLf)

   ' Receive response from the server
   seg = Tcp1.Receive()

   ' Write output
   Debug.WriteLine("Operation complete. The following information")
   Debug.WriteLine("was reported by the server:")
   Debug.WriteLine(seg.ToString())
End Sub

[C#]
private void TcpDemo()
{

   // The following code assumes that good responses are always received from
   // the server. More robust code should check each response and handle appropriately.

   // Connect to SMTP port
   tcp1.Connect("mail", 25);

   // Send the EHLO command
   tcp1.Send("EHLO myserver\r\n");

   // Get response from the server
   Segment seg = tcp1.Receive();

   // Send MAIL FROM command
   tcp1.Send("MAIL FROM: test@myserver.com\r\n");

   // Get response from the server
   seg = tcp1.Receive();

   // Send RCPT TO command
   tcp1.Send("RCPT TO: you@yourserver.com\r\n");

   // Get response from the server
   seg = tcp1.Receive();

   // Send DATA command
   tcp1.Send("DATA\r\n");

   // Get response from the server
   seg = tcp1.Receive();

   // Send DATA
   tcp1.Send("Test Message\r\n.\r\n");

   // Receive response from the server
   seg = tcp1.Receive();

   // Write output
   Debug.WriteLine("Operation complete. The following information");
   Debug.WriteLine("was reported by the server about the operation:");
   Debug.WriteLine(seg.ToString());
}

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

Tcp Members | Dart.PowerTCP.Ftp Namespace


Tcp Members

Tcp overview

Public Instance Constructors

Tcp Overloaded. Initializes a new instance of the Tcp class.

Public Instance Properties

AutoReceive | Gets or sets a value which determines if data is automatically received.
Available | Gets the amount of data that has been received from the network and is available to be read.
Certificate | The Certificate object representing the certificate to use for optional client-side authentication.
Charset | Gets and sets the character set used for string/byte array conversions.
Connected | Gets the connected state of the connection.
ConnectTimeout | Gets or sets the number of milliseconds to wait for response from the server when connecting.
Container (inherited from Component) | Gets the IContainer that contains the Component.
DoEvents | Gets or sets a value that controls the processing of events during blocking method calls.
KeepAlive | Gets or sets the value of the socket's KeepAlive option.
LocalEndPoint | Returns the local address the socket is bound to.
NoDelay | Gets and sets a value the disables the use of Nagle's algorithm so that data is sent immediately.
OutOfBandInline | Gets or sets a value that indicates whether out-of-band (urgent) data is read as normal in-line data.
Proxy | Returns the Proxy instance that controls proxy server use.
ReceiveBufferSize | Gets and sets the size of the system receive buffer.
ReceiveTimeout | Gets and sets the number of milliseconds that a Receive method will block before throwing a SocketException.
RemoteCertificate | The Certificate object representing the certificate presented by the remote host during the SSL handshake.
RemoteEndPoint | Returns the remote address/port the socket is connected to.
ReuseAddress | Gets or sets a value that typically allows any local port to be specified, even if it is already in use.
SecureProtocol | Gets or sets a value which determines the type of encryption to use on the data.
SendBufferSize | Gets and sets the size of the system send buffer.
SendTimeout | Gets and sets the number of milliseconds that a Send method will block before throwing a SocketException.
Site (inherited from Component) | Gets or sets the ISite of the Component.
Socket | Returns a reference to the System.Net.Sockets.Socket instance being used.
Stream | Returns a SegmentedStream that can be used for advanced streaming operations on the socket.
SynchronizingObject | Set this object to automatically control thread marshalling between worker threads and the main UI thread.
Tag | Gets or sets an object reference that can be used to associate this instance with any other.
UseAuthentication | Gets or sets a value that determines if certificate authentication is used.
UseSslShutdown | Controls whether or not shut-down bytes are sent to the server when the connection is closed.

Public Instance Methods

BeginConnect | Overloaded. Connect to a server asynchronously, specifying the local interface and a range of local ports to use. The EndConnect event is raised when completed.
BeginReceive | Overloaded. Receive data into your buffer asynchronously specifying a buffer, offset, count and SocketFlags value. The EndReceive event is raised when completed.
BeginSend | Overloaded. Send data from your buffer asynchronously, specifying a buffer, offset, count and SocketFlags value. The EndSend event is raised when completed.
Close | Overloaded. Close the connection.
Connect | Overloaded. Connect to a host, specifying the local interface and a range of local ports to use.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose (inherited from Component) | Releases all resources used by the Component.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
Receive | Overloaded. Receive data from the host, specifying a buffer, offset, count and SocketFlags value.
Send | Overloaded. Send data to the server, specifying a buffer, offset, count and SocketFlags value.
ToString (inherited from Component) | Overridden.

Public Instance Events

CertificateReceived | This event is raised when a certificate has been received to be authenticated.
CertificateRequested | This event is raised when a certificate has been requested.
ConnectedChanged | Obsolete. Raised when the value of the Object.Connected property changes.
ConnectedChangedEx | Raised when the value of the Object.Connected property changes. Supersedes the ConnectedChanged event.
Disposed (inherited from Component) | Adds an event handler to listen to the Disposed event on the component.
EndConnect | Raised when the BeginConnect request completes.
EndReceive | Raised when the BeginReceive request completes.
EndSend | Raised when the BeginSend request completes.
RawTrace | Raised when data has been sent/received.
Trace | Raised when data has been sent/received.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Tcp Constructor

Initializes a new instance of the Tcp class.

Overload List

Initializes a new instance of the Tcp class.

[Visual Basic] Public Sub New()
[C#] public Tcp();
[C++] public: Tcp();
[JScript] public function Tcp();

Initializes a new instance of the Tcp class.

[Visual Basic] Public Sub New(ByVal IContainer)
[C#] public Tcp(IContainer);
[C++] public: Tcp(IContainer*);
[JScript] public function Tcp(IContainer);

Initializes a new instance of the Tcp class, specifying the System.Net.Sockets.Socket to use for the underlying connection.

[Visual Basic] Public Sub New(ByVal Socket)
[C#] public Tcp(Socket);
[C++] public: Tcp(Socket*);
[JScript] public function Tcp(Socket);

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Tcp Constructor (IContainer)

Initializes a new instance of the Tcp class.

[Visual Basic]
Public Sub New( _
   ByVal container As IContainer _
)
[C#]
public Tcp(
   IContainer container
);
[C++]
public: Tcp(
   IContainer* container
);
[JScript]
public function Tcp(
   IContainer container
);

Parameters

container
The IContainer which contains the object.

Remarks

Use this constructor to add the Tcp class to the IContainer container.

To create an instance of the Tcp component using Visual Studio.NET, simply add the Tcp component to the form and the object will automatically be created and initialized. If working out of the Visual Studio.NET environment (or using the Tcp component as a reference), the Tcp component will have to be explicitly created and initialized.

The following table shows initial property values for an instance of Tcp.

Property | Initial Value
Available | 0
Charset | Default system charset (accessible via System.Text.Encoding.Default.BodyName)
Connected | false
DoEvents | true
KeepAlive | false
LocalEndPoint | reference to System.Net.IPEndPoint
NoDelay | false
OutOfBandInline | false
Proxy | reference to Dart.PowerTCP.Proxy
ReceiveBufferSize | 8192
ReceiveTimeout | 0
RemoteEndPoint | reference to System.Net.IPEndPoint
ReuseAddress | false
SendBufferSize | 8192
SendTimeout | 0
Socket | null
Tcp.State | null
Stream | SegmentedStream object

Example

The following example demonstrates creating a Tcp object.

[Visual Basic]

' Declare as class member
Friend WithEvents Tcp1 As Tcp

' Create in class initialization
Me.Tcp1 = New Tcp()

[C#]
private Tcp tcp1 = new Tcp();

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp Constructor Overload List


Tcp Constructor ()

Initializes a new instance of the Tcp class.

[Visual Basic]
Public Sub New()
[C#]
public Tcp();
[C++]
public: Tcp();
[JScript]
public function Tcp();

Remarks

The default constructor initializes a new Tcp class.

To create an instance of the Tcp component using Visual Studio.NET, simply add the Tcp component to the form and the object will automatically be created and initialized. If working out of the Visual Studio.NET environment (or using the Tcp component as a reference), the Tcp component will have to be explicitly created and initialized.

The following table shows initial property values for an instance of Tcp.

Property | Initial Value
Available | 0
Charset | Default system charset (accessible via System.Text.Encoding.Default.BodyName)
Connected | false
DoEvents | true
KeepAlive | false
LocalEndPoint | reference to System.Net.IPEndPoint
NoDelay | false
OutOfBandInline | false
Proxy | reference to Dart.PowerTCP.Proxy
ReceiveBufferSize | 8192
ReceiveTimeout | 0
RemoteEndPoint | reference to System.Net.IPEndPoint
ReuseAddress | false
SendBufferSize | 8192
SendTimeout | 0
Socket | null
Tcp.State | null
Stream | SegmentedStream object

Example

The following example demonstrates creating a Tcp object.

[Visual Basic]

' Declare as class member
Friend WithEvents Tcp1 As Tcp

' Create in class initialization
Me.Tcp1 = New Tcp()

[C#]
private Tcp tcp1 = new Tcp();

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp Constructor Overload List


Tcp Constructor (Socket)

Initializes a new instance of the Tcp class, specifying the System.Net.Sockets.Socket to use for the underlying connection.

[Visual Basic]
Public Sub New( _
   ByVal acceptedSocket As Socket _
)
[C#]
public Tcp(
   Socket acceptedSocket
);
[C++]
public: Tcp(
   Socket* acceptedSocket
);
[JScript]
public function Tcp(
   Socket acceptedSocket
);

Parameters

acceptedSocket
The System.Net.Sockets.Socket to use for the underlying connection.

Remarks

Use this constructor create an instance of the Tcp class using an already created Socket. Typically, this is used when a connection is made on a socket that is listening for connections.

To create an instance of the Tcp component using Visual Studio.NET, simply add the Tcp component to the form and the object will automatically be created and initialized. If working out of the Visual Studio.NET environment (or using the Tcp component as a reference), the Tcp component will have to be explicitly created and initialized.

The following table shows initial property values for an instance of Tcp.

Property | Initial Value
Available | 0
Charset | Default system charset (accessible via System.Text.Encoding.Default.BodyName)
Connected | false
DoEvents | true
KeepAlive | false
LocalEndPoint | reference to System.Net.IPEndPoint
NoDelay | false
OutOfBandInline | false
Proxy | reference to Dart.PowerTCP.Proxy
ReceiveBufferSize | 8192
ReceiveTimeout | 0
RemoteEndPoint | reference to System.Net.IPEndPoint
ReuseAddress | false
SendBufferSize | 8192
SendTimeout | 0
Socket | null
Tcp.State | null
Stream | SegmentedStream object

Example

The following example demonstrates creating a Tcp object.

[Visual Basic]

' Declare as class member
Friend WithEvents Tcp1 As Tcp

' Create in class initialization
Me.Tcp1 = New Tcp()

[C#]
private Tcp tcp1 = new Tcp();

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp Constructor Overload List


Tcp Properties

The properties of the Tcp class are listed below. For a complete list of Tcp class members, see the Tcp Members topic.

Public Instance Properties

AutoReceive | Gets or sets a value which determines if data is automatically received.
Available | Gets the amount of data that has been received from the network and is available to be read.
Certificate | The Certificate object representing the certificate to use for optional client-side authentication.
Charset | Gets and sets the character set used for string/byte array conversions.
Connected | Gets the connected state of the connection.
ConnectTimeout | Gets or sets the number of milliseconds to wait for response from the server when connecting.
Container (inherited from Component) | Gets the IContainer that contains the Component.
DoEvents | Gets or sets a value that controls the processing of events during blocking method calls.
KeepAlive | Gets or sets the value of the socket's KeepAlive option.
LocalEndPoint | Returns the local address the socket is bound to.
NoDelay | Gets and sets a value the disables the use of Nagle's algorithm so that data is sent immediately.
OutOfBandInline | Gets or sets a value that indicates whether out-of-band (urgent) data is read as normal in-line data.
Proxy | Returns the Proxy instance that controls proxy server use.
ReceiveBufferSize | Gets and sets the size of the system receive buffer.
ReceiveTimeout | Gets and sets the number of milliseconds that a Receive method will block before throwing a SocketException.
RemoteCertificate | The Certificate object representing the certificate presented by the remote host during the SSL handshake.
RemoteEndPoint | Returns the remote address/port the socket is connected to.
ReuseAddress | Gets or sets a value that typically allows any local port to be specified, even if it is already in use.
SecureProtocol | Gets or sets a value which determines the type of encryption to use on the data.
SendBufferSize | Gets and sets the size of the system send buffer.
SendTimeout | Gets and sets the number of milliseconds that a Send method will block before throwing a SocketException.
Site (inherited from Component) | Gets or sets the ISite of the Component.
Socket | Returns a reference to the System.Net.Sockets.Socket instance being used.
Stream | Returns a SegmentedStream that can be used for advanced streaming operations on the socket.
SynchronizingObject | Set this object to automatically control thread marshalling between worker threads and the main UI thread.
Tag | Gets or sets an object reference that can be used to associate this instance with any other.
UseAuthentication | Gets or sets a value that determines if certificate authentication is used.
UseSslShutdown | Controls whether or not shut-down bytes are sent to the server when the connection is closed.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


AutoReceive Property

Tcp.AutoReceive Property

Gets or sets a value which determines if data is automatically received.

[Visual Basic]
Public Property AutoReceive As Boolean
[C#]
public bool AutoReceive { get; set; }
[C++]
public: __property bool get_AutoReceive();
public: __property void set_AutoReceive(bool );
[JScript]
public function get AutoReceive() : bool
public function set AutoReceive(bool);

Property Value

true if data is to be automatically received; false otherwise. The default value is false.

Remarks

Setting this property to true will cause the component to automatically post a BeginReceive immediately after connecting. Once data is received, the Object.EndReceive event is raised. Upon exiting this event, a new Object.BeginReceive is posted. As a result, when you use this methodology, you simply need to connect to the server and send data. Data is automatically received and Object.EndReceive is raised with no explicit call to Object.BeginReceive required.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Available Property

Tcp.Available Property

Gets the amount of data that has been received from the network and is available to be read.

[Visual Basic]
Public Property ReadOnly Available As Integer
[C#]
public int Available { get; }
[C++]
public: __property int get_Available();
[JScript]
public function get Available() : int

Property Value

The number of bytes of data that has been received from the network and are available to be read.

Remarks

When data is received from the network, it is collected in system buffers. The Available property contains the amount of bytes of data that has been received. In order to receive the data into a useful data structure such as a string, byte array, or Segment object that you can use within your application you must use the Receive or Tcp.Stream.Read methods. If these methods are not invoked or are seldom invoked, then "back pressure" is exerted at the remote host and packet transmission rates will decrease. If these methods are invoked, the data is received and removed from the system buffers, making room for more data to be received from the network.

Example

The following example demonstrates receiving a chunked response from the server. HTTP 1.1 allows a server to send a "chunked" response. When this occurs, the server will send the headers then a hex value representing the size of the next "chunk". This is continued until all data has been sent. This is a good stream example because it demonstrates both reading until a delimiter is found and reading fixed-size "chunks" of data.

[Visual Basic]
' Connect to HTTP Port
Tcp1.Connect("www.yahoo.com", 80)

' Send GET Request for home page. Be sure to specify HTTP/1.1 and Host
' to get a chunked response.
Dim command As Byte() = System.Text.Encoding.Default.GetBytes("GET / HTTP/1.1" + vbCrLf + "Host:www.yahoo.com" + vbCrLf + vbCrLf)
Tcp1.Stream.Write(command)

' Get the headers by reading until a double CRLF is found.
Dim found As Boolean = False
Dim s As String = Tcp1.Stream.Read(vbCrLf + vbCrLf, 1024, found)

Dim pagedata As String = ""

' Keep receiving data. When all data is sent, the server will close the connection.
Do While Tcp1.Connected

   ' Get the chunk size by reading until a CRLF is found.
   s = Tcp1.Stream.Read(vbCrLf, 1024, found)

   ' Remove the delimiter
   s = s.Trim()

   ' Make sure s has data
   If s <> "" Then

      ' Convert from string hex to decimal integer.
      Dim chunksize As Integer = System.Convert.ToInt32(s, 16)

      ' The final chunk will have size 0 and does not need to be handled.
      If chunksize <> 0 Then

         ' initialize byte array with chunk size
         Dim data(chunksize) As Byte

         ' Fill the byte array.
         Tcp1.Stream.Read(data, True)

         ' Add to the string
         pagedata += System.Text.Encoding.Default.GetString(data)
      End If
   End If
Loop

' Entire page should be retrieved by this point. Display
Debug.WriteLine(pagedata)

[C#]
// Connect to HTTP Port
tcp1.Connect("www.yahoo.com", 80);

// Send GET Request for home page. Be sure to specify HTTP/1.1 and Host
// to get a chunked response.
byte[] command  = System.Text.Encoding.Default.GetBytes("GET / HTTP/1.1\r\nHost:www.yahoo.com\r\n\r\n");
tcp1.Stream.Write(command);

// Get the headers by reading until a double CRLF is found.
bool found = false;
string s = tcp1.Stream.Read("\r\n\r\n", 1024, ref found);

string pagedata = "";

// Keep receiving data. When all data is sent, the server will close the connection.
while(tcp1.Connected)
{
   // Get the chunk size by reading until a CRLF is found.
   s = tcp1.Stream.Read("\r\n", 1024, ref found);

   // Remove the delimiter
   s = s.Trim();

   // Make sure s has data
   if(s != "")
   {
      // Convert from string hex to decimal integer.
      int chunksize = System.Convert.ToInt32(s, 16);

      // The final chunk will have size 0 and does not need to be handled.
      if(chunksize != 0)
      {
         // initialize byte array with chunk size
         byte[] data = new byte[chunksize];

         // Fill the byte array.
         tcp1.Stream.Read(data, true);

         // Add to the string
         pagedata+= System.Text.Encoding.Default.GetString(data);
      }
   }

}

// Entire page should be retrieved at this point. Display
Debug.WriteLine(pagedata);

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Certificate Property

Tcp.Certificate Property

The Certificate object representing the certificate to use for optional client-side authentication.

[Visual Basic]
Public Property Certificate As Certificate
[C#]
public Certificate Certificate { get; set; }
[C++]
public: __property Certificate* get_Certificate();
public: __property void set_Certificate(Certificate* );
[JScript]
public function get Certificate() : Certificate
public function set Certificate(Certificate);

Property Value

A Certificate object representing the certificate to use for optional client-side authentication; null otherwise.

Remarks

If a secure server requests a certificate from the client for client-authentication, the value of this property is sent to the server.

Typically this property can either be set before attempting to connect or from within the CertificateRequested event which is raised when the server requests a certificate from the client.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Charset Property

Tcp.Charset Property

Gets and sets the character set used for string/byte array conversions.

[Visual Basic]
Public Property Charset As String
[C#]
public string Charset { get; set; }
[C++]
public: __property String* get_Charset();
public: __property void set_Charset(String* );
[JScript]
public function get Charset() : String
public function set Charset(String);

Property Value

A string representing the character set used.

Remarks

This value defaults to the language used on the runtime machine (accessible through System.Text.Encoding.Default.BodyName). Set this property to the desired character set string to override this behavior. An example charset for Kanji is "ISO-2022-JP", while Latin-1 is "ISO-8859-1". "UTF-8" will always encode unicode strings, but not all mail readers support decoding this character set.

When communicating with clients from other countries set this property based on the standard string defined for the language intended. This enables the International client to be able to properly decode the message.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Connected Property

Tcp.Connected Property

Gets the connected state of the connection.

[Visual Basic]
Public Property ReadOnly Connected As Boolean
[C#]
public bool Connected { get; }
[C++]
public: __property bool get_Connected();
[JScript]
public function get Connected() : bool

Property Value

true if the TCP connection is connected to a remote resource and authenticated; otherwise, false.

Remarks

If the PowerTCP component is connected to a remote resource AND authenticated, this property returns true. If this property is false, the connection was either never connected, is no longer connected, or is connected but not yet authenticated. When receiving data from the server, this property is a good way to tell if all data has been received. Keep receiving data in a loop until this property equals false.

When using PowerTCP components which make use of the Tcp component as the underlying connection, this property returns the same value as the Object.Connection.Connected property (where Object.Connection exposes the Tcp object used for the connection).

The Object.ConnectedChanged and Object.ConnectedChangedEx events are raised whenever this property changes.

Example

The following example demonstrates the code required to build a simple echo server.

[Visual Basic]
Private Sub StartServer()
   ' Begin listening for connections on port 7.
   Server1.Listen(7)
End Sub

Private Sub Server1_Connection(ByVal sender As Object, ByVal e As ConnectionEventArgs) Handles Server1.Connection
   ' This event is raised on a new thread when a connection is received.
   Try
      ' Keep receiving data until connection is closed
      Do While (e.Tcp.Connected)
         ' Receive data.
         Dim seg As Segment = e.Tcp.Receive()

         ' Echo data back to client
         e.Tcp.Send(seg.ToString())
      Loop
   Catch ex As Exception
      'eat exception
   End Try
End Sub

[C#]
private void StartServer()
{
   // Begin listening for connections on port 7.
   server1.Listen(7);
}

private void server1_Connection(object sender, ConnectionEventArgs e)
{
   // This event is raised on a new thread when a connection is received.
   try
   {
      // Keep receiving data until connection is closed
      while(e.Tcp.Connected)
      {
         // Receive data.
         Segment seg = e.Tcp.Receive();

         // Echo data back to client.
         e.Tcp.Send(seg.ToString());
      }
   }
   catch(Exception ex)
   {
      // eat any exceptions
   }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


ConnectTimeout Property

Tcp.ConnectTimeout Property

Gets or sets the number of milliseconds to wait for response from the server when connecting.

[Visual Basic]
Public Property ConnectTimeout As Integer
[C#]
public int ConnectTimeout { get; set; }
[C++]
public: __property int get_ConnectTimeout();
public: __property void set_ConnectTimeout(int );
[JScript]
public function get ConnectTimeout() : int
public function set ConnectTimeout(int);

Property Value

The number of milliseconds to wait for response from the server when connecting. The default value is 0.

Remarks

The Object.Connect method will block for the amount of time specified by Object.ConnectTimeout. If no response is received from the server in this amount of time, a System.Net.SocketException will be thrown. The default value is 0, indicating no timeout is used.

NOTE. There is no pragmatic control over which the system will wait for a response. The generally accepted maximum wait time for Windows platforms appears to be 25 seconds. If you set this property for a value less than 25 seconds, PowerTCP will throw a SocketException. If you set it for a value greater than 25 seconds, the system may throw an exception before your specified timeout is reached.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


DoEvents Property

Tcp.DoEvents Property

Gets or sets a value that controls the processing of events during blocking method calls.

[Visual Basic]
Public Property DoEvents As Boolean
[C#]
public bool DoEvents { get; set; }
[C++]
public: __property bool get_DoEvents();
public: __property void set_DoEvents(bool );
[JScript]
public function get DoEvents() : bool
public function set DoEvents(bool);

Property Value

true if user-interface events should be processed during synchronous method calls; otherwise, false. The default value is true.

Remarks

When performing a synchronous (blocking) method, PowerTCP will process user-interface events (such as window painting) if this property is set to true AND the current thread has an event message queue. If no message queue is present (such as on an ASP page or under any worker thread), the value of this property has no effect. This property is used only for synchronous methods. Object.DoEvents is not needed if using asynchronous methods because the asynchronous method will execute on a different thread, allowing the UI thread to continue working unblocked.

For example, this property is beneficial when an interactive application is being used and the user may want to abort a currently processing operation by clicking an "Abort" button. If Object.DoEvents is set to false, this will not be possible. Set the Object.DoEvents property to true and the application will respond to other events (such as button clicks) during synchronous operations.

Example

The following example demonstrates some of the lesser used Tcp component members.

[Visual Basic]
' Disable UI events.
Tcp1.DoEvents = False

' Enable KeepAlive socket option
Tcp1.KeepAlive = True

' Disable use of Nagle's Algoritm
Tcp1.NoDelay = True

' Read urgent data as normal in-line data.
Tcp1.OutOfBandInline = True

' Allow addresses to be reused
Tcp1.ReuseAddress = True

' Connect
Tcp1.Connect("atropos", 7)

' Send data
Tcp1.Send("test")

' Receive response
Dim seg As Segment = Tcp1.Receive()

[C#]
// Disable UI events.
tcp1.DoEvents = false;

// Enable KeepAlive socket option
tcp1.KeepAlive = true;

// Disable use of Nagle's Algoritm
tcp1.NoDelay = true;

// Read urgent data as normal in-line data.
tcp1.OutOfBandInline = true;

// Allow addresses to be reused
tcp1.ReuseAddress = true

// Connect
tcp1.Connect("atropos", 7);

// Send data
tcp1.Send("test");

// Receive response
Segment seg = tcp1.Receive();

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


KeepAlive Property

Tcp.KeepAlive Property

Gets or sets the value of the socket's KeepAlive option.

[Visual Basic]
Public Property KeepAlive As Boolean
[C#]
public bool KeepAlive { get; set; }
[C++]
public: __property bool get_KeepAlive();
public: __property void set_KeepAlive(bool );
[JScript]
public function get KeepAlive() : bool
public function set KeepAlive(bool);

Property Value

true if packets are to be sent during inactive periods; otherwise, false. The default value is false.

Remarks

When a connection is inactive (data is not being sent or received for a period of time), setting KeepAlive to true causes the underlying Socket of the Tcp component to probe the other end of a connection when it has been idle for an allotted amount of time (usually 2 hours).

This property can be used to ensure a connection reset indication occurs during periods of inactivity.

The timeout before keepalives are sent and the interval between keepalive transmissions can be set by editing the system's registry.

1. Find the registry key.

For Windows 95/98/ME:

[HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP]

For other Operating Systems:

[HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Tcpip\Parameters]

2. Create a DWORD value "KeepAliveTime" and set it to the number of milliseconds to wait before sending keep alive packets (the default is 2 hours - 7,200,000 milliseconds).

3. Create a DWORD value (or string value for Windows 98) "KeepAliveInterval" and set it to the time in milliseconds between retransmissions of keepalives, once the KeepAliveTime has expired (the default is 1 second - 1000 milliseconds).

4. Restart Windows for the change to take effect.

Example

The following example demonstrates some of the lesser used Tcp component members.

[Visual Basic]
' Disable UI events.
Tcp1.DoEvents = False

' Enable KeepAlive socket option
Tcp1.KeepAlive = True

' Disable use of Nagle's Algoritm
Tcp1.NoDelay = True

' Read urgent data as normal in-line data.
Tcp1.OutOfBandInline = True

' Allow addresses to be reused
Tcp1.ReuseAddress = True

' Connect
Tcp1.Connect("atropos", 7)

' Send data
Tcp1.Send("test")

' Receive response
Dim seg As Segment = Tcp1.Receive()

[C#]
// Disable UI events.
tcp1.DoEvents = false;

// Enable KeepAlive socket option
tcp1.KeepAlive = true;

// Disable use of Nagle's Algoritm
tcp1.NoDelay = true;

// Read urgent data as normal in-line data.
tcp1.OutOfBandInline = true;

// Allow addresses to be reused
tcp1.ReuseAddress = true

// Connect
tcp1.Connect("atropos", 7);

// Send data
tcp1.Send("test");

// Receive response
Segment seg = tcp1.Receive();

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


LocalEndPoint Property

Tcp.LocalEndPoint Property

Returns the local address the socket is bound to.

[Visual Basic]
Public Property ReadOnly LocalEndPoint As IPEndPoint
[C#]
public IPEndPoint LocalEndPoint { get; }
[C++]
public: __property IPEndPoint* get_LocalEndPoint();
[JScript]
public function get LocalEndPoint() : IPEndPoint

Property Value

The local IPEndPoint that the Tcp object is using for communications.

Remarks

null is returned when the Connected property is false. When the Connected property is true this property returns the IPEndPoint instance representing the local address and port. If a local interface was specified using the Connect or BeginConnect to connect to the host, this property should reflect that interface. Otherwise this property will reflect the default interface.

To retrieve the local IP address, access Tcp.LocalEndPoint.Address. To retrieve the local port, access Tcp.LocalEndPoint.Port. As a shortcut, use the Tcp.LocalEndPoint.ToString method to return the IP address and port in address:port notation.

Example

The following example demonstrates using the ConnectedChanged event to notify the user of the status of the connection.

[Visual Basic]
Private Sub Tcp1_ConnectedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Tcp1.ConnectedChanged
   ' Get current state of connection
   If Tcp1.Connected Then
      Debug.WriteLine("Connection made")

      ' Display info about the local/remote endpoints
      Debug.WriteLine("Local endpoint: " + Tcp1.LocalEndPoint.ToString())
      Debug.WriteLine("Remote endpoint: " + Tcp1.RemoteEndPoint.ToString())
   Else
      Debug.WriteLine("Connection closed")
   End If
End Sub

[C#]
private void tcp1_ConnectedChanged(object sender, System.EventArgs e)
{
    // Get current state of connection
    if(tcp1.Connected)
    {
        Debug.WriteLine("Connection made");

        // Display info about the local/remote endpoints
        Debug.WriteLine("Local endpoint: " + tcp1.LocalEndPoint.ToString());
        Debug.WriteLine("Remote endpoint: " + tcp1.RemoteEndPoint.ToString());
    }
    else
        Debug.WriteLine("Connection closed");
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


NoDelay Property

Tcp.NoDelay Property

Gets and sets a value the disables the use of Nagle's algorithm so that data is sent immediately.

[Visual Basic]
Public Property NoDelay As Boolean
[C#]
public bool NoDelay { get; set; }
[C++]
public: __property bool get_NoDelay();
public: __property void set_NoDelay(bool );
[JScript]
public function get NoDelay() : bool
public function set NoDelay(bool);

Property Value

false if Nagle's algorithm is to be used; otherwise true. The default value is false.

Remarks

When small pieces of data (such as a byte) are send many times consecutively, inefficiency can result because a packet could be sent with 1 byte of useful data and 40 bytes of header information. Nagle's algorithm specifies that data such as this should be automatically concatenated and sent in a single packet. When true, Nagle's algorithm is defeated and data is immediately sent in a dedicated packet. When false, Nagle's algorithm is used so consecutive Send methods might send data as a single (more efficient) packet.

Setting this property to true could result in a speed optimization (because packets is sent immediately, without having to wait to see if Send is called again). Setting this property to false results in data being transmitted more efficiently.

Example

The following example demonstrates some of the lesser used Tcp component members.

[Visual Basic]
' Disable UI events.
Tcp1.DoEvents = False

' Enable KeepAlive socket option
Tcp1.KeepAlive = True

' Disable use of Nagle's Algoritm
Tcp1.NoDelay = True

' Read urgent data as normal in-line data.
Tcp1.OutOfBandInline = True

' Allow addresses to be reused
Tcp1.ReuseAddress = True

' Connect
Tcp1.Connect("atropos", 7)

' Send data
Tcp1.Send("test")

' Receive response
Dim seg As Segment = Tcp1.Receive()

[C#]
// Disable UI events.
tcp1.DoEvents = false;

// Enable KeepAlive socket option
tcp1.KeepAlive = true;

// Disable use of Nagle's Algoritm
tcp1.NoDelay = true;

// Read urgent data as normal in-line data.
tcp1.OutOfBandInline = true;

// Allow addresses to be reused
tcp1.ReuseAddress = true

// Connect
tcp1.Connect("atropos", 7);

// Send data
tcp1.Send("test");

// Receive response
Segment seg = tcp1.Receive();

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


OutOfBandInline Property

Tcp.OutOfBandInline Property

Gets or sets a value that indicates whether out-of-band (urgent) data is read as normal in-line data.

[Visual Basic]
Public Property OutOfBandInline As Boolean
[C#]
public bool OutOfBandInline { get; set; }
[C++]
public: __property bool get_OutOfBandInline();
public: __property void set_OutOfBandInline(bool );
[JScript]
public function get OutOfBandInline() : bool
public function set OutOfBandInline(bool);

Property Value

true if urgent data is to be read as normal in-line data, otherwise false. The default value is false.

Remarks

When the "urgent" socket flag is set, this means that the packet contains data that should be acted upon before "non-urgent" data. Setting this property to true will cause this urgent data to be read in-line. If this property is set to false, the typical technique used to receive out-of-band data is BeginReceive(SocketFlags.Urgent) which posts a blocking receive on the socket waiting for urgent data to arrive.

To minimize interoperability problems, applications writers are advised not to use out-of-band data unless this is required in order to interoperate with an existing service.

Example

The following example demonstrates some of the lesser used Tcp component members.

[Visual Basic]
' Disable UI events.
Tcp1.DoEvents = False

' Enable KeepAlive socket option
Tcp1.KeepAlive = True

' Disable use of Nagle's Algoritm
Tcp1.NoDelay = True

' Read urgent data as normal in-line data.
Tcp1.OutOfBandInline = True

' Allow addresses to be reused
Tcp1.ReuseAddress = True

' Connect
Tcp1.Connect("atropos", 7)

' Send data
Tcp1.Send("test")

' Receive response
Dim seg As Segment = Tcp1.Receive()

[C#]
// Disable UI events.
tcp1.DoEvents = false;

// Enable KeepAlive socket option
tcp1.KeepAlive = true;

// Disable use of Nagle's Algoritm
tcp1.NoDelay = true;

// Read urgent data as normal in-line data.
tcp1.OutOfBandInline = true;

// Allow addresses to be reused
tcp1.ReuseAddress = true

// Connect
tcp1.Connect("atropos", 7);

// Send data
tcp1.Send("test");

// Receive response
Segment seg = tcp1.Receive();

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Proxy Property

Tcp.Proxy Property

Returns the Proxy instance that controls proxy server use.

[Visual Basic]
Public Property ReadOnly Proxy As Proxy
[C#]
public Proxy Proxy { get; }
[C++]
public: __property Proxy* get_Proxy();
[JScript]
public function get Proxy() : Proxy

Property Value

The Proxy object to use to control proxy server use.

Remarks

Some networks are configured to require your use of an TCP proxy server. PowerTCP supports most types. Configure your proxy use by specifying the properties of this Proxy object.

Use the Proxy property if your application needs to connect with one of the following proxies:

  • SOCKS v4
  • SOCKS v5

Example

The following example demonstrates asynchronously connecting using the BeginConnect method.

[Visual Basic]
Private Sub Test()
   ' Begin to asynchronously connect to an echo port.
   Tcp1.BeginConnect("atropos", 7)
End Sub

Private Sub Tcp1_EndConnect(ByVal sender As Object, ByVal e As ExceptionEventArgs) Handles Tcp1.EndConnect
   ' Connect complete, check for any exceptions
   If e.Exception Is Nothing Then
      ' Now send some data.
      Tcp1.Send("hello")

      ' Receive the data back.
      Dim seg As Segment = Tcp1.Receive()
      Debug.WriteLine(seg.ToString())
   End If
End Sub

[C#]
private void Test()
{
   // Begin to asynchronously connect to an echo port.
   tcp1.BeginConnect("atropos", 7);
}

private void tcp1_EndConnect(object sender, ExceptionEventArgs e)
{
   // Connect complete, check for any exceptions
   if(e.Exception == null)
   {
      // Now send some data.
      tcp1.Send("hello");

      // Receive the data back.
      Segment seg = tcp1.Receive();

      Debug.WriteLine(seg.ToString());
   }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


ReceiveBufferSize Property

Tcp.ReceiveBufferSize Property

Gets and sets the size of the system receive buffer.

[Visual Basic]
Public Property ReceiveBufferSize As Integer
[C#]
public int ReceiveBufferSize { get; set; }
[C++]
public: __property int get_ReceiveBufferSize();
public: __property void set_ReceiveBufferSize(int );
[JScript]
public function get ReceiveBufferSize() : int
public function set ReceiveBufferSize(int);

Property Value

Size of the system receive buffer in bytes. The default is 8192.

Remarks

This property sets the size of the system receive buffer. The default is 8192 which means that if the total data's bytes you are receiving exceeds this you will need to call Receive multiple times until Connected = false.

Example

The following example demonstrates sending and receiving data using byte arrays.

[Visual Basic]
' Connect to an echo port
Tcp1.Connect("atropos", 7)

' Send some bytes
Dim buffer As Byte() = System.Text.Encoding.Default.GetBytes("test")
Tcp1.Stream.Write(buffer, 0, buffer.Length)

' Receive the echoed data
Dim response(Tcp1.ReceiveBufferSize) As Byte
Tcp1.Stream.Read(response, 0, Tcp1.ReceiveBufferSize)

' Close the connection
Tcp1.Close()

' Display the response
Debug.WriteLine(System.Text.Encoding.Default.GetString(response))

[C#]
// Connect to an echo port
tcp1.Connect("atropos", 7);

// Send some bytes
byte[] buffer = System.Text.Encoding.Default.GetBytes("test");
tcp1.Stream.Write(buffer, 0, buffer.Length);

// Receive the echoed data
byte[] response = new byte[tcp1.ReceiveBufferSize];
tcp1.Stream.Read(response, 0, tcp1.ReceiveBufferSize);

// Close the connection
tcp1.Close();

// Display the response
Debug.WriteLine(System.Text.Encoding.Default.GetString(response));

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


ReceiveTimeout Property

Tcp.ReceiveTimeout Property

Gets and sets the number of milliseconds that a Receive method will block before throwing a SocketException.

[Visual Basic]
Public Property ReceiveTimeout As Integer
[C#]
public int ReceiveTimeout { get; set; }
[C++]
public: __property int get_ReceiveTimeout();
public: __property void set_ReceiveTimeout(int );
[JScript]
public function get ReceiveTimeout() : int
public function set ReceiveTimeout(int);

Property Value

The timeout (in milliseconds) for completing a blocking Receive or Tcp.Stream.Read.

Remarks

The Tcp component will block (not execute further code on the main thread) until either the data requested is received or until the method blocks for the time specified in ReceiveTimeout, at which point a SocketException is thrown. The default is 0, which indicates no timeout. When using BeginReceive, the EndReceive event will fire with a SocketException, if the ReceiveTimeout period expires.

This property is useful for determining network failure while receiving data. It is also useful for cases where the response from the server has to occur quickly or not at all, such as in an ASP script or when connecting and receiving data from a series of sockets in a batch process.

If building a server application, this value determines how long a child connection can be idle before disconnecting them.

Note: If the ReceiveTimeout period expires, the resulting SocketException will NOT cause the connection to sever. This is different behavior that earlier versions of the Tcp object.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


RemoteCertificate Property

Tcp.RemoteCertificate Property

The Certificate object representing the certificate presented by the remote host during the SSL handshake.

[Visual Basic]
Public Property ReadOnly RemoteCertificate As Certificate
[C#]
public Certificate RemoteCertificate { get; }
[C++]
public: __property Certificate* get_RemoteCertificate();
[JScript]
public function get RemoteCertificate() : Certificate

Property Value

A Certificate object representing the certificate presented by the remote host during the SSL handshake.

Remarks

If a secure connection was established and the remote host presented a certificate, RemoteCertificate will be a representation of this certificate.

This property will always be set if a secure connection is established and the remote host is the server. If the remote host is a client, it will only be set if client certificate authentication takes place.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


RemoteEndPoint Property

Tcp.RemoteEndPoint Property

Returns the remote address/port the socket is connected to.

[Visual Basic]
Public Property ReadOnly RemoteEndPoint As IPEndPoint
[C#]
public IPEndPoint RemoteEndPoint { get; }
[C++]
public: __property IPEndPoint* get_RemoteEndPoint();
[JScript]
public function get RemoteEndPoint() : IPEndPoint

Property Value

The remote IPEndPoint that the Tcp object is using for communications.

Remarks

null is returned when the Connected property is false. When the Connected property is true this property returns the IPEndPoint instance representing the remote address and port.

To retrieve the remote IP address, access Tcp.RemoteEndPoint.Address. To retrieve the remote port, access Tcp.RemoteEndPoint.Port. As a shortcut, use the Tcp.RemoteEndPoint.ToString method to return the IP address and port in address:port notation.

Example

The following example demonstrates using the ConnectedChanged event to notify the user of the status of the connection.

[Visual Basic]
Private Sub Tcp1_ConnectedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Tcp1.ConnectedChanged
   ' Get current state of connection
   If Tcp1.Connected Then
      Debug.WriteLine("Connection made")

      ' Display info about the local/remote endpoints
      Debug.WriteLine("Local endpoint: " + Tcp1.LocalEndPoint.ToString())
      Debug.WriteLine("Remote endpoint: " + Tcp1.RemoteEndPoint.ToString())
   Else
      Debug.WriteLine("Connection closed")
   End If
End Sub

[C#]
private void tcp1_ConnectedChanged(object sender, System.EventArgs e)
{
    // Get current state of connection
    if(tcp1.Connected)
    {
        Debug.WriteLine("Connection made");

        // Display info about the local/remote endpoints
        Debug.WriteLine("Local endpoint: " + tcp1.LocalEndPoint.ToString());
        Debug.WriteLine("Remote endpoint: " + tcp1.RemoteEndPoint.ToString());
    }
    else
        Debug.WriteLine("Connection closed");
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


ReuseAddress Property

Tcp.ReuseAddress Property

Gets or sets a value that typically allows any local port to be specified, even if it is already in use.

[Visual Basic]
Public Property ReuseAddress As Boolean
[C#]
public bool ReuseAddress { get; set; }
[C++]
public: __property bool get_ReuseAddress();
public: __property void set_ReuseAddress(bool );
[JScript]
public function get ReuseAddress() : bool
public function set ReuseAddress(bool);

Property Value

true if a specific local port number is desired for multiple active connections; otherwise false. The default is false, to indicate it should not be allowed.

Remarks

The option is used (set to true) when a specific local port number is desired for multiple active connections.

Example

The following example demonstrates some of the lesser used Tcp component members.

[Visual Basic]
' Disable UI events.
Tcp1.DoEvents = False

' Enable KeepAlive socket option
Tcp1.KeepAlive = True

' Disable use of Nagle's Algoritm
Tcp1.NoDelay = True

' Read urgent data as normal in-line data.
Tcp1.OutOfBandInline = True

' Allow addresses to be reused
Tcp1.ReuseAddress = True

' Connect
Tcp1.Connect("atropos", 7)

' Send data
Tcp1.Send("test")

' Receive response
Dim seg As Segment = Tcp1.Receive()

[C#]
// Disable UI events.
tcp1.DoEvents = false;

// Enable KeepAlive socket option
tcp1.KeepAlive = true;

// Disable use of Nagle's Algoritm
tcp1.NoDelay = true;

// Read urgent data as normal in-line data.
tcp1.OutOfBandInline = true;

// Allow addresses to be reused
tcp1.ReuseAddress = true

// Connect
tcp1.Connect("atropos", 7);

// Send data
tcp1.Send("test");

// Receive response
Segment seg = tcp1.Receive();

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


SecureProtocol Property

Tcp.SecureProtocol Property

Gets or sets a value which determines the type of encryption to use on the data.

[Visual Basic]
Public Property SecureProtocol As SecureProtocol
[C#]
public SecureProtocol SecureProtocol { get; set; }
[C++]
public: __property SecureProtocol get_SecureProtocol();
public: __property void set_SecureProtocol(SecureProtocol );
[JScript]
public function get SecureProtocol() : SecureProtocol
public function set SecureProtocol(SecureProtocol);

Property Value

A SecureProtocol value.

Remarks

Set this property to set the type of encryption to use on the data sent/received. This property defaults to SecureProtocol.None, signifying no encryption is used on the data.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


SendBufferSize Property

Tcp.SendBufferSize Property

Gets and sets the size of the system send buffer.

[Visual Basic]
Public Property SendBufferSize As Integer
[C#]
public int SendBufferSize { get; set; }
[C++]
public: __property int get_SendBufferSize();
public: __property void set_SendBufferSize(int );
[JScript]
public function get SendBufferSize() : int
public function set SendBufferSize(int);

Property Value

The size of the system send buffer in bytes. The default is 8192.

Remarks

This property sets the size of the system send buffer. The default is 8192 which means that if the total data's bytes you are sending exceeds this you will need to call Send multiple times.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


SendTimeout Property

Tcp.SendTimeout Property

Gets and sets the number of milliseconds that a Send method will block before throwing a SocketException.

[Visual Basic]
Public Property SendTimeout As Integer
[C#]
public int SendTimeout { get; set; }
[C++]
public: __property int get_SendTimeout();
public: __property void set_SendTimeout(int );
[JScript]
public function get SendTimeout() : int
public function set SendTimeout(int);

Property Value

The timeout (in milli-seconds) for completing a blocking Send or Write. The default is 0, which indicates no timeout.

Remarks

The Tcp component will block (not execute further code on the main thread) until either the data is sent or until the method blocks for the time specified in SendTimeout, at which point a SocketException is thrown. The default is 0, which indicates no timeout. Setting this property has no effect on asynchronous methods such as BeginSend.

This property is useful for determining network failure while sending data. It is also useful for cases where sending data has to occur quickly or not at all, such as in an ASP script or when connecting and sending data to a series of sockets in a batch process.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Socket Property

Tcp.Socket Property

Returns a reference to the System.Net.Sockets.Socket instance being used.

[Visual Basic]
Public Property ReadOnly Socket As Socket
[C#]
public Socket Socket { get; }
[C++]
public: __property Socket* get_Socket();
[JScript]
public function get Socket() : Socket

Property Value

The System.Net.Sockets.Socket being used for the TCP connection.

Remarks

The Socket used for the TCP connection is exposed through this property. It is not recommended to read or write to the TCP stream using the Socket object directly. To read or write, use the higher-level methods such as Receive or Send, or members of Stream such as Tcp.Stream.Read and Tcp.Stream.Write.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Stream Property

Tcp.Stream Property

Returns a SegmentedStream that can be used for advanced streaming operations on the socket.

[Visual Basic]
Public Property Stream As SegmentedStream
[C#]
public SegmentedStream Stream { get; set; }
[C++]
public: __property SegmentedStream* get_Stream();
public: __property void set_Stream(SegmentedStream* );
[JScript]
public function get Stream() : SegmentedStream
public function set Stream(SegmentedStream);

Property Value

A SegmentedStream object.

Remarks

Typically, when data needs to be send or received, the Object.Send or Object.Receive methods can be used. However, often advanced streaming operations are required. Two of the most common are reading token-delimited segments and fixed-length segments. To read fixed-length segments, simply create a fixed-size byte array the size of the segment you would like to read. Then use the Object.Stream.Read method, passing in the byte array and true as the fill parameter. Data is read until either all available data has been received, or the array has been completely filled with data. To read token-delimited segments, create an array of characters that you would like to use as a delimiter. Then use the Object.Stream.Read, passing in the delimiter array. Data is read until the delimiter has been reached. If the delimiter is not found, data is read until all data has been received.

Note: The following applies to using the Stream property with secure PowerTCP implementations only! In addition, you can change the initialization of this property to change the behavior of the way data is read or written. Since SegmentedStream is a PipeStream type, Object.Stream.CoreStream can be changed to any type of PipeStream. The PowerTCP secure implementation works this way. For example, if you wish to change to secure communications using SSL, you would initlialize the Object.Stream property using an SslStream like so,

// Initialize the Stream property to a new PipeStream "combination", enabling SSL communication.
// (This only applies to using the Tcp component to communicate securely.)
tcp1.Stream = new SegmentedStream(new SslStream(new TcpStream(tcp1)));

And, to switch back to "normal" communications,

// Switch back to a non-secure PipeStream "combination.
tcp1.Stream = new SegmentedStream(new TcpStream(tcp1));

Note for Tcp component usage only:Internally, the Tcp component will "scan" this property to link in the Tcp.CertificateReceivedEvent and Tcp.CertificateRequestedEvent, so these events do not need to be explicitly linked in unless you require advanced functionality.

Example

The following example demonstrates connecting implementing the SMTP protocol using the Tcp component's stream interface to send a simple message.

[Visual Basic]
' The following code assumes that good responses are always received from
' the server. More robust code should check each response and handle appropriately.

' Connect to SMTP port
Tcp1.Connect("mail", 25)

' Send the EHLO command
Tcp1.Stream.Write("EHLO myserver\r\n")

' Get response from the server
Dim s As String = Tcp1.Stream.Read()

' Send MAIL FROM command
Tcp1.Stream.Write("MAIL FROM: test@dart.com" + vbCrLf)

' Get response from the server
s = Tcp1.Stream.Read()

' Send RCPT TO command
Tcp1.Stream.Write("RCPT TO: cranford@dart.com" + vbCrLf)

' Get response from the server
s = Tcp1.Stream.Read()

' Send DATA command
Tcp1.Stream.Write("DATA" + vbCrLf)

' Get response from the server
s = Tcp1.Stream.Read()

' Send DATA
Tcp1.Stream.Write("Test Message" + vbCrLf + "." + vbCrLf)

' Receive response from the server
s = Tcp1.Stream.Read()

' Write output
Debug.WriteLine("Operation complete. The following information")
Debug.WriteLine("was reported by the server:")
Debug.WriteLine(s)

[C#]
// The following code assumes that good responses are always received from
// the server. More robust code should check each response and handle appropriately.

// Connect to SMTP port
tcp1.Connect("mail", 25);

// Send the EHLO command
tcp1.Stream.Write("EHLO myserver\r\n");

// Get response from the server
string s = tcp1.Stream.Read();

// Send MAIL FROM command
tcp1.Stream.Write("MAIL FROM: test@dart.com\r\n");

// Get response from the server
s = tcp1.Stream.Read();

// Send RCPT TO command
tcp1.Stream.Write("RCPT TO: cranford@dart.com\r\n");

// Get response from the server
s = tcp1.Stream.Read();

// Send DATA command
tcp1.Stream.Write("DATA\r\n");

// Get response from the server
s = tcp1.Stream.Read();

// Send DATA
tcp1.Stream.Write("Test Message\r\n.\r\n");

// Receive response from the server
s = tcp1.Stream.Read();

// Write output
Debug.WriteLine("Operation complete. The following information");
Debug.WriteLine("was reported by the server:");
Debug.WriteLine(s);

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


SynchronizingObject Property

Tcp.SynchronizingObject Property

Set this object to automatically control thread marshalling between worker threads and the main UI thread.

[Visual Basic]
Public Property SynchronizingObject As ISynchronizeInvoke
[C#]
public ISynchronizeInvoke SynchronizingObject { get; set; }
[C++]
public: __property ISynchronizeInvoke* get_SynchronizingObject();
public: __property void set_SynchronizingObject(ISynchronizeInvoke* );
[JScript]
public function get SynchronizingObject() : ISynchronizeInvoke
public function set SynchronizingObject(ISynchronizeInvoke);

Property Value

If used, the main UI thread object; null if unused.

Remarks

Any application that (1) uses multithreading (for example, an application which uses an asynchronous BeginXXX method) and (2) must update a shared UI element on the main UI thread (such as a ListView object) from one of these worker threads must set this property to the value of the main UI thread object. If the application meets both of these requirements and this property is NOT set, you may see strange behavior in your application (such as strange exceptions or improper UI element values).

If you do not know whether or not you need to use this property, simply take the failsafe approach when programming Windows applications and always set this property to the Main Form object. If any thread marshalling has to occur between a worker thread and the UI thread, it will occur automatically.

Provides data for the CollectionChanged event. NOTE for server implementations: If you are using a PowerTCP server component to build a server application, you do not want to set this property (as it will cause the server application to become single-threaded). Instead, you want to use the Control.BeginInvoke method to thread-marshall to the main UI thread (see any of the installed sample server applications for an example of this).

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Tag Property

Tcp.Tag Property

Gets or sets an object reference that can be used to associate this instance with any other.

[Visual Basic]
Public Property Tag As Object
[C#]
public object Tag { get; set; }
[C++]
public: __property Object* get_Tag();
public: __property void set_Tag(Object* );
[JScript]
public function get Tag() : Object
public function set Tag(Object);

Property Value

Any object that is associated with the component; null if no objects are associated with the component. Any object that is associated with the object, null if no objects are associated with the object

Remarks

Use this property to associate any type derived from Object class with the component. A common use for the Tag property is to store data that is closely associated with the component.

Use this property to associate any object with the object.

Example

The following example demonstrates a simple multi-client chat server.

[Visual Basic]
Private Sub StartServer()
   ' Begin listening for connections on port 8888.
   Server1.Listen(8888)
End Sub

Private Sub Server1_Connection(ByVal sender As Object, ByVal e As ConnectionEventArgs) Handles Server1.Connection
   ' This event is raised on a new thread when a connection is received.
   Try
      ' Send username command.
      e.Tcp.Stream.Write("Please enter your username: ")

      ' Read until a CRLF is reached
      Dim found As Boolean = False
      Dim s As String = e.Tcp.Stream.Read(vbCrLf, 1024, found)

      If (found) Then
         ' Trim(whitespace)
         s = s.Trim()

         ' Associate username with TCP instance
         e.Tcp.Tag = s
         e.Tcp.Stream.Write("Go ahead and chat" + vbCrLf)
      Else
         ' Disconnect
         e.Tcp.Stream.Write("Bad Input" + vbCrLf)
         e.Tcp.Stream.Close()
      End If

      Do While (e.Tcp.Connected)

         ' Receive data.
         found = False
         Dim text As String = e.Tcp.Stream.Read(vbCrLf, 1024, found)

         ' Echo data back to all clients
         Dim tcp As Tcp
         For Each tcp In Server1.Connections
            ' Preface text with user name and send
            tcp.Stream.Write(e.Tcp.Tag.ToString() + ": " + text + vbCrLf)
         Next
      Loop
   Catch ex As Exception
      ' eat exception
   End Try
End Sub

[C#]
private void StartServer()
{
   // Begin listening for connections on port 8888.
   server1.Listen(8888);
}

private void server1_Connection(object sender, ConnectionEventArgs e)
{
   // This event is raised on a new thread when a connection is received.
   try
   {
      // Send username command.
      e.Tcp.Stream.Write("Please enter your username: ");

      // Read until a CRLF is reached
      bool found = false;
      string s = e.Tcp.Stream.Read("\r\n", 1024, ref found);

      if(found)
      {
         // Trim whitespace
         s = s.Trim();

         // Associate username with TCP instance
         e.Tcp.Tag = s;
         e.Tcp.Stream.Write("Go ahead and chat\r\n");
      }
      else
      {
         // Disconnect
         e.Tcp.Stream.Write("Bad Input\r\n");
         e.Tcp.Stream.Close();
      }
      while(e.Tcp.Connected)
      {
         // Receive data.
         found = false;
         string text = e.Tcp.Stream.Read("\r\n", 1024, ref found);

         // Echo data back to all clients
         foreach(Tcp tcp in server1.Connections)
         {
            // Preface text with user name (from Tcp.Tag) and send
            tcp.Stream.Write(e.Tcp.Tag.ToString() + ": " + text + "\r\n");
         }
      }
   }
   catch(Exception ex)
   {
      // eat exception
   }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


UseAuthentication Property

Tcp.UseAuthentication Property

Gets or sets a value that determines if certificate authentication is used.

[Visual Basic]
Public Property UseAuthentication As Boolean
[C#]
public bool UseAuthentication { get; set; }
[C++]
public: __property bool get_UseAuthentication();
public: __property void set_UseAuthentication(bool );
[JScript]
public function get UseAuthentication() : bool
public function set UseAuthentication(bool);

Property Value

A Boolean value which determines if certificate authentication is used. Defaults to true.

Remarks

If set to true, you must control the acceptance/denial of certificates in the CertificateReceived event. If set to false, all certificates will be accepted no matter if they are valid or invalid.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


UseSslShutdown Property

Tcp.UseSslShutdown Property

Controls whether or not shut-down bytes are sent to the server when the connection is closed.

[Visual Basic]
Public Property UseSslShutdown As Boolean
[C#]
public bool UseSslShutdown { get; set; }
[C++]
public: __property bool get_UseSslShutdown();
public: __property void set_UseSslShutdown(bool );
[JScript]
public function get UseSslShutdown() : bool
public function set UseSslShutdown(bool);

Property Value

True if shut-down bytes are to be sent to the server; false otherwise. The default value is true.

Remarks

When the Object.Close method is used to close down a secure connection, the component will send out shut-down bytes to attempt to gracefully shut down the connection. However, some servers do not expect these shut-down bytes and, as a result, the connection can be improperly closed. If this is the case, set this property to false and no shut-down bytes will be sent when the connection is closed.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Tcp Methods

The methods of the Tcp class are listed below. For a complete list of Tcp class members, see the Tcp Members topic.

Public Instance Methods

BeginConnect | Overloaded. Connect to a server asynchronously, specifying the local interface and a range of local ports to use. The EndConnect event is raised when completed.
BeginReceive | Overloaded. Receive data into your buffer asynchronously specifying a buffer, offset, count and SocketFlags value. The EndReceive event is raised when completed.
BeginSend | Overloaded. Send data from your buffer asynchronously, specifying a buffer, offset, count and SocketFlags value. The EndSend event is raised when completed.
Close | Overloaded. Close the connection.
Connect | Overloaded. Connect to a host, specifying the local interface and a range of local ports to use.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose (inherited from Component) | Releases all resources used by the Component.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
Receive | Overloaded. Receive data from the host, specifying a buffer, offset, count and SocketFlags value.
Send | Overloaded. Send data to the server, specifying a buffer, offset, count and SocketFlags value.
ToString (inherited from Component) | Overridden.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


BeginConnect Method

Tcp.BeginConnect Method

Connect to a server asynchronously. The EndConnect event is raised when completed.

Overload List

Connect to a server asynchronously. The EndConnect event is raised when completed.

[Visual Basic] Public Function BeginConnect(ByVal String,ByVal Integer) As IAsyncResult
[C#] public IAsyncResult BeginConnect(string,int);
[C++] public: IAsyncResult* BeginConnect(String*,int);
[JScript] public function BeginConnect(String,int): IAsyncResult;

Connect to a server asynchronously, specifying the local interface and a range of local ports to use. The EndConnect event is raised when completed.

[Visual Basic] Overridable OverloadsPublic Function BeginConnect(ByVal String,ByVal Integer,ByVal String,ByVal Integer,ByVal Integer,ByVal Object) As IAsyncResult
[C#] public virtual IAsyncResult BeginConnect(string,int,string,int,int,object);
[C++] public: virtual IAsyncResult* BeginConnect(String*,int,String*,int,int,Object*);
[JScript] public virtual function BeginConnect(String,int,String,int,int,Object): IAsyncResult;

Connect to a server asynchronously, specifying the local interface to use. The EndConnect event is raised when completed.

[Visual Basic] Public Function BeginConnect(ByVal String,ByVal Integer,ByVal String,ByVal Integer,ByVal Object) As IAsyncResult
[C#] public IAsyncResult BeginConnect(string,int,string,int,object);
[C++] public: IAsyncResult* BeginConnect(String*,int,String*,int,Object*);
[JScript] public function BeginConnect(String,int,String,int,Object): IAsyncResult;

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


BeginConnect Method (String, Int32)

Tcp.BeginConnect Method (String, Int32)

Connect to a server asynchronously. The EndConnect event is raised when completed.

[Visual Basic]
Public Function BeginConnect( _
   ByVal server As String, _
   ByVal serverPort As Integer _
) As IAsyncResult
[C#]
public IAsyncResult BeginConnect(
   string server,
   int serverPort
);
[C++]
public: IAsyncResult* BeginConnect(
   String* server,
   int serverPort
);
[JScript]
public function BeginConnect(
   String server,
   int serverPort
): IAsyncResult;

Parameters

server
Remote hostname or address in dot notation.
serverPort
Remote port, a number between 1 and 65535, inclusive.

Return Value

An IAsyncResult that represents the asynchronous operation, which could still be pending.

Remarks

Use this method if you wish to connect to a host transparently with minimal application impact, as execution occurs on another thread. This method begins to asynchronously connect to the server. Upon completion (on both success and failure) the EndConnect event is raised. An EventArgs object is passed into this event, containing information about the event. If the connection succeeds, the ConnectedChanged event is raised. Once the connection has been made, you can send and receive data from the remote device.

If you are using the Tcp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the EventHandler delegate.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

To connect synchronously, use the Connect method.

Exceptions

Exception Type | Condition
InvalidOperationException | BeginXXX method used without providing an EndXXX event handler.

Example

The following example demonstrates asynchronously connecting using the BeginConnect method.

[Visual Basic]
Private Sub Test()
   ' Begin to asynchronously connect to an echo port.
   Tcp1.BeginConnect("atropos", 7)
End Sub

Private Sub Tcp1_EndConnect(ByVal sender As Object, ByVal e As ExceptionEventArgs) Handles Tcp1.EndConnect
   ' Connect complete, check for any exceptions
   If e.Exception Is Nothing Then
      ' Now send some data.
      Tcp1.Send("hello")

      ' Receive the data back.
      Dim seg As Segment = Tcp1.Receive()
      Debug.WriteLine(seg.ToString())
   End If
End Sub

[C#]
private void Test()
{
   // Begin to asynchronously connect to an echo port.
   tcp1.BeginConnect("atropos", 7);
}

private void tcp1_EndConnect(object sender, ExceptionEventArgs e)
{
   // Connect complete, check for any exceptions
   if(e.Exception == null)
   {
      // Now send some data.
      tcp1.Send("hello");

      // Receive the data back.
      Segment seg = tcp1.Receive();

      Debug.WriteLine(seg.ToString());
   }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.BeginConnect Overload List


BeginConnect Method (String, Int32, String, Int32, Int32, Object)

Tcp.BeginConnect Method (String, Int32, String, Int32, Int32, Object)

Connect to a server asynchronously, specifying the local interface and a range of local ports to use. The EndConnect event is raised when completed.

[Visual Basic]
Overridable  OverloadsPublic Function BeginConnect( _
   ByVal server As String, _
   ByVal serverPort As Integer, _
   ByVal client As String, _
   ByVal clientPortMin As Integer, _
   ByVal clientPortMax As Integer, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public virtual IAsyncResult BeginConnect(
   string server,
   int serverPort,
   string client,
   int clientPortMin,
   int clientPortMax,
   object state
);
[C++]
public: virtual IAsyncResult* BeginConnect(
   String* server,
   int serverPort,
   String* client,
   int clientPortMin,
   int clientPortMax,
   Object* state
);
[JScript]
public virtual function BeginConnect(
   String server,
   int serverPort,
   String client,
   int clientPortMin,
   int clientPortMax,
   Object state
): IAsyncResult;

Parameters

server
Remote hostname or address in dot notation.
serverPort
Remote port, a number between 1 and 65535, inclusive.
client
Optional local hostname or address in dot notation. Use "" as default.
clientPortMin
The minimum client port number to use as a local interface.
clientPortMax
The maximim client port number to use as a local interface.
state
User state information.

Return Value

An IAsyncResult that represents the asynchronous operation, which could still be pending.

Remarks

Use this method if you wish to connect to a host transparently with minimal application impact, as execution occurs on another thread. This method begins to asynchronously connect to the server. Upon completion (on both success and failure) the EndConnect event is raised. An EventArgs object is passed into this event, containing information about the event. If the connection succeeds, the ConnectedChanged event is raised. Once the connection has been made, you can send and receive data from the remote device.

If you are using the Tcp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the EventHandler delegate.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

To connect synchronously, use the Connect method.

Exceptions

Exception Type | Condition
InvalidOperationException | BeginXXX method used without providing an EndXXX event handler.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.BeginConnect Overload List


BeginConnect Method (String, Int32, String, Int32, Object)

Tcp.BeginConnect Method (String, Int32, String, Int32, Object)

Connect to a server asynchronously, specifying the local interface to use. The EndConnect event is raised when completed.

[Visual Basic]
Public Function BeginConnect( _
   ByVal server As String, _
   ByVal serverPort As Integer, _
   ByVal client As String, _
   ByVal clientPort As Integer, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginConnect(
   string server,
   int serverPort,
   string client,
   int clientPort,
   object state
);
[C++]
public: IAsyncResult* BeginConnect(
   String* server,
   int serverPort,
   String* client,
   int clientPort,
   Object* state
);
[JScript]
public function BeginConnect(
   String server,
   int serverPort,
   String client,
   int clientPort,
   Object state
): IAsyncResult;

Parameters

server
Remote hostname or address in dot notation.
serverPort
Remote port, a number between 1 and 65535, inclusive.
client
Optional local hostname or address in dot notation. Use "" as default.
clientPort
Optional local port, a number between 1 and 65535, inclusive. Use 0 as default.
state
User state information.

Return Value

An IAsyncResult that represents the asynchronous operation, which could still be pending.

Remarks

Use this method if you wish to connect to a host transparently with minimal application impact, as execution occurs on another thread. This method begins to asynchronously connect to the server. Upon completion (on both success and failure) the EndConnect event is raised. An EventArgs object is passed into this event, containing information about the event. If the connection succeeds, the ConnectedChanged event is raised. Once the connection has been made, you can send and receive data from the remote device.

If you are using the Tcp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the EventHandler delegate.

For more information on implementing and handling events using PowerTCP.NET, see the topic, Using Events In PowerTCP.

To connect synchronously, use the Connect method.

Exceptions

Exception Type | Condition
InvalidOperationException | BeginXXX method used without providing an EndXXX event handler.

Example

The following example demonstrates asynchronously connecting using the BeginConnect method.

[Visual Basic]
Private Sub Test()
   ' Begin to asynchronously connect to an echo port.
   Tcp1.BeginConnect("atropos", 7)
End Sub

Private Sub Tcp1_EndConnect(ByVal sender As Object, ByVal e As ExceptionEventArgs) Handles Tcp1.EndConnect
   ' Connect complete, check for any exceptions
   If e.Exception Is Nothing Then
      ' Now send some data.
      Tcp1.Send("hello")

      ' Receive the data back.
      Dim seg As Segment = Tcp1.Receive()
      Debug.WriteLine(seg.ToString())
   End If
End Sub

[C#]
private void Test()
{
   // Begin to asynchronously connect to an echo port.
   tcp1.BeginConnect("atropos", 7);
}

private void tcp1_EndConnect(object sender, ExceptionEventArgs e)
{
   // Connect complete, check for any exceptions
   if(e.Exception == null)
   {
      // Now send some data.
      tcp1.Send("hello");

      // Receive the data back.
      Segment seg = tcp1.Receive();

      Debug.WriteLine(seg.ToString());
   }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.BeginConnect Overload List


BeginReceive Method

Tcp.BeginReceive Method

Receive data into your buffer asynchronously. The EndReceive event is raised when completed.

Overload List

Receive data into your buffer asynchronously. The EndReceive event is raised when completed.

[Visual Basic] Public Function BeginReceive(ByVal Byte()) As IAsyncResult
[C#] public IAsyncResult BeginReceive(byte[]);
[C++] public: IAsyncResult* BeginReceive(char __gc[]);
[JScript] public function BeginReceive(Byte[]): IAsyncResult;

Receive data into your buffer asynchronously specifying a buffer, offset, count and SocketFlags value. The EndReceive event is raised when completed.

[Visual Basic] Public Function BeginReceive(ByVal Byte(),ByVal Integer,ByVal Integer,ByVal SocketFlags,ByVal Object) As IAsyncResult
[C#] public IAsyncResult BeginReceive(byte[],int,int,SocketFlags,object);
[C++] public: IAsyncResult* BeginReceive(char __gc[],int,int,SocketFlags,Object*);
[JScript] public function BeginReceive(Byte[],int,int,SocketFlags,Object): IAsyncResult;

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


BeginReceive Method (Byte[])

Tcp.BeginReceive Method (Byte[])

Receive data into your buffer asynchronously. The EndReceive event is raised when completed.

[Visual Basic]
Public Function BeginReceive( _
   ByVal buffer As Byte() _
) As IAsyncResult
[C#]
public IAsyncResult BeginReceive(
   byte[] buffer
);
[C++]
public: IAsyncResult* BeginReceive(
   char buffer __gc[]
);
[JScript]
public function BeginReceive(
   Byte[] buffer
): IAsyncResult;

Parameters

buffer
Destination memory location to store received data.

Return Value

An IAsyncResult that represents the asynchronous operation, which could still be pending.

Remarks

The BeginReceive method is used to receive data into a buffer asynchronously. When data has been received, the EndReceive event is raised. A SegmentEventArgs object is passed into this event, containing a Segment object which encapsulates information about the data itself and the amount of bytes of data received.

The object state is useful for any kind of state information you would like accessible in the EndReceive event. Since the method is "disconnected" from the calling code and returns to the calling thread elsewhere, you may wish to pass an object/variable as state to be retrieved and used in the event handler.

If you are using the Tcp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the SegmentEventHandler delegate.

To synchronously receive data, use the Receive method.

Use this method if you wish to receive data into a buffer transparently with minimal application impact, as execution occurs on another thread. This method is the standard means for asynchronously receiving data. All available data is received.

Exceptions

Exception Type | Condition
InvalidOperationException | BeginXXX method used without providing an EndXXX event handler.
IOException | The stream is not Readable.
ArgumentNullException | buffer is null.
ArgumentOutOfRangeException | offset or count is less than 0.
ArgumentException | offset + count is greater than the length of buffer.
SocketException | The socket is not connected.

Example

The following example demonstrates asynchronous receiving and sending of data.

[Visual Basic]
Private Sub AsynchTcpDemo()

   ' Attempt to connect to an echo port.
   Try
      Tcp1.Connect("myserver", 7)
   Catch ex As Exception
      Return
   End Try

   ' Send data, since we are connected to an echo port, the same data should be returned.
   ' The following code demonstrates asynchronously sending data. When data has been sent
   ' the EndSend event will be raised.

   Dim buffer() As Byte = System.Text.Encoding.Default.GetBytes("a")
   Tcp1.BeginSend(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)
End Sub

Private Sub Tcp1_EndSend(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndSend
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Send is complete. Display info about the data sent.
      Debug.WriteLine("Byte count sent: " + e.Segment.Count)
      Debug.WriteLine("Data sent: " + e.Segment.ToString())

      Dim buffer(Tcp1.ReceiveBufferSize) As Byte

      ' Receive the data. The EndReceive event will be raised upon completion.
      Tcp1.BeginReceive(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)

    End If
End Sub

Private Sub Tcp1_EndReceive(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndReceive
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Receive is complete. Display info about the data sent.
      Debug.WriteLine("Byte count received: " + e.Segment.Count)
      Debug.WriteLine("Data received: " + e.Segment.ToString())

      ' Close the connection
      Tcp1.Close()
    End If
End Sub

[C#]
private void AsynchTcpDemo()
{
    // Attempt to connect to an echo port.
    try
    {
        tcp1.Connect("myserver", 7);
    }
    catch(Exception ex)
    {return;}

    // Send data, since we are connected to an echo port, the same data should be returned.
    // The following code demonstrates asynchronously sending data. When data has been sent
    // the EndSend event will be raised.

    byte[] buffer = System.Text.Encoding.Default.GetBytes("a");
    tcp1.BeginSend(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
}

private void tcp1_EndSend(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Send is complete. Display info about the data sent.
        Debug.WriteLine("Byte count sent: " + e.Segment.Count);
        Debug.WriteLine("Data sent: " + e.Segment.ToString());

        byte[] buffer = new byte[tcp1.ReceiveBufferSize];

        // Receive the data. The EndReceive event will be raised upon completion.
        tcp1.BeginReceive(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
    }
}

private void tcp1_EndReceive(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Receive is complete. Display info about the data sent.
        Debug.WriteLine("Byte count received: " + e.Segment.Count);
        Debug.WriteLine("Data received: " + e.Segment.ToString());

        // Close the connection
        tcp1.Close();
    }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.BeginReceive Overload List


BeginReceive Method (Byte[], Int32, Int32, SocketFlags, Object)

Tcp.BeginReceive Method (Byte[], Int32, Int32, SocketFlags, Object)

Receive data into your buffer asynchronously specifying a buffer, offset, count and SocketFlags value. The EndReceive event is raised when completed.

[Visual Basic]
Public Function BeginReceive( _
   ByVal buffer As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer, _
   ByVal socketFlags As SocketFlags, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginReceive(
   byte[] buffer,
   int offset,
   int count,
   SocketFlags socketFlags,
   object state
);
[C++]
public: IAsyncResult* BeginReceive(
   char buffer __gc[],
   int offset,
   int count,
   SocketFlags socketFlags,
   Object* state
);
[JScript]
public function BeginReceive(
   Byte[] buffer,
   int offset,
   int count,
   SocketFlags socketFlags,
   Object state
): IAsyncResult;

Parameters

buffer
Destination memory location to store received data.
offset
Starting offset within buffer for filling.
count
Maximum number of bytes to receive.
socketFlags
A bitwise combination of special use receiving parameters.
state
User state information.

Return Value

An IAsyncResult that represents the asynchronous operation, which could still be pending.

Remarks

The BeginReceive method is used to receive data into a buffer asynchronously. When data has been received, the EndReceive event is raised. A SegmentEventArgs object is passed into this event, containing a Segment object which encapsulates information about the data itself and the amount of bytes of data received.

The object state is useful for any kind of state information you would like accessible in the EndReceive event. Since the method is "disconnected" from the calling code and returns to the calling thread elsewhere, you may wish to pass an object/variable as state to be retrieved and used in the event handler.

If you are using the Tcp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the SegmentEventHandler delegate.

To synchronously receive data, use the Receive method.

Use this method if you wish to receive data into your buffer transparently with minimal application impact, as execution occurs on another thread. This method allows for greater configuration over how the data is received. For example, you could specify SocketFlags.Peek to peek at an incoming message. Also, if you would like to perform an asynchronous receive and make user defined objects available in the EndReceive event (via the state object), you must use this method.

Exceptions

Exception Type | Condition
InvalidOperationException | BeginXXX method used without providing an EndXXX event handler.
IOException | The stream is not Readable.
ArgumentNullException | buffer is null.
ArgumentOutOfRangeException | offset or count is less than 0.
ArgumentException | offset + count is greater than the length of buffer.
SocketException | The socket is not connected.

Example

The following example demonstrates asynchronous receiving and sending of data.

[Visual Basic]
Private Sub AsynchTcpDemo()

   ' Attempt to connect to an echo port.
   Try
      Tcp1.Connect("myserver", 7)
   Catch ex As Exception
      Return
   End Try

   ' Send data, since we are connected to an echo port, the same data should be returned.
   ' The following code demonstrates asynchronously sending data. When data has been sent
   ' the EndSend event will be raised.

   Dim buffer() As Byte = System.Text.Encoding.Default.GetBytes("a")
   Tcp1.BeginSend(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)
End Sub

Private Sub Tcp1_EndSend(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndSend
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Send is complete. Display info about the data sent.
      Debug.WriteLine("Byte count sent: " + e.Segment.Count)
      Debug.WriteLine("Data sent: " + e.Segment.ToString())

      Dim buffer(Tcp1.ReceiveBufferSize) As Byte

      ' Receive the data. The EndReceive event will be raised upon completion.
      Tcp1.BeginReceive(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)

    End If
End Sub

Private Sub Tcp1_EndReceive(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndReceive
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Receive is complete. Display info about the data sent.
      Debug.WriteLine("Byte count received: " + e.Segment.Count)
      Debug.WriteLine("Data received: " + e.Segment.ToString())

      ' Close the connection
      Tcp1.Close()
    End If
End Sub

[C#]
private void AsynchTcpDemo()
{
    // Attempt to connect to an echo port.
    try
    {
        tcp1.Connect("myserver", 7);
    }
    catch(Exception ex)
    {return;}

    // Send data, since we are connected to an echo port, the same data should be returned.
    // The following code demonstrates asynchronously sending data. When data has been sent
    // the EndSend event will be raised.

    byte[] buffer = System.Text.Encoding.Default.GetBytes("a");
    tcp1.BeginSend(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
}

private void tcp1_EndSend(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Send is complete. Display info about the data sent.
        Debug.WriteLine("Byte count sent: " + e.Segment.Count);
        Debug.WriteLine("Data sent: " + e.Segment.ToString());

        byte[] buffer = new byte[tcp1.ReceiveBufferSize];

        // Receive the data. The EndReceive event will be raised upon completion.
        tcp1.BeginReceive(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
    }
}

private void tcp1_EndReceive(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Receive is complete. Display info about the data sent.
        Debug.WriteLine("Byte count received: " + e.Segment.Count);
        Debug.WriteLine("Data received: " + e.Segment.ToString());

        // Close the connection
        tcp1.Close();
    }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.BeginReceive Overload List


BeginSend Method

Tcp.BeginSend Method

Send data from your buffer asynchronously. The EndSend event is raised when completed.

Overload List

Send data from your buffer asynchronously. The EndSend event is raised when completed.

[Visual Basic] Public Function BeginSend(ByVal Byte()) As IAsyncResult
[C#] public IAsyncResult BeginSend(byte[]);
[C++] public: IAsyncResult* BeginSend(char __gc[]);
[JScript] public function BeginSend(Byte[]): IAsyncResult;

Send data from your buffer asynchronously, specifying a buffer, offset, count and SocketFlags value. The EndSend event is raised when completed.

[Visual Basic] Public Function BeginSend(ByVal Byte(),ByVal Integer,ByVal Integer,ByVal SocketFlags,ByVal Object) As IAsyncResult
[C#] public IAsyncResult BeginSend(byte[],int,int,SocketFlags,object);
[C++] public: IAsyncResult* BeginSend(char __gc[],int,int,SocketFlags,Object*);
[JScript] public function BeginSend(Byte[],int,int,SocketFlags,Object): IAsyncResult;

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


BeginSend Method (Byte[])

Tcp.BeginSend Method (Byte[])

Send data from your buffer asynchronously. The EndSend event is raised when completed.

[Visual Basic]
Public Function BeginSend( _
   ByVal buffer As Byte() _
) As IAsyncResult
[C#]
public IAsyncResult BeginSend(
   byte[] buffer
);
[C++]
public: IAsyncResult* BeginSend(
   char buffer __gc[]
);
[JScript]
public function BeginSend(
   Byte[] buffer
): IAsyncResult;

Parameters

buffer
Source memory location for the data to send.

Return Value

An IAsyncResult that represents the asynchronous operation, which could still be pending.

Remarks

The BeginSend method is used to send data from a buffer asynchronously. When the data has been sent, the EndSend event is raised. A SegmentEventArgs object is passed into this event, containing a Segment object, containing information about the data sent, including the data itself and the amount of bytes of data sent.

If you are using the Tcp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the SegmentEventHandler delegate.

To synchronously send data, use the Send method.

Use this method if you wish to receive data into a buffer transparently with minimal application impact, as execution occurs on another thread. This method is the standard means for asynchronously sending data.

Exceptions

Exception Type | Condition
InvalidOperationException | BeginXXX method used without providing an EndXXX event handler.
ArgumentOutOfRangeException | offset or count is less than 0.
ArgumentException | offset + count is greater than the length of buffer.
SocketException | The socket is not connected.

Example

The following example demonstrates asynchronous receiving and sending of data.

[Visual Basic]
Private Sub AsynchTcpDemo()

   ' Attempt to connect to an echo port.
   Try
      Tcp1.Connect("myserver", 7)
   Catch ex As Exception
      Return
   End Try

   ' Send data, since we are connected to an echo port, the same data should be returned.
   ' The following code demonstrates asynchronously sending data. When data has been sent
   ' the EndSend event will be raised.

   Dim buffer() As Byte = System.Text.Encoding.Default.GetBytes("a")
   Tcp1.BeginSend(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)
End Sub

Private Sub Tcp1_EndSend(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndSend
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Send is complete. Display info about the data sent.
      Debug.WriteLine("Byte count sent: " + e.Segment.Count)
      Debug.WriteLine("Data sent: " + e.Segment.ToString())

      Dim buffer(Tcp1.ReceiveBufferSize) As Byte

      ' Receive the data. The EndReceive event will be raised upon completion.
      Tcp1.BeginReceive(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)

    End If
End Sub

Private Sub Tcp1_EndReceive(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndReceive
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Receive is complete. Display info about the data sent.
      Debug.WriteLine("Byte count received: " + e.Segment.Count)
      Debug.WriteLine("Data received: " + e.Segment.ToString())

      ' Close the connection
      Tcp1.Close()
    End If
End Sub

[C#]
private void AsynchTcpDemo()
{
    // Attempt to connect to an echo port.
    try
    {
        tcp1.Connect("myserver", 7);
    }
    catch(Exception ex)
    {return;}

    // Send data, since we are connected to an echo port, the same data should be returned.
    // The following code demonstrates asynchronously sending data. When data has been sent
    // the EndSend event will be raised.

    byte[] buffer = System.Text.Encoding.Default.GetBytes("a");
    tcp1.BeginSend(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
}

private void tcp1_EndSend(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Send is complete. Display info about the data sent.
        Debug.WriteLine("Byte count sent: " + e.Segment.Count);
        Debug.WriteLine("Data sent: " + e.Segment.ToString());

        byte[] buffer = new byte[tcp1.ReceiveBufferSize];

        // Receive the data. The EndReceive event will be raised upon completion.
        tcp1.BeginReceive(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
    }
}

private void tcp1_EndReceive(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Receive is complete. Display info about the data sent.
        Debug.WriteLine("Byte count received: " + e.Segment.Count);
        Debug.WriteLine("Data received: " + e.Segment.ToString());

        // Close the connection
        tcp1.Close();
    }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.BeginSend Overload List


BeginSend Method (Byte[], Int32, Int32, SocketFlags, Object)

Tcp.BeginSend Method (Byte[], Int32, Int32, SocketFlags, Object)

Send data from your buffer asynchronously, specifying a buffer, offset, count and SocketFlags value. The EndSend event is raised when completed.

[Visual Basic]
Public Function BeginSend( _
   ByVal buffer As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer, _
   ByVal socketFlags As SocketFlags, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginSend(
   byte[] buffer,
   int offset,
   int count,
   SocketFlags socketFlags,
   object state
);
[C++]
public: IAsyncResult* BeginSend(
   char buffer __gc[],
   int offset,
   int count,
   SocketFlags socketFlags,
   Object* state
);
[JScript]
public function BeginSend(
   Byte[] buffer,
   int offset,
   int count,
   SocketFlags socketFlags,
   Object state
): IAsyncResult;

Parameters

buffer
Source memory location for the data to send.
offset
Starting offset within buffer for sending.
count
Number of bytes to send.
socketFlags
Bitwise combination of special use sending parameters.
state
User state information.

Return Value

An IAsyncResult that represents the asynchronous operation, which could still be pending.

Remarks

The BeginSend method is used to send data from a buffer asynchronously. When the data has been sent, the EndSend event is raised. A SegmentEventArgs object is passed into this event, containing a Segment object, containing information about the data sent, including the data itself and the amount of bytes of data sent.

If you are using the Tcp component as a reference, you must "wire up" the event yourself. This involves creating a method as the event handler that implements the SegmentEventHandler delegate.

To synchronously send data, use the Send method.

Use this method if you wish to receive data into a buffer transparently with minimal application impact, as execution occurs on another thread. This method allows for greater configuration over how the data is sent. For example, you could specify SocketFlags.DontRoute to specify to send without using routing tables. Also, if you would like to perform an asynchronous send and make user defined data available in the EndSend event, you must use this method.

Exceptions

Exception Type | Condition
InvalidOperationException | BeginXXX method used without providing an EndXXX event handler.
ArgumentOutOfRangeException | offset or count is less than 0.
ArgumentException | offset + count is greater than the length of buffer.
SocketException | The socket is not connected.

Example

The following example demonstrates asynchronous receiving and sending of data.

[Visual Basic]
Private Sub AsynchTcpDemo()

   ' Attempt to connect to an echo port.
   Try
      Tcp1.Connect("myserver", 7)
   Catch ex As Exception
      Return
   End Try

   ' Send data, since we are connected to an echo port, the same data should be returned.
   ' The following code demonstrates asynchronously sending data. When data has been sent
   ' the EndSend event will be raised.

   Dim buffer() As Byte = System.Text.Encoding.Default.GetBytes("a")
   Tcp1.BeginSend(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)
End Sub

Private Sub Tcp1_EndSend(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndSend
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Send is complete. Display info about the data sent.
      Debug.WriteLine("Byte count sent: " + e.Segment.Count)
      Debug.WriteLine("Data sent: " + e.Segment.ToString())

      Dim buffer(Tcp1.ReceiveBufferSize) As Byte

      ' Receive the data. The EndReceive event will be raised upon completion.
      Tcp1.BeginReceive(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)

    End If
End Sub

Private Sub Tcp1_EndReceive(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndReceive
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Receive is complete. Display info about the data sent.
      Debug.WriteLine("Byte count received: " + e.Segment.Count)
      Debug.WriteLine("Data received: " + e.Segment.ToString())

      ' Close the connection
      Tcp1.Close()
    End If
End Sub

[C#]
private void AsynchTcpDemo()
{
    // Attempt to connect to an echo port.
    try
    {
        tcp1.Connect("myserver", 7);
    }
    catch(Exception ex)
    {return;}

    // Send data, since we are connected to an echo port, the same data should be returned.
    // The following code demonstrates asynchronously sending data. When data has been sent
    // the EndSend event will be raised.

    byte[] buffer = System.Text.Encoding.Default.GetBytes("a");
    tcp1.BeginSend(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
}

private void tcp1_EndSend(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Send is complete. Display info about the data sent.
        Debug.WriteLine("Byte count sent: " + e.Segment.Count);
        Debug.WriteLine("Data sent: " + e.Segment.ToString());

        byte[] buffer = new byte[tcp1.ReceiveBufferSize];

        // Receive the data. The EndReceive event will be raised upon completion.
        tcp1.BeginReceive(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
    }
}

private void tcp1_EndReceive(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Receive is complete. Display info about the data sent.
        Debug.WriteLine("Byte count received: " + e.Segment.Count);
        Debug.WriteLine("Data received: " + e.Segment.ToString());

        // Close the connection
        tcp1.Close();
    }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.BeginSend Overload List


Close Method

Tcp.Close Method

Close the connection.

Overload List

Close the connection.

[Visual Basic] Public Sub Close()
[C#] public void Close();
[C++] public: void Close();
[JScript] public function Close();

Close the connection.

[Visual Basic] Public Sub Close(ByVal LingerOption)
[C#] public void Close(LingerOption);
[C++] public: void Close(LingerOption*);
[JScript] public function Close(LingerOption);

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Close Method ()

Tcp.Close Method ()

Close the connection.

[Visual Basic]
Public Sub Close()
[C#]
public void Close();
[C++]
public: void Close();
[JScript]
public function Close();

Remarks

This method is the recommended way to explicitly close a connection. The Connected property is set to false when the connection is closed.

Example

The following example demonstrates connecting to an echo port, sending data, receiving data, then closing the connection.

[Visual Basic]
Private Sub TcpDemo()

   ' Connect to echo port.
   Tcp1.Connect("atropos", "7")

   ' Send some data
   Dim seg As Segment = Tcp1.Send("Hello")

   ' Display info
   Debug.WriteLine("Bytes of data sent: " & seg.Count)
   Debug.WriteLine("Data sent: " & seg.ToString())

   ' Receive response (this should be the same as the sent data)
   seg = Tcp1.Receive()

   ' Display info
   Debug.WriteLine("Bytes of data received: " & seg.Count)
   Debug.WriteLine("Data received: " & seg.ToString())

   ' Since connection is to an echo port, the client has to
   ' close the connection.
   Try
      Tcp1.Close()
   Catch ex As Exception
      ' Error, just dispose the object.
      Tcp1.Dispose()
   End Try

   '* Output
   '* --------------------------
   '* Bytes of data sent: 5
   '* Data sent: Hello
   '* Bytes of data received: 5
   '* Data received: Hello
   '*
End Sub

[C#]
private void TcpDemo()
{
   // Connect to echo port.
   tcp1.Connect("atropos", "7");

   // Send some data
   Segment seg = tcp1.Send("Hello");

   // Display info
   Debug.WriteLine("Bytes of data sent: " + seg.Count);
   Debug.WriteLine("Data sent: " + seg.ToString());

   // Receive response (this should be the same as the sent data)
   seg = tcp1.Receive();

   // Display info
   Debug.WriteLine("Bytes of data received: " + seg.Count);
   Debug.WriteLine("Data received: " + seg.ToString());

   // Since connection is to an echo port, the client has to
   // close the connection.
   try
   {
      tcp1.Close();
   }
   catch(Exception ex)
   {
      // Error, just dispose the object.
      tcp1.Dispose();
   }

   /* Output
    * --------------------------
    * Bytes of data sent: 5
    * Data sent: Hello
    * Bytes of data received: 5
    * Data received: Hello
    */
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.Close Overload List


Close Method (LingerOption)

Tcp.Close Method (LingerOption)

Close the connection.

[Visual Basic]
Public Sub Close( _
   ByVal linger As LingerOption _
)
[C#]
public void Close(
   LingerOption linger
);
[C++]
public: void Close(
   LingerOption* linger
);
[JScript]
public function Close(
   LingerOption linger
);

Parameters

linger
If null is used, a graceful disconnect will occur without blocking execution of your application.

Remarks

This method is the recommended way to explicitly close a connection. The Connected property is set to false when the connection is closed.

The LingerOption parameter controls the amount of time to remain connected after the socket is closed.

Example

The following example demonstrates connecting to an echo port, sending data, receiving data, then closing the connection.

[Visual Basic]
Private Sub TcpDemo()

   ' Connect to echo port.
   Tcp1.Connect("atropos", "7")

   ' Send some data
   Dim seg As Segment = Tcp1.Send("Hello")

   ' Display info
   Debug.WriteLine("Bytes of data sent: " & seg.Count)
   Debug.WriteLine("Data sent: " & seg.ToString())

   ' Receive response (this should be the same as the sent data)
   seg = Tcp1.Receive()

   ' Display info
   Debug.WriteLine("Bytes of data received: " & seg.Count)
   Debug.WriteLine("Data received: " & seg.ToString())

   ' Since connection is to an echo port, the client has to
   ' close the connection.
   Try
      Tcp1.Close()
   Catch ex As Exception
      ' Error, just dispose the object.
      Tcp1.Dispose()
   End Try

   '* Output
   '* --------------------------
   '* Bytes of data sent: 5
   '* Data sent: Hello
   '* Bytes of data received: 5
   '* Data received: Hello
   '*
End Sub

[C#]
private void TcpDemo()
{
   // Connect to echo port.
   tcp1.Connect("atropos", "7");

   // Send some data
   Segment seg = tcp1.Send("Hello");

   // Display info
   Debug.WriteLine("Bytes of data sent: " + seg.Count);
   Debug.WriteLine("Data sent: " + seg.ToString());

   // Receive response (this should be the same as the sent data)
   seg = tcp1.Receive();

   // Display info
   Debug.WriteLine("Bytes of data received: " + seg.Count);
   Debug.WriteLine("Data received: " + seg.ToString());

   // Since connection is to an echo port, the client has to
   // close the connection.
   try
   {
      tcp1.Close();
   }
   catch(Exception ex)
   {
      // Error, just dispose the object.
      tcp1.Dispose();
   }

   /* Output
    * --------------------------
    * Bytes of data sent: 5
    * Data sent: Hello
    * Bytes of data received: 5
    * Data received: Hello
    */
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.Close Overload List


Connect Method

Tcp.Connect Method

Connect to a host.

Overload List

Connect to a host.

[Visual Basic] Public Sub Connect(ByVal String,ByVal Integer)
[C#] public void Connect(string,int);
[C++] public: void Connect(String*,int);
[JScript] public function Connect(String,int);

Connect to a host, specifying the local interface to use.

[Visual Basic] Public Sub Connect(ByVal String,ByVal Integer,ByVal String,ByVal Integer)
[C#] public void Connect(string,int,string,int);
[C++] public: void Connect(String*,int,String*,int);
[JScript] public function Connect(String,int,String,int);

Connect to a host, specifying the local interface and a range of local ports to use.

[Visual Basic] Overridable OverloadsPublic Sub Connect(ByVal String,ByVal Integer,ByVal String,ByVal Integer,ByVal Integer)
[C#] public virtual void Connect(string,int,string,int,int);
[C++] public: virtual void Connect(String*,int,String*,int,int);
[JScript] public virtual function Connect(String,int,String,int,int);

Connect to a host.

[Visual Basic] Public Sub Connect(ByVal String,ByVal String)
[C#] public void Connect(string,string);
[C++] public: void Connect(String*,String*);
[JScript] public function Connect(String,String);

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Connect Method (String, Int32)

Tcp.Connect Method (String, Int32)

Connect to a host.

[Visual Basic]
Public Sub Connect( _
   ByVal server As String, _
   ByVal serverPort As Integer _
)
[C#]
public void Connect(
   string server,
   int serverPort
);
[C++]
public: void Connect(
   String* server,
   int serverPort
);
[JScript]
public function Connect(
   String server,
   int serverPort
);

Parameters

server
Remote hostname or address in dot notation.
serverPort
Remote port, a number between 1 and 65535, inclusive.

Remarks

The Connect method establishes a network connection between the default local network interface/port and the device identified by remote network address/port. If no exception is thrown, the connection has succeeded and the Connected property will return true after this method returns. Once the connection has been made, you can send/receive data to/from the server.

This method always blocks until the attempted connection succeeds or fails.

Example

The following example demonstrates connecting implementing the SMTP protocol using the Tcp component to send a simple message.

[Visual Basic]
Private Sub TcpDemo()

   ' The following code assumes that good responses are always received from
   ' the server. More robust code should check each response and handle appropriately.

   ' Connect to SMTP port
   Tcp1.Connect("mail", 25)

   ' Send the EHLO command
   Tcp1.Send("EHLO myserver" + vbCrLf)

   ' Get response from the server
   Dim seg As Segment = Tcp1.Receive()

   ' Send MAIL FROM command
   Tcp1.Send("MAIL FROM: test@myserver.com" + vbCrLf)

   ' Get response from the server
   seg = Tcp1.Receive()

   ' Send RCPT TO command
   Tcp1.Send("RCPT TO: you@yourserver.com" + vbCrLf)

   ' Get response from the server
   seg = Tcp1.Receive()

   ' Send DATA command
   Tcp1.Send("DATA" + vbCrLf)

   ' Get response from the server
   seg = Tcp1.Receive()

   ' Send DATA
   Tcp1.Send("Test Message" + vbCrLf + "." + vbCrLf)

   ' Receive response from the server
   seg = Tcp1.Receive()

   ' Write output
   Debug.WriteLine("Operation complete. The following information")
   Debug.WriteLine("was reported by the server:")
   Debug.WriteLine(seg.ToString())
End Sub

[C#]
private void TcpDemo()
{

   // The following code assumes that good responses are always received from
   // the server. More robust code should check each response and handle appropriately.

   // Connect to SMTP port
   tcp1.Connect("mail", 25);

   // Send the EHLO command
   tcp1.Send("EHLO myserver\r\n");

   // Get response from the server
   Segment seg = tcp1.Receive();

   // Send MAIL FROM command
   tcp1.Send("MAIL FROM: test@myserver.com\r\n");

   // Get response from the server
   seg = tcp1.Receive();

   // Send RCPT TO command
   tcp1.Send("RCPT TO: you@yourserver.com\r\n");

   // Get response from the server
   seg = tcp1.Receive();

   // Send DATA command
   tcp1.Send("DATA\r\n");

   // Get response from the server
   seg = tcp1.Receive();

   // Send DATA
   tcp1.Send("Test Message\r\n.\r\n");

   // Receive response from the server
   seg = tcp1.Receive();

   // Write output
   Debug.WriteLine("Operation complete. The following information");
   Debug.WriteLine("was reported by the server about the operation:");
   Debug.WriteLine(seg.ToString());
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.Connect Overload List


Connect Method (String, Int32, String, Int32)

Tcp.Connect Method (String, Int32, String, Int32)

Connect to a host, specifying the local interface to use.

[Visual Basic]
Public Sub Connect( _
   ByVal server As String, _
   ByVal serverPort As Integer, _
   ByVal client As String, _
   ByVal clientPort As Integer _
)
[C#]
public void Connect(
   string server,
   int serverPort,
   string client,
   int clientPort
);
[C++]
public: void Connect(
   String* server,
   int serverPort,
   String* client,
   int clientPort
);
[JScript]
public function Connect(
   String server,
   int serverPort,
   String client,
   int clientPort
);

Parameters

server
Remote hostname or address in dot notation.
serverPort
Remote port, a number between 1 and 65535, inclusive.
client
Optional local hostname or address in dot notation. Use "" as default.
clientPort
Optional local port, a number between 1 and 65535, inclusive. Use 0 as default.

Remarks

The Connect method establishes a network connection between the specified local network interface/port and the device identified by remote network address/port. If no exception is thrown, the connection has succeeded and the Connected property will return true after this method returns. Once the connection has been made, you can send/receive data to/from the server.

This method always blocks until the attempted connection succeeds or fails.

Example

The following example demonstrates connecting to a server while specifying a local interface to use.

[Visual Basic]
' Connect to the server, specifying the local interface to use
Tcp1.Connect("atropos", 13, "192.168.0.83", 8888)

' Since connection was to DAYTIME port (13), simply receive the time
Dim seg As Segment = Tcp1.Receive()

Debug.WriteLine("Time reported by server: " + seg.ToString())

[C#]
// Connect to the server, specifying the local interface to use
tcp1.Connect("atropos", 13, "192.168.0.83", 8888);

// Since connection was to DAYTIME port (13), simply receive the time
Segment seg = tcp1.Receive();

Debug.WriteLine("Time reported by server: " + seg.ToString());

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.Connect Overload List


Connect Method (String, Int32, String, Int32, Int32)

Tcp.Connect Method (String, Int32, String, Int32, Int32)

Connect to a host, specifying the local interface and a range of local ports to use.

[Visual Basic]
Overridable  OverloadsPublic Sub Connect( _
   ByVal server As String, _
   ByVal serverPort As Integer, _
   ByVal client As String, _
   ByVal clientPortMin As Integer, _
   ByVal clientPortMax As Integer _
)
[C#]
public virtual void Connect(
   string server,
   int serverPort,
   string client,
   int clientPortMin,
   int clientPortMax
);
[C++]
public: virtual void Connect(
   String* server,
   int serverPort,
   String* client,
   int clientPortMin,
   int clientPortMax
);
[JScript]
public virtual function Connect(
   String server,
   int serverPort,
   String client,
   int clientPortMin,
   int clientPortMax
);

Parameters

server
Remote hostname or address in dot notation.
serverPort
Remote port, a number between 1 and 65535, inclusive.
client
Optional local hostname or address in dot notation. Use "" as default.
clientPortMin
The minimum client port number to use as a local interface.
clientPortMax
The maximum client port number to use as a local interface.

Remarks

The Connect method establishes a network connection between the specified local network interface/port and the device identified by remote network address/port. If no exception is thrown, the connection has succeeded and the Connected property will return true after this method returns. Once the connection has been made, you can send/receive data to/from the server.

This method always blocks until the attempted connection succeeds or fails.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.Connect Overload List


Connect Method (String, String)

Tcp.Connect Method (String, String)

Connect to a host.

[Visual Basic]
Public Sub Connect( _
   ByVal server As String, _
   ByVal serverPort As String _
)
[C#]
public void Connect(
   string server,
   string serverPort
);
[C++]
public: void Connect(
   String* server,
   String* serverPort
);
[JScript]
public function Connect(
   String server,
   String serverPort
);

Parameters

server
Remote hostname or address in dot notation.
serverPort
A string value which can be cast to an Integer between 1 and 65535, inclusive.

Remarks

The Connect method establishes a network connection between the default local network interface/port and the device identified by remote network address/port. If no exception is thrown, the connection has succeeded and the Connected property will return true after this method returns. Once the connection has been made, you can send/receive data to/from the server.

This method always blocks until the attempted connection succeeds or fails.

Example

The following example demonstrates connecting to an echo port, sending data, receiving data, then closing the connection.

[Visual Basic]
Private Sub TcpDemo()

   ' Connect to echo port.
   Tcp1.Connect("atropos", "7")

   ' Send some data
   Dim seg As Segment = Tcp1.Send("Hello")

   ' Display info
   Debug.WriteLine("Bytes of data sent: " & seg.Count)
   Debug.WriteLine("Data sent: " & seg.ToString())

   ' Receive response (this should be the same as the sent data)
   seg = Tcp1.Receive()

   ' Display info
   Debug.WriteLine("Bytes of data received: " & seg.Count)
   Debug.WriteLine("Data received: " & seg.ToString())

   ' Since connection is to an echo port, the client has to
   ' close the connection.
   Try
      Tcp1.Close()
   Catch ex As Exception
      ' Error, just dispose the object.
      Tcp1.Dispose()
   End Try

   '* Output
   '* --------------------------
   '* Bytes of data sent: 5
   '* Data sent: Hello
   '* Bytes of data received: 5
   '* Data received: Hello
   '*
End Sub

[C#]
private void TcpDemo()
{
   // Connect to echo port.
   tcp1.Connect("atropos", "7");

   // Send some data
   Segment seg = tcp1.Send("Hello");

   // Display info
   Debug.WriteLine("Bytes of data sent: " + seg.Count);
   Debug.WriteLine("Data sent: " + seg.ToString());

   // Receive response (this should be the same as the sent data)
   seg = tcp1.Receive();

   // Display info
   Debug.WriteLine("Bytes of data received: " + seg.Count);
   Debug.WriteLine("Data received: " + seg.ToString());

   // Since connection is to an echo port, the client has to
   // close the connection.
   try
   {
      tcp1.Close();
   }
   catch(Exception ex)
   {
      // Error, just dispose the object.
      tcp1.Dispose();
   }

   /* Output
    * --------------------------
    * Bytes of data sent: 5
    * Data sent: Hello
    * Bytes of data received: 5
    * Data received: Hello
    */
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.Connect Overload List


Receive Method

Tcp.Receive Method

Receive data from the host.

Overload List

Receive data from the host.

[Visual Basic] Public Function Receive() As Segment
[C#] public Segment Receive();
[C++] public: Segment* Receive();
[JScript] public function Receive(): Segment;

Receive data from the host.

[Visual Basic] Public Function Receive(ByVal Byte()) As Segment
[C#] public Segment Receive(byte[]);
[C++] public: Segment* Receive(char __gc[]);
[JScript] public function Receive(Byte[]): Segment;

Receive data from the host, specifying a buffer, offset, count and SocketFlags value.

[Visual Basic] Public Function Receive(ByVal Byte(),ByVal Integer,ByVal Integer,ByVal SocketFlags) As Segment
[C#] public Segment Receive(byte[],int,int,SocketFlags);
[C++] public: Segment* Receive(char __gc[],int,int,SocketFlags);
[JScript] public function Receive(Byte[],int,int,SocketFlags): Segment;

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Receive Method ()

Tcp.Receive Method ()

Receive data from the host.

[Visual Basic]
Public Function Receive() As Segment
[C#]
public Segment Receive();
[C++]
public: Segment* Receive();
[JScript]
public function Receive(): Segment;

Return Value

A Segment object encapsulating the data received.

Remarks

After connecting, data can be received using the Tcp.Recieve method. All Receive methods return a Segment object, encapsulating the data received. In order to access the data, simply access the properties of the Segment object returned such as Buffer (to access the data in a byte array) or ToString (to access the data as a string).

If the amount of data received from the server exceeds ReceiveBufferSize, the Receive method will have to be called multiple times until the socket closes.

This method is functionally equivalent to Tcp.Stream.Write().

Exceptions

Exception Type | Condition
IOException | The stream is not Readable.
ArgumentNullException | buffer is null.
ArgumentOutOfRangeException | offset or count is less than 0.
ArgumentException | offset + count is greater than the length of buffer.
SocketException | The socket is not connected.

Example

The following example demonstrates connecting implementing the SMTP protocol using the Tcp component to send a simple message.

[Visual Basic]
Private Sub TcpDemo()

   ' The following code assumes that good responses are always received from
   ' the server. More robust code should check each response and handle appropriately.

   ' Connect to SMTP port
   Tcp1.Connect("mail", 25)

   ' Send the EHLO command
   Tcp1.Send("EHLO myserver" + vbCrLf)

   ' Get response from the server
   Dim seg As Segment = Tcp1.Receive()

   ' Send MAIL FROM command
   Tcp1.Send("MAIL FROM: test@myserver.com" + vbCrLf)

   ' Get response from the server
   seg = Tcp1.Receive()

   ' Send RCPT TO command
   Tcp1.Send("RCPT TO: you@yourserver.com" + vbCrLf)

   ' Get response from the server
   seg = Tcp1.Receive()

   ' Send DATA command
   Tcp1.Send("DATA" + vbCrLf)

   ' Get response from the server
   seg = Tcp1.Receive()

   ' Send DATA
   Tcp1.Send("Test Message" + vbCrLf + "." + vbCrLf)

   ' Receive response from the server
   seg = Tcp1.Receive()

   ' Write output
   Debug.WriteLine("Operation complete. The following information")
   Debug.WriteLine("was reported by the server:")
   Debug.WriteLine(seg.ToString())
End Sub

[C#]
private void TcpDemo()
{

   // The following code assumes that good responses are always received from
   // the server. More robust code should check each response and handle appropriately.

   // Connect to SMTP port
   tcp1.Connect("mail", 25);

   // Send the EHLO command
   tcp1.Send("EHLO myserver\r\n");

   // Get response from the server
   Segment seg = tcp1.Receive();

   // Send MAIL FROM command
   tcp1.Send("MAIL FROM: test@myserver.com\r\n");

   // Get response from the server
   seg = tcp1.Receive();

   // Send RCPT TO command
   tcp1.Send("RCPT TO: you@yourserver.com\r\n");

   // Get response from the server
   seg = tcp1.Receive();

   // Send DATA command
   tcp1.Send("DATA\r\n");

   // Get response from the server
   seg = tcp1.Receive();

   // Send DATA
   tcp1.Send("Test Message\r\n.\r\n");

   // Receive response from the server
   seg = tcp1.Receive();

   // Write output
   Debug.WriteLine("Operation complete. The following information");
   Debug.WriteLine("was reported by the server about the operation:");
   Debug.WriteLine(seg.ToString());
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.Receive Overload List


Receive Method (Byte[])

Tcp.Receive Method (Byte[])

Receive data from the host.

[Visual Basic]
Public Function Receive( _
   ByVal buffer As Byte() _
) As Segment
[C#]
public Segment Receive(
   byte[] buffer
);
[C++]
public: Segment* Receive(
   char buffer __gc[]
);
[JScript]
public function Receive(
   Byte[] buffer
): Segment;

Parameters

buffer
Destination memory location to store received data.

Return Value

A Segment object encapsulating the data received.

Remarks

After connecting, data can be received using the Tcp.Recieve method. All Receive methods return a Segment object, encapsulating the data received. In order to access the data, simply access the properties of the Segment object returned such as Buffer (to access the data in a byte array) or ToString (to access the data as a string).

If the amount of data received from the server exceeds ReceiveBufferSize, the Receive method will have to be called multiple times until the socket closes.

This method is functionally equivalent to Tcp.Stream.Write(byte[]).

Exceptions

Exception Type | Condition
IOException | The stream is not Readable.
ArgumentNullException | buffer is null.
ArgumentOutOfRangeException | offset or count is less than 0.
ArgumentException | offset + count is greater than the length of buffer.
SocketException | The socket is not connected.

Example

The following example demonstrates sending bytes to the server.

[Visual Basic]
Private Sub Test()
   ' Connect to an echo port
   Tcp1.Connect("atropos", 7)

   Dim sendbuffer() As Byte = System.Text.Encoding.Default.GetBytes("abcdefg")

   ' Send some bytes.
   Tcp1.Send(sendbuffer)

   Dim recvbuffer(sendbuffer.Length) As Byte

   ' Server will echo the bytes back. Receive the bytes.
   Tcp1.Receive(recvbuffer)

   ' Close the connection.
   Tcp1.Close()
End Sub

[C#]
private void Test()
{
   // Connect to the echo port
   tcp1.Connect("atropos", 7);

   byte[] sendbuffer = System.Text.Encoding.Default.GetBytes("abcdefg");

   // Send some bytes.
   tcp1.Send(sendbuffer);

   byte[] recvbuffer = new byte[sendbuffer.Length];

   // Server will echo the bytes back. Receive the bytes.
   tcp1.Receive(recvbuffer);

   // Close the connection.
   tcp1.Close();
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.Receive Overload List


Receive Method (Byte[], Int32, Int32, SocketFlags)

Tcp.Receive Method (Byte[], Int32, Int32, SocketFlags)

Receive data from the host, specifying a buffer, offset, count and SocketFlags value.

[Visual Basic]
Public Function Receive( _
   ByVal buffer As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer, _
   ByVal socketFlags As SocketFlags _
) As Segment
[C#]
public Segment Receive(
   byte[] buffer,
   int offset,
   int count,
   SocketFlags socketFlags
);
[C++]
public: Segment* Receive(
   char buffer __gc[],
   int offset,
   int count,
   SocketFlags socketFlags
);
[JScript]
public function Receive(
   Byte[] buffer,
   int offset,
   int count,
   SocketFlags socketFlags
): Segment;

Parameters

buffer
Destination memory location to store received data.
offset
Starting offset within buffer for filling.
count
Maximum number of bytes to receive.
socketFlags
A bitwise combination of special use receiving parameters.

Return Value

A Segment object encapsulating the data received.

Remarks

After connecting, data can be received using the Tcp.Recieve method. All Receive methods return a Segment object, encapsulating the data received. In order to access the data, simply access the properties of the Segment object returned such as Buffer (to access the data in a byte array) or ToString (to access the data as a string).

This method is the only way to receive data from a host while specifying a SocketFlags parameter.

Exceptions

Exception Type | Condition
IOException | The stream is not Readable.
ArgumentNullException | buffer is null.
ArgumentOutOfRangeException | offset or count is less than 0.
ArgumentException | offset + count is greater than the length of buffer.
SocketException | The socket is not connected.

Example

The following example demonstrates sending bytes to the server with a SocketFlag option.

[Visual Basic]
Private Sub Test()
   ' Connect to an echo port
   Tcp1.Connect("atropos", 7)

   Dim sendbuffer() As Byte = System.Text.Encoding.Default.GetBytes("abcdefg")

   ' Send some bytes with "OutOfBand" SocketFlag option
   Tcp1.Send(sendbuffer, 0, sendbuffer.Length, SocketFlags.OutOfBand)

   Dim recvbuffer(sendbuffer.Length) As Byte

   ' Server will echo the bytes back. Receive the bytes.
   Tcp1.Receive(recvbuffer, 0, recvbuffer.Length, SocketFlags.None)

   ' Close the connection.
   Tcp1.Close()
End Sub

[C#]
private void Test()
{
   // Connect to the echo port
   tcp1.Connect("atropos", 7);

   byte[] sendbuffer = System.Text.Encoding.Default.GetBytes("abcdefg");

   // Send some bytes with "OutOfBand" SocketFlag option
   tcp1.Send(sendbuffer, 0, sendbuffer.Length, SocketFlags.OutOfBand);

   byte[] recvbuffer = new byte[sendbuffer.Length];

   // Server will echo the bytes back. Receive the bytes.
   tcp1.Receive(recvbuffer, 0, recvbuffer.Length, SocketFlags.None);

   // Close the connection.
   tcp1.Close();
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.Receive Overload List


Send Method

Tcp.Send Method

Send data to the server.

Overload List

Send data to the server.

[Visual Basic] Public Function Send(ByVal Byte()) As Segment
[C#] public Segment Send(byte[]);
[C++] public: Segment* Send(char __gc[]);
[JScript] public function Send(Byte[]): Segment;

Send data to the server, specifying a buffer, offset, count and SocketFlags value.

[Visual Basic] Public Function Send(ByVal Byte(),ByVal Integer,ByVal Integer,ByVal SocketFlags) As Segment
[C#] public Segment Send(byte[],int,int,SocketFlags);
[C++] public: Segment* Send(char __gc[],int,int,SocketFlags);
[JScript] public function Send(Byte[],int,int,SocketFlags): Segment;

Send data to the server.

[Visual Basic] Public Function Send(ByVal String) As Segment
[C#] public Segment Send(string);
[C++] public: Segment* Send(String*);
[JScript] public function Send(String): Segment;

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Send Method (Byte[])

Tcp.Send Method (Byte[])

Send data to the server.

[Visual Basic]
Public Function Send( _
   ByVal buffer As Byte() _
) As Segment
[C#]
public Segment Send(
   byte[] buffer
);
[C++]
public: Segment* Send(
   char buffer __gc[]
);
[JScript]
public function Send(
   Byte[] buffer
): Segment;

Parameters

buffer
Source memory location for the data to send.

Return Value

A Segment object encapsulating information about the data sent.

Remarks

After connecting, data can be received using the Send method. All Send methods return a Segment object, encapsulating information about the data sent such as the data sent, and the amount of bytes of data sent.

This method is functionally equivalent to Tcp.Stream.Write(byte[]).

Exceptions

Exception Type | Condition
ArgumentOutOfRangeException | offset or count is less than 0.
ArgumentException | offset + count is greater than the length of buffer.
SocketException | The socket is not connected.

Example

The following example demonstrates sending bytes to the server.

[Visual Basic]
Private Sub Test()
   ' Connect to an echo port
   Tcp1.Connect("atropos", 7)

   Dim sendbuffer() As Byte = System.Text.Encoding.Default.GetBytes("abcdefg")

   ' Send some bytes.
   Tcp1.Send(sendbuffer)

   Dim recvbuffer(sendbuffer.Length) As Byte

   ' Server will echo the bytes back. Receive the bytes.
   Tcp1.Receive(recvbuffer)

   ' Close the connection.
   Tcp1.Close()
End Sub

[C#]
private void Test()
{
   // Connect to the echo port
   tcp1.Connect("atropos", 7);

   byte[] sendbuffer = System.Text.Encoding.Default.GetBytes("abcdefg");

   // Send some bytes.
   tcp1.Send(sendbuffer);

   byte[] recvbuffer = new byte[sendbuffer.Length];

   // Server will echo the bytes back. Receive the bytes.
   tcp1.Receive(recvbuffer);

   // Close the connection.
   tcp1.Close();
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.Send Overload List


Send Method (Byte[], Int32, Int32, SocketFlags)

Tcp.Send Method (Byte[], Int32, Int32, SocketFlags)

Send data to the server, specifying a buffer, offset, count and SocketFlags value.

[Visual Basic]
Public Function Send( _
   ByVal buffer As Byte(), _
   ByVal offset As Integer, _
   ByVal count As Integer, _
   ByVal socketFlags As SocketFlags _
) As Segment
[C#]
public Segment Send(
   byte[] buffer,
   int offset,
   int count,
   SocketFlags socketFlags
);
[C++]
public: Segment* Send(
   char buffer __gc[],
   int offset,
   int count,
   SocketFlags socketFlags
);
[JScript]
public function Send(
   Byte[] buffer,
   int offset,
   int count,
   SocketFlags socketFlags
): Segment;

Parameters

buffer
Source memory location for the data to send.
offset
Starting offset within buffer for sending.
count
Number of bytes to send.
socketFlags
A bitwise combination of special use sending parameters.

Return Value

A Segment object encapsulating information about the data sent.

Remarks

After connecting, data can be received using the Send method. All Send methods return a Segment object, encapsulating information about the data sent such as the data sent, and the amount of bytes of data sent.

This method is the only way to send data to a host while specifying a SocketFlags parameter.

Exceptions

Exception Type | Condition
ArgumentOutOfRangeException | offset or count is less than 0.
ArgumentException | offset + count is greater than the length of buffer.
SocketException | The socket is not connected.

Example

The following example demonstrates sending bytes to the server with a SocketFlag option.

[Visual Basic]
Private Sub Test()
   ' Connect to an echo port
   Tcp1.Connect("atropos", 7)

   Dim sendbuffer() As Byte = System.Text.Encoding.Default.GetBytes("abcdefg")

   ' Send some bytes with "OutOfBand" SocketFlag option
   Tcp1.Send(sendbuffer, 0, sendbuffer.Length, SocketFlags.OutOfBand)

   Dim recvbuffer(sendbuffer.Length) As Byte

   ' Server will echo the bytes back. Receive the bytes.
   Tcp1.Receive(recvbuffer, 0, recvbuffer.Length, SocketFlags.None)

   ' Close the connection.
   Tcp1.Close()
End Sub

[C#]
private void Test()
{
   // Connect to the echo port
   tcp1.Connect("atropos", 7);

   byte[] sendbuffer = System.Text.Encoding.Default.GetBytes("abcdefg");

   // Send some bytes with "OutOfBand" SocketFlag option
   tcp1.Send(sendbuffer, 0, sendbuffer.Length, SocketFlags.OutOfBand);

   byte[] recvbuffer = new byte[sendbuffer.Length];

   // Server will echo the bytes back. Receive the bytes.
   tcp1.Receive(recvbuffer, 0, recvbuffer.Length, SocketFlags.None);

   // Close the connection.
   tcp1.Close();
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.Send Overload List


Send Method (String)

Tcp.Send Method (String)

Send data to the server.

[Visual Basic]
Public Function Send( _
   ByVal buffer As String _
) As Segment
[C#]
public Segment Send(
   string buffer
);
[C++]
public: Segment* Send(
   String* buffer
);
[JScript]
public function Send(
   String buffer
): Segment;

Parameters

buffer
Data to be decoded into bytes and sent.

Return Value

A Segment object encapsulating information about the data sent.

Remarks

After connecting, data can be received using the Send method. All Send methods return a Segment object, encapsulating information about the data sent such as the data sent, and the amount of bytes of data sent.

This method is functionally equivalent to Tcp.Stream.Write.

Exceptions

Exception Type | Condition
ArgumentOutOfRangeException | offset or count is less than 0.
ArgumentException | offset + count is greater than the length of buffer.
SocketException | The socket is not connected.

Example

The following example demonstrates connecting implementing the SMTP protocol using the Tcp component to send a simple message.

[Visual Basic]
Private Sub TcpDemo()

   ' The following code assumes that good responses are always received from
   ' the server. More robust code should check each response and handle appropriately.

   ' Connect to SMTP port
   Tcp1.Connect("mail", 25)

   ' Send the EHLO command
   Tcp1.Send("EHLO myserver" + vbCrLf)

   ' Get response from the server
   Dim seg As Segment = Tcp1.Receive()

   ' Send MAIL FROM command
   Tcp1.Send("MAIL FROM: test@myserver.com" + vbCrLf)

   ' Get response from the server
   seg = Tcp1.Receive()

   ' Send RCPT TO command
   Tcp1.Send("RCPT TO: you@yourserver.com" + vbCrLf)

   ' Get response from the server
   seg = Tcp1.Receive()

   ' Send DATA command
   Tcp1.Send("DATA" + vbCrLf)

   ' Get response from the server
   seg = Tcp1.Receive()

   ' Send DATA
   Tcp1.Send("Test Message" + vbCrLf + "." + vbCrLf)

   ' Receive response from the server
   seg = Tcp1.Receive()

   ' Write output
   Debug.WriteLine("Operation complete. The following information")
   Debug.WriteLine("was reported by the server:")
   Debug.WriteLine(seg.ToString())
End Sub

[C#]
private void TcpDemo()
{

   // The following code assumes that good responses are always received from
   // the server. More robust code should check each response and handle appropriately.

   // Connect to SMTP port
   tcp1.Connect("mail", 25);

   // Send the EHLO command
   tcp1.Send("EHLO myserver\r\n");

   // Get response from the server
   Segment seg = tcp1.Receive();

   // Send MAIL FROM command
   tcp1.Send("MAIL FROM: test@myserver.com\r\n");

   // Get response from the server
   seg = tcp1.Receive();

   // Send RCPT TO command
   tcp1.Send("RCPT TO: you@yourserver.com\r\n");

   // Get response from the server
   seg = tcp1.Receive();

   // Send DATA command
   tcp1.Send("DATA\r\n");

   // Get response from the server
   seg = tcp1.Receive();

   // Send DATA
   tcp1.Send("Test Message\r\n.\r\n");

   // Receive response from the server
   seg = tcp1.Receive();

   // Write output
   Debug.WriteLine("Operation complete. The following information");
   Debug.WriteLine("was reported by the server about the operation:");
   Debug.WriteLine(seg.ToString());
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace | Tcp.Send Overload List


Tcp Events

The events of the Tcp class are listed below. For a complete list of Tcp class members, see the Tcp Members topic.

Public Instance Events

CertificateReceived | This event is raised when a certificate has been received to be authenticated.
CertificateRequested | This event is raised when a certificate has been requested.
ConnectedChanged | Obsolete. Raised when the value of the Object.Connected property changes.
ConnectedChangedEx | Raised when the value of the Object.Connected property changes. Supersedes the ConnectedChanged event.
Disposed (inherited from Component) | Adds an event handler to listen to the Disposed event on the component.
EndConnect | Raised when the BeginConnect request completes.
EndReceive | Raised when the BeginReceive request completes.
EndSend | Raised when the BeginSend request completes.
RawTrace | Raised when data has been sent/received.
Trace | Raised when data has been sent/received.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


CertificateReceived Event

Tcp.CertificateReceived Event

This event is raised when a certificate has been received to be authenticated.

[Visual Basic]
Public Event CertificateReceived As CertificateReceivedEventHandler
[C#]
public event CertificateReceivedEventHandler CertificateReceived;
[C++]
public: __event CertificateReceivedEventHandler* CertificateReceived;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type CertificateReceivedEventArgs containing data related to this event. The following CertificateReceivedEventArgs properties provide information specific to this event.

Property | Description
Accept | Controls whether or not the certificate is accepted.
Certificate | The certificate received for authentication.
TrustedRoot | Returns whether or not the certificate is from a Trusted Root Authority.
ValidDate | Returns whether or not the current time-date is within the certificate's life span.
ValidName | Returns whether or not the name is valid.

Remarks

The CertificateReceived event is raised when a certificate has been received from a secure server. A CertificateReceivedEventArgs object is passed into the event handler, containing information required to determine the validity of the certificate. If the certificate is determined to be invalid (if any of the properties ValidDate, ValidName, or TrustedRoot are false) the certificate is rejected. Accept is false to signify this. Set Accept to true to override this and accept the certificate.

Example

The following example demonstrates creating a simple secure client.

[Visual Basic]
    Private Sub SecureTest()

        'Allow component to negotiate best security option
        Tcp1.SecureProtocol = SecureProtocol.Auto

        ' Connect to a secure echo server.
        Tcp1.Connect("mysecureserver", 7)

        ' Send secure data
        Tcp1.Send("Test")

        ' Receive and display secure data
        System.Diagnostics.Debug.WriteLine(Tcp1.Receive().ToString())

        ' Close the connection
        Tcp1.Close()
    End Sub

    Private Sub Tcp1_CertificateRequested(ByVal sender As Object, ByVal e As System.EventArgs) Handles Tcp1.CertificateRequested
        'The server has requested client authentication
        'Allow the user to select a certificate
        Dim certform As New CertificateListForm(True, True)
        If (certform.ShowDialog(Me) = DialogResult.OK) Then
            Tcp1.Certificate = certform.SelectedCertificate
        End If
    End Sub

    Private Sub Tcp1_CertificateReceived(ByVal sender As Object, ByVal e As Dart.PowerTCP.SslSockets.CertificateReceivedEventArgs) Handles Tcp1.CertificateReceived
        'If the server's certificate is invalid for any reason,
        'the user can decide whether to proceed
        Dim msg As String = "The certificate was invalid for the following reason(s)" + vbLf

        ' Check to see if the certificate is from a trusted root.
        If (Not e.TrustedRoot) Then
            msg += "This certificate is not from a trusted root" + vbLf
        End If

        ' Check to see if the certificate has a valid date.
        If (Not e.ValidDate) Then
            msg += "This certificate does not have a valid date" + vbLf
        End If

        ' Check to see if the certificate has a valid name.
        If (Not e.ValidName) Then
            msg += "This certificate does not have a valid name" + vbLf
        End If

        If (Not e.Accept) Then
            msg += "Would you like to accept this certificate anyway?"
            If (MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
                e.Accept = True
            End If
        End If
    End Sub

[C#]
private void SecureTest()
{
    //Allow component to negotiate best security option
    tcp1.SecureProtocol = SecureProtocol.Auto;

    // Connect to a secure echo server.
    tcp1.Connect("mysecureserver", 7);

    // Send secure data
    tcp1.Send("Test");

    // Receive and display secure data
    System.Diagnostics.Debug.WriteLine(tcp1.Receive().ToString());

    // Close the connection
    tcp1.Close();
}

private void tcp1_CertificateRequested(object sender, System.EventArgs e)
{
    //The server has requested client authentication
    //Allow the user to select a certificate
    CertificateListForm certform = new CertificateListForm(true, true);
    if(certform.ShowDialog(this) == DialogResult.OK)
        tcp1.Certificate = certform.SelectedCertificate;
}

private void tcp1_CertificateReceived(object sender, CertificateReceivedEventArgs e)
{
    //If the server's certificate is invalid for any reason,
    //the user can decide whether to proceed
    string msg = "The certificate was invalid for the following reason(s)\n";

    // Check to see if the certificate is from a trusted root.
    if(!e.TrustedRoot)
        msg+= "This certificate is not from a trusted root\n";

    // Check to see if the certificate has a valid date.
    if(!e.ValidDate)
        msg+= "This certificate does not have a valid date\n";

    // Check to see if the certificate has a valid name.
    if(!e.ValidName)
        msg+= "This certificate does not have a valid name\n";

    if(!e.Accept)
    {
        msg += "Would you like to accept this certificate anyway?";
        if(MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) == DialogResult.Yes)
            e.Accept = true;
    }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


CertificateRequested Event

Tcp.CertificateRequested Event

This event is raised when a certificate has been requested.

[Visual Basic]
Public Event CertificateRequested As EventHandler
[C#]
public event EventHandler CertificateRequested;
[C++]
public: __event EventHandler* CertificateRequested;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Remarks

The CertificateRequested event is raised when a secure server requests a certificate from the client for client authentication. The SslStream.Certificate property of the current Tcp component (or, if using a different component, the Tcp component used for the underlying connection) must be set to a valid certificate. The easiest way to do this is to cast the sender parameter to an SslStream, then set the SslStream.Certificate property to a valid certificate.

Many objects provide a high-level Object.Certificate property, which represents the certificate used by the object. If the object you are using has such a high-level property it is recommended to use this property instead of the implementation described above.

Example

The following example demonstrates creating a simple secure client.

[Visual Basic]
    Private Sub SecureTest()

        'Allow component to negotiate best security option
        Tcp1.SecureProtocol = SecureProtocol.Auto

        ' Connect to a secure echo server.
        Tcp1.Connect("mysecureserver", 7)

        ' Send secure data
        Tcp1.Send("Test")

        ' Receive and display secure data
        System.Diagnostics.Debug.WriteLine(Tcp1.Receive().ToString())

        ' Close the connection
        Tcp1.Close()
    End Sub

    Private Sub Tcp1_CertificateRequested(ByVal sender As Object, ByVal e As System.EventArgs) Handles Tcp1.CertificateRequested
        'The server has requested client authentication
        'Allow the user to select a certificate
        Dim certform As New CertificateListForm(True, True)
        If (certform.ShowDialog(Me) = DialogResult.OK) Then
            Tcp1.Certificate = certform.SelectedCertificate
        End If
    End Sub

    Private Sub Tcp1_CertificateReceived(ByVal sender As Object, ByVal e As Dart.PowerTCP.SslSockets.CertificateReceivedEventArgs) Handles Tcp1.CertificateReceived
        'If the server's certificate is invalid for any reason,
        'the user can decide whether to proceed
        Dim msg As String = "The certificate was invalid for the following reason(s)" + vbLf

        ' Check to see if the certificate is from a trusted root.
        If (Not e.TrustedRoot) Then
            msg += "This certificate is not from a trusted root" + vbLf
        End If

        ' Check to see if the certificate has a valid date.
        If (Not e.ValidDate) Then
            msg += "This certificate does not have a valid date" + vbLf
        End If

        ' Check to see if the certificate has a valid name.
        If (Not e.ValidName) Then
            msg += "This certificate does not have a valid name" + vbLf
        End If

        If (Not e.Accept) Then
            msg += "Would you like to accept this certificate anyway?"
            If (MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
                e.Accept = True
            End If
        End If
    End Sub

[C#]
private void SecureTest()
{
    //Allow component to negotiate best security option
    tcp1.SecureProtocol = SecureProtocol.Auto;

    // Connect to a secure echo server.
    tcp1.Connect("mysecureserver", 7);

    // Send secure data
    tcp1.Send("Test");

    // Receive and display secure data
    System.Diagnostics.Debug.WriteLine(tcp1.Receive().ToString());

    // Close the connection
    tcp1.Close();
}

private void tcp1_CertificateRequested(object sender, System.EventArgs e)
{
    //The server has requested client authentication
    //Allow the user to select a certificate
    CertificateListForm certform = new CertificateListForm(true, true);
    if(certform.ShowDialog(this) == DialogResult.OK)
        tcp1.Certificate = certform.SelectedCertificate;
}

private void tcp1_CertificateReceived(object sender, CertificateReceivedEventArgs e)
{
    //If the server's certificate is invalid for any reason,
    //the user can decide whether to proceed
    string msg = "The certificate was invalid for the following reason(s)\n";

    // Check to see if the certificate is from a trusted root.
    if(!e.TrustedRoot)
        msg+= "This certificate is not from a trusted root\n";

    // Check to see if the certificate has a valid date.
    if(!e.ValidDate)
        msg+= "This certificate does not have a valid date\n";

    // Check to see if the certificate has a valid name.
    if(!e.ValidName)
        msg+= "This certificate does not have a valid name\n";

    if(!e.Accept)
    {
        msg += "Would you like to accept this certificate anyway?";
        if(MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) == DialogResult.Yes)
            e.Accept = true;
    }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


ConnectedChanged Event

Tcp.ConnectedChanged Event

NOTE: This event is now obsolete.

Superceded by ConnectedChangedEx event

Raised when the value of the Object.Connected property changes.

[Visual Basic]
Public Event ConnectedChanged As EventHandler
[C#]
public event EventHandler ConnectedChanged;
[C++]
public: __event EventHandler* ConnectedChanged;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Remarks

This event is raised when the value of the Object.Connected property changes. The value of the Object.Connected property changes whenever a TCP connection to a resource is either made or closed.

This event is useful in several scenarios, for example:

  • Displaying the user when a connection has been terminated.
  • Notifying the application if a connection has been terminated.

If you are using the PowerTCP component as a reference, you must create a method to handle the event yourself. For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see Using Events In PowerTCP.

Example

The following example demonstrates using the ConnectedChanged event to notify the user of the status of the connection.

[Visual Basic]
Private Sub Tcp1_ConnectedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Tcp1.ConnectedChanged
   ' Get current state of connection
   If Tcp1.Connected Then
      Debug.WriteLine("Connection made")

      ' Display info about the local/remote endpoints
      Debug.WriteLine("Local endpoint: " + Tcp1.LocalEndPoint.ToString())
      Debug.WriteLine("Remote endpoint: " + Tcp1.RemoteEndPoint.ToString())
   Else
      Debug.WriteLine("Connection closed")
   End If
End Sub

[C#]
private void tcp1_ConnectedChanged(object sender, System.EventArgs e)
{
    // Get current state of connection
    if(tcp1.Connected)
    {
        Debug.WriteLine("Connection made");

        // Display info about the local/remote endpoints
        Debug.WriteLine("Local endpoint: " + tcp1.LocalEndPoint.ToString());
        Debug.WriteLine("Remote endpoint: " + tcp1.RemoteEndPoint.ToString());
    }
    else
        Debug.WriteLine("Connection closed");
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


ConnectedChangedEx Event

Tcp.ConnectedChangedEx Event

Raised when the value of the Object.Connected property changes. Supersedes the ConnectedChanged event.

[Visual Basic]
Public Event ConnectedChangedEx As EventHandlerEx
[C#]
public event EventHandlerEx ConnectedChangedEx;
[C++]
public: __event EventHandlerEx* ConnectedChangedEx;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Remarks

This event is raised when the value of the Object.Connected property changes. The value of the Object.Connected property changes whenever a TCP connection to a resource is either made or closed.

This event is useful in several scenarios, for example:

  • Displaying the user when a connection has been terminated.
  • Notifying the application if a connection has been terminated.

If you are using the PowerTCP component as a reference, you must create a method to handle the event yourself. For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see Using Events In PowerTCP.

Example

The following example demonstrates using the ConnectedChanged event to notify the user of the status of the connection.

[Visual Basic]
Private Sub Tcp1_ConnectedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Tcp1.ConnectedChanged
   ' Get current state of connection
   If Tcp1.Connected Then
      Debug.WriteLine("Connection made")

      ' Display info about the local/remote endpoints
      Debug.WriteLine("Local endpoint: " + Tcp1.LocalEndPoint.ToString())
      Debug.WriteLine("Remote endpoint: " + Tcp1.RemoteEndPoint.ToString())
   Else
      Debug.WriteLine("Connection closed")
   End If
End Sub

[C#]
private void tcp1_ConnectedChanged(object sender, System.EventArgs e)
{
    // Get current state of connection
    if(tcp1.Connected)
    {
        Debug.WriteLine("Connection made");

        // Display info about the local/remote endpoints
        Debug.WriteLine("Local endpoint: " + tcp1.LocalEndPoint.ToString());
        Debug.WriteLine("Remote endpoint: " + tcp1.RemoteEndPoint.ToString());
    }
    else
        Debug.WriteLine("Connection closed");
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


EndConnect Event

Tcp.EndConnect Event

Raised when the BeginConnect request completes.

[Visual Basic]
Public Event EndConnect As ConnectEventHandler
[C#]
public event ConnectEventHandler EndConnect;
[C++]
public: __event ConnectEventHandler* EndConnect;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type ExceptionEventArgs containing data related to this event. The following ExceptionEventArgs properties provide information specific to this event.

Property | Description
Exception | Gets any exception which occurred during the asynchronous operation.
State | Gets the object that was included as part of the associated method call.

Remarks

This event is raised when the asynchronous method call BeginConnect completes. An EventArgs object is passed into the event, containing information about the event.

For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see the topic, Using Events In PowerTCP.

If you are using the Tcp component as a reference, you must create a method to handle the event yourself.

This event MUST be implemented if you are using the BeginConnect method.

Example

The following example demonstrates asynchronously connecting using the BeginConnect method.

[Visual Basic]
Private Sub Test()
   ' Begin to asynchronously connect to an echo port.
   Tcp1.BeginConnect("atropos", 7)
End Sub

Private Sub Tcp1_EndConnect(ByVal sender As Object, ByVal e As ExceptionEventArgs) Handles Tcp1.EndConnect
   ' Connect complete, check for any exceptions
   If e.Exception Is Nothing Then
      ' Now send some data.
      Tcp1.Send("hello")

      ' Receive the data back.
      Dim seg As Segment = Tcp1.Receive()
      Debug.WriteLine(seg.ToString())
   End If
End Sub

[C#]
private void Test()
{
   // Begin to asynchronously connect to an echo port.
   tcp1.BeginConnect("atropos", 7);
}

private void tcp1_EndConnect(object sender, ExceptionEventArgs e)
{
   // Connect complete, check for any exceptions
   if(e.Exception == null)
   {
      // Now send some data.
      tcp1.Send("hello");

      // Receive the data back.
      Segment seg = tcp1.Receive();

      Debug.WriteLine(seg.ToString());
   }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


EndReceive Event

Tcp.EndReceive Event

Raised when the BeginReceive request completes.

[Visual Basic]
Public Event EndReceive As SegmentEventHandler
[C#]
public event SegmentEventHandler EndReceive;
[C++]
public: __event SegmentEventHandler* EndReceive;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type SegmentEventArgs containing data related to this event. The following SegmentEventArgs properties provide information specific to this event.

Property | Description
Exception | Gets any exception which occurred during the asynchronous operation.
Segment | The Segment object referencing the data that was sent or received.
State | Gets the object that was included as part of the associated method call.

Remarks

This event is raised when the asynchronous method call BeginReceive completes. A SegmentEventArgs object is passed into the event, containing information about the event, such as the data received.

If any errors occurred during the asynchronous operation, they would be returned in the SegmentEventArgs object, check Exception to check for any exception.

For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see the topic, Using Events In PowerTCP.

If you are using the Tcp component as a reference, you must create a method to handle the event yourself.

This event MUST be implemented if you are using the BeginReceive method.

Example

The following example demonstrates asynchronous receiving and sending of data.

[Visual Basic]
Private Sub AsynchTcpDemo()

   ' Attempt to connect to an echo port.
   Try
      Tcp1.Connect("myserver", 7)
   Catch ex As Exception
      Return
   End Try

   ' Send data, since we are connected to an echo port, the same data should be returned.
   ' The following code demonstrates asynchronously sending data. When data has been sent
   ' the EndSend event will be raised.

   Dim buffer() As Byte = System.Text.Encoding.Default.GetBytes("a")
   Tcp1.BeginSend(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)
End Sub

Private Sub Tcp1_EndSend(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndSend
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Send is complete. Display info about the data sent.
      Debug.WriteLine("Byte count sent: " + e.Segment.Count)
      Debug.WriteLine("Data sent: " + e.Segment.ToString())

      Dim buffer(Tcp1.ReceiveBufferSize) As Byte

      ' Receive the data. The EndReceive event will be raised upon completion.
      Tcp1.BeginReceive(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)

    End If
End Sub

Private Sub Tcp1_EndReceive(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndReceive
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Receive is complete. Display info about the data sent.
      Debug.WriteLine("Byte count received: " + e.Segment.Count)
      Debug.WriteLine("Data received: " + e.Segment.ToString())

      ' Close the connection
      Tcp1.Close()
    End If
End Sub

[C#]
private void AsynchTcpDemo()
{
    // Attempt to connect to an echo port.
    try
    {
        tcp1.Connect("myserver", 7);
    }
    catch(Exception ex)
    {return;}

    // Send data, since we are connected to an echo port, the same data should be returned.
    // The following code demonstrates asynchronously sending data. When data has been sent
    // the EndSend event will be raised.

    byte[] buffer = System.Text.Encoding.Default.GetBytes("a");
    tcp1.BeginSend(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
}

private void tcp1_EndSend(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Send is complete. Display info about the data sent.
        Debug.WriteLine("Byte count sent: " + e.Segment.Count);
        Debug.WriteLine("Data sent: " + e.Segment.ToString());

        byte[] buffer = new byte[tcp1.ReceiveBufferSize];

        // Receive the data. The EndReceive event will be raised upon completion.
        tcp1.BeginReceive(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
    }
}

private void tcp1_EndReceive(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Receive is complete. Display info about the data sent.
        Debug.WriteLine("Byte count received: " + e.Segment.Count);
        Debug.WriteLine("Data received: " + e.Segment.ToString());

        // Close the connection
        tcp1.Close();
    }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


EndSend Event

Tcp.EndSend Event

Raised when the BeginSend request completes.

[Visual Basic]
Public Event EndSend As SegmentEventHandler
[C#]
public event SegmentEventHandler EndSend;
[C++]
public: __event SegmentEventHandler* EndSend;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type SegmentEventArgs containing data related to this event. The following SegmentEventArgs properties provide information specific to this event.

Property | Description
Exception | Gets any exception which occurred during the asynchronous operation.
Segment | The Segment object referencing the data that was sent or received.
State | Gets the object that was included as part of the associated method call.

Remarks

This event is raised when the asynchronous method call BeginSend completes. A SegmentEventArgs object is passed into the event, containing information about the event, such as the data sent.

If any errors occurred during the asynchronous operation, they would be returned in the SegmentEventArgs object, check Exception to check for any exception.

For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see the topic, Using Events In PowerTCP.

If you are using the Tcp component as a reference, you must create a method to handle the event yourself.

This event MUST be implemented if you are using the BeginSend method.

Example

The following example demonstrates asynchronous receiving and sending of data.

[Visual Basic]
Private Sub AsynchTcpDemo()

   ' Attempt to connect to an echo port.
   Try
      Tcp1.Connect("myserver", 7)
   Catch ex As Exception
      Return
   End Try

   ' Send data, since we are connected to an echo port, the same data should be returned.
   ' The following code demonstrates asynchronously sending data. When data has been sent
   ' the EndSend event will be raised.

   Dim buffer() As Byte = System.Text.Encoding.Default.GetBytes("a")
   Tcp1.BeginSend(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)
End Sub

Private Sub Tcp1_EndSend(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndSend
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Send is complete. Display info about the data sent.
      Debug.WriteLine("Byte count sent: " + e.Segment.Count)
      Debug.WriteLine("Data sent: " + e.Segment.ToString())

      Dim buffer(Tcp1.ReceiveBufferSize) As Byte

      ' Receive the data. The EndReceive event will be raised upon completion.
      Tcp1.BeginReceive(buffer, 0, buffer.Length, Net.Sockets.SocketFlags.None, Nothing)

    End If
End Sub

Private Sub Tcp1_EndReceive(ByVal sender As Object, ByVal e As Dart.PowerTCP.SegmentEventArgs) Handles Tcp1.EndReceive
   ' Check for exception
   If e.Exception Is Nothing Then

      ' Receive is complete. Display info about the data sent.
      Debug.WriteLine("Byte count received: " + e.Segment.Count)
      Debug.WriteLine("Data received: " + e.Segment.ToString())

      ' Close the connection
      Tcp1.Close()
    End If
End Sub

[C#]
private void AsynchTcpDemo()
{
    // Attempt to connect to an echo port.
    try
    {
        tcp1.Connect("myserver", 7);
    }
    catch(Exception ex)
    {return;}

    // Send data, since we are connected to an echo port, the same data should be returned.
    // The following code demonstrates asynchronously sending data. When data has been sent
    // the EndSend event will be raised.

    byte[] buffer = System.Text.Encoding.Default.GetBytes("a");
    tcp1.BeginSend(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
}

private void tcp1_EndSend(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Send is complete. Display info about the data sent.
        Debug.WriteLine("Byte count sent: " + e.Segment.Count);
        Debug.WriteLine("Data sent: " + e.Segment.ToString());

        byte[] buffer = new byte[tcp1.ReceiveBufferSize];

        // Receive the data. The EndReceive event will be raised upon completion.
        tcp1.BeginReceive(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, null);
    }
}

private void tcp1_EndReceive(object sender, Dart.PowerTCP.SegmentEventArgs e)
{
    // Check for exception
    if(e.Exception == null)
    {
        // Receive is complete. Display info about the data sent.
        Debug.WriteLine("Byte count received: " + e.Segment.Count);
        Debug.WriteLine("Data received: " + e.Segment.ToString());

        // Close the connection
        tcp1.Close();
    }
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


RawTrace Event

Tcp.RawTrace Event

Raised when data has been sent/received.

[Visual Basic]
Public Event RawTrace As SegmentEventHandler
[C#]
public event SegmentEventHandler RawTrace;
[C++]
public: __event SegmentEventHandler* RawTrace;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type SegmentEventArgs containing data related to this event. The following SegmentEventArgs properties provide information specific to this event.

Property | Description
Exception | Gets any exception which occurred during the asynchronous operation.
Segment | The Segment object referencing the data that was sent or received.
State | Gets the object that was included as part of the associated method call.

Remarks

Use this event for advanced runtime debugging for security implementations. For general data traces use the Object.Trace event.

The Object.RawTrace event always reports actual data sent/received over the socket. The Count of each segment reflects the number of bytes actually written and received. The Object.Trace event reports data sent/received at a higher level. For example, for the Telnet component, Object.Trace reports data sent/received, but does not report IAC option sequences that are processed by TelnetStream, whereas Object.RawTrace allows you to trace the actual data sent/received, including Telnet option commands.

If you are using the PowerTCP component as a reference, you must create a method to handle the event yourself. For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see Using Events In PowerTCP.

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


Trace Event

Tcp.Trace Event

Raised when data has been sent/received.

[Visual Basic]
Public Event Trace As SegmentEventHandler
[C#]
public event SegmentEventHandler Trace;
[C++]
public: __event SegmentEventHandler* Trace;

[JScript] In JScript, you can use the events defined by a type, but you cannot define your own.

Event Data

The event handler receives an argument of type SegmentEventArgs containing data related to this event. The following SegmentEventArgs properties provide information specific to this event.

Property | Description
Exception | Gets any exception which occurred during the asynchronous operation.
Segment | The Segment object referencing the data that was sent or received.
State | Gets the object that was included as part of the associated method call.

Remarks

This event is raised when commands or data has been sent/received. If you are using a component which uses TCP as the transport protocol a SegmentEventArgs object is passed into the event containing any commands or data sent or received. If you are using a component which uses UDP as the transport protocol a DatagramEventArgs object is passed into the event containing any commands or data sent or received.

The Object.RawTrace event always reports actual data sent/received over the socket. The Count of each segment reflects the number of bytes actually written and received. The Object.Trace event reports data sent/received at a higher level. For example, for the Telnet component, Object.Trace reports data sent/received, but does not report IAC option sequences that are processed by TelnetStream, whereas Object.RawTrace allows you to trace the actual data sent/received, including Telnet option commands.

If you are using the PowerTCP component as a reference, you must create a method to handle the event yourself. For more information on using events using PowerTCP.NET within the Visual Studio.NET environment, see Using Events In PowerTCP.

Example

The following example demonstrates using the Tcp component's Trace event to create a log of all data sent and received.

[Visual Basic]
Private Sub Tcp1_Trace(ByVal sender As Object, ByVal e As SegmentEventArgs) Handles Tcp1.Trace
   ' Get the data into a byte array
   Dim buffer As Byte() = System.Text.Encoding.Default.GetBytes(e.Segment.ToString())

   ' Create a FileStream
   Dim f As New FileStream("C:\test\socketlog.log", FileMode.Append)

   ' Write the data to the file.
   f.Write(buffer, 0, buffer.Length)
   f.Close()
End Sub

[C#]
private void tcp1_Trace(object sender, SegmentEventArgs e)
{
   // Get the data into a byte array
   byte[] buffer = System.Text.Encoding.Default.GetBytes(e.Segment.ToString());

   // Create a FileStream
   FileStream f = new FileStream("C:\\test\\socketlog.txt", FileMode.Append);

   // Write the data to the file.
   f.Write(buffer, 0, buffer.Length);
   f.Close();
}

See Also

Tcp Class | Dart.PowerTCP.Ftp Namespace


TcpStream Class

TcpStream implements sending and receiving of data through network sockets.

For a list of all members of this type, see TcpStream Members.

System.Object
System.MarshalByRefObject
System.IO.Stream
Dart.PowerTCP.Ftp.EnhancedStream
Dart.PowerTCP.Ftp.TcpStream

[Visual Basic]
Public Class TcpStream
    Inherits EnhancedStream
[C#]
public class TcpStream : EnhancedStream
[C++]
public __gc class TcpStream : public EnhancedStream
[JScript]
public class TcpStream extends EnhancedStream

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

All PowerTCP components which use TCP as the transport-layer protocol use this class as the interface to the Socket.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

TcpStream Members | Dart.PowerTCP.Ftp Namespace


TcpStream Members

TcpStream overview

Public Instance Constructors

TcpStream Constructor Initializes a new instance of the TcpStream class for the specified Tcp object.

Public Instance Properties

Available | Gets the amount of data that has been received from the network and is available to be read.
CanRead | Overridden. Indicates that data can be read from the stream.
CanSeek (inherited from EnhancedStream) | Gets a value indicating whether the current stream supports seeking.
CanWrite | Overridden. Indicates that data can be written to the stream.
Charset (inherited from EnhancedStream) | Gets and sets the character set used for string/byte array conversions.
Encoding (inherited from EnhancedStream) | Gets or sets the type of encoding to use.
Length (inherited from EnhancedStream) | The length of data available on the stream. This method always throws a NotSupportedException.
Position (inherited from EnhancedStream) | Gets or sets the position in the stream. This method always throws a NotSupportedException.

Public Instance Methods

BeginRead (inherited from Stream) | Begins an asynchronous read operation.
BeginWrite (inherited from Stream) | Begins an asynchronous write operation.
Close | Overridden. Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose (inherited from EnhancedStream) | Releases all resources associated with the object.
EndRead (inherited from Stream) | Waits for the pending asynchronous read to complete.
EndWrite (inherited from Stream) | Ends an asynchronous write operation.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
Flush (inherited from EnhancedStream) | Overridden. Default implementation is no-op. May be overridden by derived classes
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
Read | Overridden. Overloaded. Reads at least one byte of data from the stream and copies it into the provided buffer.
Read (inherited from EnhancedStream) | Overloaded. Reads at least one byte of data from the Stream and copies it into the provided buffer.
ReadByte (inherited from Stream) | Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
Save (inherited from EnhancedStream) | Overloaded. Saves the data in the stream to the file specified by fileName.
Seek (inherited from EnhancedStream) | Overridden. Sets the position within the current Stream to the specified value. Always throws a NotSupportedException.
SetLength (inherited from EnhancedStream) | Overridden. Sets the length of the current Stream to the specified value. Always throws a NotSupportedException.
ToArray (inherited from EnhancedStream) | Returns the byte array representation of the Stream data.
ToString (inherited from EnhancedStream) | Overridden. Returns the string representation of the Stream data.
Write | Overridden. Overloaded. Writes a sequence of bytes to the stream and returns when the operation is complete.
Write (inherited from EnhancedStream) | Overloaded. Writes a sequence of bytes to the Stream and returns when the operation is complete.
WriteByte (inherited from Stream) | Writes a byte to the current position in the stream and advances the position within the stream by one byte.
WriteTo (inherited from EnhancedStream) | Overloaded. Writes all of the data contained in this Stream to a destination Stream.

See Also

TcpStream Class | Dart.PowerTCP.Ftp Namespace


TcpStream Constructor

Initializes a new instance of the TcpStream class for the specified Tcp object.

[Visual Basic]
Public Sub New( _
   ByVal tcp As Tcp _
)
[C#]
public TcpStream(
   Tcp tcp
);
[C++]
public: TcpStream(
   Tcp* tcp
);
[JScript]
public function TcpStream(
   Tcp tcp
);

Parameters

tcp
The Tcp object that provides the network data for the new TcpStream.

See Also

TcpStream Class | Dart.PowerTCP.Ftp Namespace


TcpStream Properties

The properties of the TcpStream class are listed below. For a complete list of TcpStream class members, see the TcpStream Members topic.

Public Instance Properties

Available | Gets the amount of data that has been received from the network and is available to be read.
CanRead | Overridden. Indicates that data can be read from the stream.
CanSeek (inherited from EnhancedStream) | Gets a value indicating whether the current stream supports seeking.
CanWrite | Overridden. Indicates that data can be written to the stream.
Charset (inherited from EnhancedStream) | Gets and sets the character set used for string/byte array conversions.
Encoding (inherited from EnhancedStream) | Gets or sets the type of encoding to use.
Length (inherited from EnhancedStream) | The length of data available on the stream. This method always throws a NotSupportedException.
Position (inherited from EnhancedStream) | Gets or sets the position in the stream. This method always throws a NotSupportedException.

See Also

TcpStream Class | Dart.PowerTCP.Ftp Namespace


Available Property

TcpStream.Available Property

Gets the amount of data that has been received from the network and is available to be read.

[Visual Basic]
Overridable Public Property ReadOnly Available As Integer
[C#]
public virtual int Available { get; }
[C++]
public: virtual __property int get_Available();
[JScript]
public virtual function get Available() : int

See Also

TcpStream Class | Dart.PowerTCP.Ftp Namespace


CanRead Property

TcpStream.CanRead Property

Indicates that data can be read from the stream.

[Visual Basic]
Overrides Public Property ReadOnly CanRead As Boolean
[C#]
public override bool CanRead { get; }
[C++]
public: __property bool get_CanRead();
[JScript]
public override function get CanRead() : bool

Remarks

If the stream is closed, this property returns false.

See Also

TcpStream Class | Dart.PowerTCP.Ftp Namespace


CanWrite Property

TcpStream.CanWrite Property

Indicates that data can be written to the stream.

[Visual Basic]
Overrides Public Property ReadOnly CanWrite As Boolean
[C#]
public override bool CanWrite { get; }
[C++]
public: __property bool get_CanWrite();
[JScript]
public override function get CanWrite() : bool

Remarks

If the stream is closed, this property returns false.

See Also

TcpStream Class | Dart.PowerTCP.Ftp Namespace


TcpStream Methods

The methods of the TcpStream class are listed below. For a complete list of TcpStream class members, see the TcpStream Members topic.

Public Instance Methods

BeginRead (inherited from Stream) | Begins an asynchronous read operation.
BeginWrite (inherited from Stream) | Begins an asynchronous write operation.
Close | Overridden. Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
CreateObjRef (inherited from MarshalByRefObject) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose (inherited from EnhancedStream) | Releases all resources associated with the object.
EndRead (inherited from Stream) | Waits for the pending asynchronous read to complete.
EndWrite (inherited from Stream) | Ends an asynchronous write operation.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
Flush (inherited from EnhancedStream) | Overridden. Default implementation is no-op. May be overridden by derived classes
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) | Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
InitializeLifetimeService (inherited from MarshalByRefObject) | Obtains a lifetime service object to control the lifetime policy for this instance.
Read | Overridden. Overloaded. Reads at least one byte of data from the stream and copies it into the provided buffer.
Read (inherited from EnhancedStream) | Overloaded. Reads at least one byte of data from the Stream and copies it into the provided buffer.
ReadByte (inherited from Stream) | Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
Save (inherited from EnhancedStream) | Overloaded. Saves the data in the stream to the file specified by fileName.
Seek (inherited from EnhancedStream) | Overridden. Sets the position within the current Stream to the specified value. Always throws a NotSupportedException.
SetLength (inherited from EnhancedStream) | Overridden. Sets the length of the current Stream to the specified value. Always throws a NotSupportedException.
ToArray (inherited from EnhancedStream) | Returns the byte array representation of the Stream data.
ToString (inherited from EnhancedStream) | Overridden. Returns the string representation of the Stream data.
Write | Overridden. Overloaded. Writes a sequence of bytes to the stream and returns when the operation is complete.
Write (inherited from EnhancedStream) | Overloaded. Writes a sequence of bytes to the Stream and returns when the operation is complete.
WriteByte (inherited from Stream) | Writes a byte to the current position in the stream and advances the position within the stream by one byte.
WriteTo (inherited from EnhancedStream) | Overloaded. Writes all of the data contained in this Stream to a destination Stream.

See Also

TcpStream Class | Dart.PowerTCP.Ftp Namespace


Close Method

TcpStream.Close Method

Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.

[Visual Basic]
Overrides Public Sub Close()
[C#]
public override void Close();
[C++]
public: void Close();
[JScript]
public override function Close();

See Also

TcpStream Class | Dart.PowerTCP.Ftp Namespace


Read Method

TcpStream.Read Method

Reads at least one byte of data from the stream and copies it into the provided buffer.

Overload List

Reads at least one byte of data from the Stream and copies it into the provided buffer.
Inherited from EnhancedStream.

[Visual Basic] Public Function Read(ByVal Byte()) As Integer
[C#] public int Read(byte[]);
[C++] public: int Read(char __gc[]);
[JScript] public function Read(Byte[]): int;

Reads at least one byte of data from the stream and copies it into the provided buffer.

[Visual Basic] Overrides OverloadsPublic Function Read(ByVal Byte(),ByVal Integer,ByVal Integer) As Integer
[C#] public override int Read(byte[],int,int);
[C++] public: int Read(char __gc[],int,int);
[JScript] public override function Read(Byte[],int,int): int;

See Also

TcpStream Class | Dart.PowerTCP.Ftp Namespace


Read Method (Byte[], Int32, Int32)

TcpStream.Read Method (Byte[], Int32, Int32)

Reads at least one byte of data from the stream and copies it into the provided buffer.

[Visual Basic]
Overrides  OverloadsPublic Function Read( _
   ByVal buffer As Byte(), _
   ByVal offset As Integer, _
   ByVal size As Integer _
) As Integer
[C#]
public override int Read(
   byte[] buffer,
   int offset,
   int size
);
[C++]
public: int Read(
   char buffer __gc[],
   int offset,
   int size
);
[JScript]
public override function Read(
   Byte[] buffer,
   int offset,
   int size
): int;

Parameters

buffer
The storage location for the received data.
offset
The zero-based position in the buffer at which to store the received data.
size
The maximum number of bytes to read.

Return Value

The total number of bytes read into the buffer.

Remarks

This is the standard method to use when reading a stream synchronously.

The return value may be less than the number of bytes requested if that many bytes are not currently available, or zero if the end of the stream has been reached. Applications must check this value to know how many bytes were read into the buffer.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Readable.
ArgumentNullException | Thrown when the receiving buffer is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when size is less than or equal to zero.
ArgumentException | Thrown when the (offset + size) > buffer.Length.

See Also

TcpStream Class | Dart.PowerTCP.Ftp Namespace | TcpStream.Read Overload List


Write Method

TcpStream.Write Method

Writes a sequence of bytes to the stream and returns when the operation is complete.

Overload List

Writes a sequence of bytes to the Stream and returns when the operation is complete.
Inherited from EnhancedStream.

[Visual Basic] Public Sub Write(ByVal Byte())
[C#] public void Write(byte[]);
[C++] public: void Write(char __gc[]);
[JScript] public function Write(Byte[]);

Writes a sequence of bytes to the stream and returns when the operation is complete.

[Visual Basic] Overrides OverloadsPublic Sub Write(ByVal Byte(),ByVal Integer,ByVal Integer)
[C#] public override void Write(byte[],int,int);
[C++] public: void Write(char __gc[],int,int);
[JScript] public override function Write(Byte[],int,int);

See Also

TcpStream Class | Dart.PowerTCP.Ftp Namespace


Write Method (Byte[], Int32, Int32)

TcpStream.Write Method (Byte[], Int32, Int32)

Writes a sequence of bytes to the stream and returns when the operation is complete.

[Visual Basic]
Overrides  OverloadsPublic Sub Write( _
   ByVal buffer As Byte(), _
   ByVal offset As Integer, _
   ByVal size As Integer _
)
[C#]
public override void Write(
   byte[] buffer,
   int offset,
   int size
);
[C++]
public: void Write(
   char buffer __gc[],
   int offset,
   int size
);
[JScript]
public override function Write(
   Byte[] buffer,
   int offset,
   int size
);

Parameters

buffer
The storage location of the data to be sent.
offset
The zero-based position in the buffer from which to begin writing from.
size
The exact number of bytes to write.

Remarks

Use the CanWrite property to determine whether the current instance supports writing.

Exceptions

Exception Type | Condition
IOException | Thrown when the stream is not Writeable.
ArgumentNullException | Thrown when buffer is null.
ArgumentOutOfRangeException | Thrown when the offset is less than zero or when size is less than or equal to zero.
ArgumentException | Thrown when the (offset + size) > buffer.Length.

See Also

TcpStream Class | Dart.PowerTCP.Ftp Namespace | TcpStream.Write Overload List


ZStreamException Class

Indicates a failure in ZLIB compression processing.

For a list of all members of this type, see ZStreamException Members.

System.Object
System.Exception
System.SystemException
System.IO.IOException
Dart.PowerTCP.Ftp.ZStreamException

[Visual Basic]
Public Class ZStreamException
    Inherits IOException
[C#]
public class ZStreamException : IOException
[C++]
public __gc class ZStreamException : public IOException
[JScript]
public class ZStreamException extends IOException

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Requirements

Namespace: Dart.PowerTCP.Ftp

Assembly: Dart.PowerTCP.Ftp (in Dart.PowerTCP.Ftp.dll)

See Also

ZStreamException Members | Dart.PowerTCP.Ftp Namespace


ZStreamException Members

ZStreamException overview

Public Instance Constructors

ZStreamException Constructor Initializes a new instance of the ZStreamException class.

Public Instance Properties

HelpLink (inherited from Exception) | Gets or sets a link to the help file associated with this exception.
InnerException (inherited from Exception) | Gets the Exception instance that caused the current exception.
Message (inherited from Exception) | Gets a message that describes the current exception.
Source (inherited from Exception) | Gets or sets the name of the application or the object that causes the error.
StackTrace (inherited from Exception) | Gets a string representation of the frames on the call stack at the time the current exception was thrown.
TargetSite (inherited from Exception) | Gets the method that throws the current exception.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetBaseException (inherited from Exception) | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetObjectData (inherited from Exception) | When overridden in a derived class, sets the SerializationInfo with information about the exception.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Exception) | Overridden. Creates and returns a string representation of the current exception.

See Also

ZStreamException Class | Dart.PowerTCP.Ftp Namespace


ZStreamException Constructor

Initializes a new instance of the ZStreamException class.

[Visual Basic]
Public Sub New( _
   ByVal s As String _
)
[C#]
public ZStreamException(
   string s
);
[C++]
public: ZStreamException(
   String* s
);
[JScript]
public function ZStreamException(
   String s
);

See Also

ZStreamException Class | Dart.PowerTCP.Ftp Namespace


Samples

PowerTCP FTP for .NET Samples

The following samples are full application which demonstrate usage of PowerTCP FTP for .NET. The default directory for sample applications is:

[PersonalFolder]\Dart Sample Applications\PowerTCP\FTP for .NET

The following table shows the samples for this release.

Sample | Description | Environments
ListView Client | Demonstrates storing and retrieving files, sending commands, displaying file transfer progress, and retrieving and displaying listings. | C# and VB .NET Applications in VS.NET 2003 and 2005
MGet Demo | Demonstrates how to retrieve multiple files from an FTP server to a local directory using a wildcard expression. | C# and VB .NET Applications in VS.NET 2003 and 2005
MPut Demo | Demonstrates how to store multiple files from a local directory to an FTP server using a wildcard expression. | C# and VB .NET Applications in VS.NET 2003 and 2005
StreamGet Demo | Demonstrates how to use the Ftp component to retrieve a file as a MemoryStream. | C# and VB .NET Applications in VS.NET 2003 and 2005
StreamPut Demo | Demonstrates how to use the Ftp component to store a MemoryStream as a file. | C# and VB .NET Applications in VS.NET 2003 and 2005
Transfer Manager | Demonstrates how to use the Ftp component asynchronously, to transfer multiple files simultaneously. | VB .NET Application in VS.NET 2003 and 2005
ListView Web Client | Demonstrates storing and retrieving files, sending commands, displaying file transfer progress, and retrieving and displaying listings in a web application. | C# and VB ASP.NET Applications in VS.NET 2003 and 2005

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Dart.PowerTCP.FtpHierarchy

Dart.PowerTCP.Ftp Hierarchy

System.Object
Dart.PowerTCP.Ftp.FtpFile
Dart.PowerTCP.Ftp.FtpProxy
Dart.PowerTCP.Ftp.FtpWebRequestCreator ---- System.Net.IWebRequestCreate
Dart.PowerTCP.Ftp.Invoke
Dart.PowerTCP.Ftp.ListEntry
Dart.PowerTCP.Ftp.Proxy
Dart.PowerTCP.Ftp.Response
Dart.PowerTCP.Ftp.Segment
System.Collections.ArrayList ---- System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList, System.ICloneable
Dart.PowerTCP.Ftp.CertificateStore ---- System.IDisposable
Dart.PowerTCP.Ftp.Listing
System.Delegate ---- System.ICloneable, System.Runtime.Serialization.ISerializable
System.MulticastDelegate
Dart.PowerTCP.Ftp.CertificateReceivedEventHandler
Dart.PowerTCP.Ftp.CertificateRequestedEventHandler
Dart.PowerTCP.Ftp.ConnectEventHandler
Dart.PowerTCP.Ftp.EventHandlerEx
Dart.PowerTCP.Ftp.FileEventHandler
Dart.PowerTCP.Ftp.FtpProgressEventHandler
Dart.PowerTCP.Ftp.InvokeEventHandler
Dart.PowerTCP.Ftp.ListEventHandler
Dart.PowerTCP.Ftp.PreviewEventHandler
Dart.PowerTCP.Ftp.SegmentEventHandler
System.EventArgs
Dart.PowerTCP.Ftp.CertificateReceivedEventArgs
Dart.PowerTCP.Ftp.ExceptionEventArgs
Dart.PowerTCP.Ftp.FileEventArgs
Dart.PowerTCP.Ftp.FtpProgressEventArgs
Dart.PowerTCP.Ftp.InvokeEventArgs
Dart.PowerTCP.Ftp.ListEventArgs
Dart.PowerTCP.Ftp.PreviewEventArgs
Dart.PowerTCP.Ftp.SegmentEventArgs
System.Exception ---- System.Runtime.Serialization.ISerializable
System.ApplicationException
Dart.PowerTCP.Ftp.BusyException
Dart.PowerTCP.Ftp.InvalidParameterTypeException
Dart.PowerTCP.Ftp.ProtocolException
System.SystemException
System.IO.IOException
Dart.PowerTCP.Ftp.ZStreamException
System.MarshalByRefObject
Dart.PowerTCP.Ftp.Certificate ---- System.IDisposable
System.ComponentModel.Component ---- System.ComponentModel.IComponent, System.IDisposable
Dart.PowerTCP.Ftp.Ftp
Dart.PowerTCP.Ftp.Tcp
System.IO.Stream ---- System.IDisposable
Dart.PowerTCP.Ftp.EnhancedStream
Dart.PowerTCP.Ftp.PipeStream
Dart.PowerTCP.Ftp.SegmentedStream
Dart.PowerTCP.Ftp.TcpStream
System.Net.WebRequest ---- System.Runtime.Serialization.ISerializable
Dart.PowerTCP.Ftp.FtpWebRequest
System.Net.WebResponse ---- System.IDisposable, System.Runtime.Serialization.ISerializable
Dart.PowerTCP.Ftp.FtpWebResponse
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Dart.PowerTCP.Ftp.CertificateProvider
Dart.PowerTCP.Ftp.CertificateStoreLocation
Dart.PowerTCP.Ftp.CertificateStoreName
Dart.PowerTCP.Ftp.Compression
Dart.PowerTCP.Ftp.EntryType
Dart.PowerTCP.Ftp.FileType
Dart.PowerTCP.Ftp.FtpCommand
Dart.PowerTCP.Ftp.FtpFileStatus
Dart.PowerTCP.Ftp.FtpProxyType
Dart.PowerTCP.Ftp.KeyUsage
Dart.PowerTCP.Ftp.ListingFormat
Dart.PowerTCP.Ftp.ProxyType
Dart.PowerTCP.Ftp.SecureProtocol
Dart.PowerTCP.Ftp.Security
Dart.PowerTCP.Ftp.StoreType

See Also

Dart.PowerTCP.Ftp Namespace


Creating An Instance Of The Ftp Component In Other Environments

Creating An Instance Of The Ftp Component Using Visual Studio .NET

Although the Ftp component can be used in your preferred environment on any machine that has the .NET Framework installed, the recommended method is to use the Ftp component within the Visual Studio .NET environment.

To create an Ftp component within Visual Studio .NET, use the following steps:

  1. Start Visual Studio .NET.
  2. From the File menu, choose New, then choose Project.
  3. From the resulting dialog box, choose either Visual C# Projects or Visual Basic Projects then choose Windows Application. Specfy a name and a location for the project, then click OK.
  4. The PowerTCP Ftp component is dependent on the PowerTCP Tcp component which must be added as a reference. To do this right-click the References folder in the Solution Explorer and choose Add Reference (see the screen shot below). If the Solution Explorer is not visible, navigate to the View menu and choose Solution Explorer.

  5. Now add the Ftp component to the form. To do this, right-click on the ToolBox and choose Customize ToolBox (see the screen shot below). If the ToolBox is not visible, naviage to the View menu and choose ToolBox.

  6. From the resulting dialog box, choose the .NET Framework Components tab, then scroll until you find the Ftp component (see the screen shot below). Check the checkbox next to it and select OK.

  7. Now click the Ftp component icon on the ToolBox, and "drag" an instance of it onto the form. The Visual Studio .NET environment will automatically create and instantiate an instance of the Ftp component.
  8. Now make a quick application to test. Drag a button onto the form.
  9. Add the following code to the button "on-click" event handler.
    [C#]
ftp1.Server = "MyFtpServer"; // Substitute your server here.
ftp1.Username = "blah"; // Substitute your username here.
ftp1.Password = "mypass"; // Substitute your password here.

// Now execute a simple method. In this case we use GetDirectory to return the
// working directory. As long as Server, Username, and Password are set, login will
// occur transparently.
string dir;
try
{
   dir = ftp1.GetDirectory();
}
catch
{
   MessageBox.Show("Error");
   return;
}
MessageBox.Show(dir);
[Visual Basic]
Ftp1.Server = "MyFtpServer" ' Substitute your server here.
Ftp1.Username = "blah" ' Substitute your username here.
Ftp1.Password = "mypass" ' Substitute your password here.

' Now execute a simple method. In this case we use GetDirectory to return the
' working directory. As long as Server, Username, and Password are set, login will
' occur transparently.
Dim dir as string

Try
   dir = ftp1.GetDirectory()
Catch
   MessageBox.Show("Error");
   Exit Sub
End Try

MessageBox.Show(dir)
  10. Navigate to the Debug menu and choose Start. The app will compile and execute. Click the button and you should see your FTP server's default working directory in the MessageBox.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Creating An Instance Of The Ftp Component

This topic gives an overview of adding an Ftp component to a Windows Application. The Ftp component can be used within Visual Studio .NET or in any other environment that has the .NET Framework installed. The preferred method is to use the component within Visual Studio .NET as it adds a great deal of design time support such as:

  • Automatic object creation/instantiation.
  • Automated event subscription.
  • Context sensitive help.
  • Autocomplete support.
  • Tool Tip help
  • The ability to use PowerTCP Controls for testing such as the Editor property.
  • Access to the Properties Window.

We realize not everybody will be using Visual Studio .NET for their development. Instructions are provided for both those working with Visual Studio .NET, and those working with other environments (such as NotePad).

Of course, this topic does not take into account any "built-in" support for creating an using objects that a non-Visual Studio .NET environment may have. This topic simply addresses how to use the component with the .NET Framework installed only.

In This Section

Creating An Instance Of The Ftp Component Using Visual Studio .NET
Provides a step by step approach to creating an instance of the Ftp component using Visual Studio .NET.
Creating An Instance Of The Ftp Component In Non-Visual Studio .NET Environments.
Provides a step-by-step approach to creating an instance of the Ftp component using other environments.
Creating A License.licx File
Provides a step-by-step approach to creating a License.licx file to license the FTP for .NET. This topic only applies to applications not written in the Visual Studio .NET environment. If working within the Visual Studio .NET environment, a licenses.licx file will automatically be created. using other environments.

See Also

Ftp Component Usage | Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Creating a Secure FTP Client

Creating a secure FTP client is quite simple. All that needs to occur is the Security property must be set to the type of security/authentication desired. Then simply connect to your secure FTP server, and handle all certificate-related issues in the CertificateReceived or CertificateRequested events.

The Simplest Secure Example: Disabling All Security Checks.

This example demonstrates the simplest possible secure FTP example. In this example, the UseAuthentication property is set to false, "disabling" all security checks (NOTE: This does NOT disable security). This means that even if an invalid certificate is received from the server, it is accepted and SSL communication is established. This has obvious shortcomings, which will be addressed later in the topic.

[Visual Basic]
Private Sub SecureTest()
   ' Set the server & user info
   Ftp1.Server = "myftpserver"
   Ftp1.ServerPort = 21
   Ftp1.Username = "user"
   Ftp1.Password = "pass"

   ' "Disable" security checks
   Ftp1.UseAuthentication = False

   ' Set the desired security/authentication to explicit.
   Ftp1.Security = Dart.PowerTCP.SecureFtp.Security.Explicit

   ' Execute a command (this will cause an SSL connection to be made first
   ' and the data will be sent securely)
   Dim dir As String = Ftp1.GetDirectory()
   Debug.WriteLine("Current directory: " + dir)

   ' Close the connection.
   Ftp1.Close()
End Sub
[C#]
private void SecureTest()
{
   // Set the server & user info
   ftp1.Server = "myftpserver";
   ftp1.ServerPort = 21;
   ftp1.Username = "user";
   ftp1.Password = "pass";

   // "Disable" security checks
   ftp1.UseAuthentication = false;

   // Set the desired security/authentication to explicit.
   ftp1.Security = Dart.PowerTCP.SecureFtp.Security.Explicit;

   // Execute a command (this will cause an SSL connection to be made first
   // and the data will be sent securely)
   string dir = ftp1.GetDirectory();
   Debug.WriteLine("Current directory: " + dir);

   // Close the connection.
   ftp1.Close();
}

A More Advanced Secure Client: Validating certificates.

The example above demonstrates communicating securely but is flawed, mainly because all certificates are automatically accepted. To remedy this, set UseAuthentication = true and handle which certificates are accepted/rejected in the CertificateReceived event.

[Visual Basic]
Private Sub SecureTest()
   ' Set the server & user info
   Ftp1.Server = "myftpserver"
   Ftp1.ServerPort = 21
   Ftp1.Username = "user"
   Ftp1.Password = "pass"

   ' "Enable" certificate authentication (verify any certificate the server sends)
   Ftp1.UseAuthentication = True

   ' Set the desired security/authentication to explicit.
   Ftp1.Security = Dart.PowerTCP.SecureFtp.Security.Explicit

   ' Execute a command (this will cause an SSL connection to be made first
   ' and the data will be sent securely)
   Dim dir As String = Ftp1.GetDirectory()
   Debug.WriteLine("Current directory: " + dir)

   ' Close the connection.
   Ftp1.Close()
End Sub

Private Sub Ftp1_CertificateReceived(ByVal sender As Object, e As Dart.PowerTCP.SecureFtp.CertificateReceivedEventArgs) Handles Ftp1.CertificateReceived
   Dim msg As String = ""

   ' Check to see if the certificate is from a trusted root.
   If Not e.TrustedRoot Then
      msg += "This certificate is not from a trusted root" + vbCrLf
   End If

   ' Check to see if the certificate has a valid date.
   If Not e.ValidDate Then
      msg += "This certificate does not have a valid date" + vbCrLf
   End If

   ' Check to see if the certificate has a valid name.
   If Not e.ValidName Then
      msg += "This certificate does not have a valid name" + vbCrLf
   End If

   If msg <> "" Then
      msg += "Would you like to accept this certificate anyway?"
      If MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) = DialogResult.Yes Then
         ' User wants to accept the invalid cert. Accept it.
         e.Accept = True
      End If
   End If
End Sub
[C#]
private void SecureTest()
{
   // Set the server & user info
   ftp1.Server = "myftpserver";
   ftp1.ServerPort = 21;
   ftp1.Username = "user";
   ftp1.Password = "pass";

   // "Enable" certificate authentication (verify any certificate the server sends)
   ftp1.UseAuthentication = true;

   // Connect to a secure server using explicit SSL
   ftp1.Security = Dart.PowerTCP.SecureFtp.Security.Explicit;

   // Execute a command (this will cause an SSL connection to be made first
   // and the data will be sent securely)
   string dir = ftp1.GetDirectory();
   Debug.WriteLine("Current directory: " + dir);

   // Close the connection.
   ftp1.Close();
}

private void ftp1_CertificateReceived(object sender, Dart.PowerTCP.SecureFtp.CertificateReceivedEventArgs e)
{
   string msg = "";

   // Check to see if the certificate is from a trusted root.
   if(!e.TrustedRoot)
      msg+= "This certificate is not from a trusted root\n";

   // Check to see if the certificate has a valid date.
   if(!e.ValidDate)
      msg+= "This certificate does not have a valid date\n";

   // Check to see if the certificate has a valid name.
   if(!e.ValidName)
      msg+= "This certificate does not have a valid name\n";

   if(msg != "")
   {
      msg += "Would you like to accept this certificate anyway?";
      if(MessageBox.Show(msg, "Invalid Cert Received", MessageBoxButtons.YesNo) == DialogResult.Yes)
      {
         // User wants to accept the invalid cert. Accept it.
         e.Accept = true;
      }
   }
}

See Also

Using Secure FTP for .NET | Secure FTP for .NET Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.


Handling Client Authentication

A secure FTP server may request a certificate from the client, forcing the client to prove it's identity to the server. This process is called client authentication. If the server does request a certificate from the FTP client, the CertificateRequested event will be raised, notifying the user.

Handling Client Authentication Interactively

When writing an interactive application in which a server requests client authentication it is often useful to notify the user and allow them to select the certificate they would like to use for client authentication. The CertificateListForm object is ideal for displaying available certificates to the user. See the topic Using The CertificateListForm Object for more information on using this object.

[Visual Basic]
Private Sub SecureTest()
   ' Set the server & user info
   Ftp1.Server = "myftpserver"
   Ftp1.ServerPort = 21
   Ftp1.Username = "user"
   Ftp1.Password = "pass"

   ' Set the desired security/authentication to explicit.
   Ftp1.Security = Dart.PowerTCP.SecureFtp.Security.Explicit

   ' Execute a command (this will cause an SSL connection to be made first
   ' and the data will be sent securely)
   Dim dir As String = Ftp1.GetDirectory()
   Debug.WriteLine("Current directory: " + dir)

   ' Close the connection.
   Ftp1.Close()
End Sub

Private Sub Ftp1_CertificateRequested(ByVal sender As Object, e As Dart.PowerTCP.SecureFtp.CertificateRequestedEventArgs) Handles Ftp1.CertificateRequested
   ' Create a new instance of CertificateListForm
   Dim certForm as new CertificateListForm(True, True)
   certForm.Text = "The Server Requested A Client Certificate"

   ' Show the CertificateListForm to the user and let them choose a certificate
   If certForm.ShowDialog() = DialogResult.OK Then
      ' Set the Certificate property to the certificate the user selected.
      Ftp1.Certificate = certForm.SelectedCertificate
   Else
      MessageBox.Show("You must select a cert. SSL communication will fail.")
   End If
End Sub
[C#]
private void SecureTest()
{
   // Set the server & user info
   ftp1.Server = "myftpserver";
   ftp1.ServerPort = 21;
   ftp1.Username = "user";
   ftp1.Password = "pass";

   // Connect to a secure server using explicit SSL
   ftp1.Security = Dart.PowerTCP.SecureFtp.Security.Explicit;

   // Execute a command (this will cause an SSL connection to be made first
   // and the data will be sent securely)
   string dir = ftp1.GetDirectory();
   Debug.WriteLine("Current directory: " + dir);

   // Close the connection.
   ftp1.Close();
}

private void ftp1_CertificateRequested(object sender, System.EventArgs e)
{
   // Create a new instance of CertificateListForm
   CertificateListForm certForm = new CertificateListForm(true, true);
   certForm.Text = "The Server Requested A Client Certificate";

   // Show the CertificateListForm to the user and let them choose a certificate
   if(certForm.ShowDialog() == DialogResult.OK)
   {
      // Set the Certificate property to the certificate the user selected.
      ftp1.Certificate = certForm.SelectedCertificate;
   }
   else
   {
      MessageBox.Show("You must select a cert. SSL communication will fail.");
   }
}

Handling Client Authentication When Writing A Scripting Application

If you are writing a scripting application which needs to execute without interactive user input it is often useful to set the Certificate property to a valid certificate before communication with the FTP server. For this purpose the CertificateStore object is ideal. NOTE, in this example the CertificateRequested event will still be raised (if an event handler is present) but it is NOT necessary to take action in this event because the Certificate property will already be properly set.

[Visual Basic]
Private Sub SecureTest()
   ' Set the server & user info
   Ftp1.Server = "myftpserver"
   Ftp1.ServerPort = 21
   Ftp1.Username = "user"
   Ftp1.Password = "pass"

   ' Disable security checks
   Ftp1.UseAuthentication = False

   ' Create a new certificate store object
   Dim store as new CertificateStore()

   ' Set the Certificate property to the first certificate found.
   Ftp1.Certificate = store(0)

   ' Connect to a secure server using explicit SSL
   Ftp1.Security = Dart.PowerTCP.SecureFtp.Security.Explicit

   ' Execute a command (this will cause an SSL connection to be made first)
   Dim dir as String = Ftp1.GetDirectory()
   Debug.WriteLine("Current directory: " + dir)

   ' Close the connection.
   Ftp1.Close()
End Sub
[C#]
private void SecureTest()
{
   // Set the server & user info
   ftp1.Server = "myftpserver";
   ftp1.ServerPort = 21;
   ftp1.Username = "user";
   ftp1.Password = "pass";

   // Disable security checks
   ftp1.UseAuthentication = false;

   // Create a new certificate store object
   CertificateStore store = new CertificateStore();

   // Set the Certificate property to the first certificate found.
   ftp1.Certificate = store[0];

   // Connect to a secure server using explicit SSL
   ftp1.Security = Dart.PowerTCP.SecureFtp.Security.Explicit;

   // Execute a command (this will cause an SSL connection to be made first)
   string dir = ftp1.GetDirectory();
   Debug.WriteLine("Current directory: " + dir);

   // Close the connection.
   ftp1.Close();
}

See Also

Using Secure FTP for .NET | Secure FTP for .NET Reference

Send comments on this topic.

© 2002 Dart Communications. All rights reserved.