lobj_userProperties = lobj_diarynote.UserProperties
ls_oldLastModDate = lobj_userProperties.Find("OldlastModDate").Value
Thursday, November 27, 2008
Accessing and finding outlook item
Dim lobj_contacts As Microsoft.Office.Interop.Outlook.MAPIFolder
Dim lobj_contact As Microsoft.Office.Interop.Outlook.ContactItem
lobj_contacts = gobj_outlook.GetNamespace("MAPI").
GetDefaultFolder(Microsoft.Office.Interop.Outlook.
OlDefaultFolders.olFolderContacts)
Dim ToList As String = message.To
lobj_contact = lobj_contacts.Items.Find("[Email1DisplayName]=""" & ToList & """")
gdebug_writer.append(lobj_contact.Email1Address)
Dim lobj_contact As Microsoft.Office.Interop.Outlook.ContactItem
lobj_contacts = gobj_outlook.GetNamespace("MAPI").
GetDefaultFolder(Microsoft.Office.Interop.Outlook.
OlDefaultFolders.olFolderContacts)
Dim ToList As String = message.To
lobj_contact = lobj_contacts.Items.Find("[Email1DisplayName]=""" & ToList & """")
gdebug_writer.append(lobj_contact.Email1Address)
Wednesday, November 19, 2008
DataGridViewExample
Private m_preceptContacts As New preceptContacts()
Private m_preceptDataSet As New DataSet()
Private m_bsContacts As New Windows.Forms.BindingSource()
Private m_toList As String = ""
Private m_ccList As String = ""
Private m_bccList As String = ""
Private m_OKButtonPushed As Boolean = False
Private Sub SelectpreceptContactForm_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If Not m_OKButtonPushed Then
m_toList = ""
m_ccList = ""
m_bccList = ""
End If
End Sub
Private Sub SelectpreceptContactForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.entityType.SelectedIndex = 1
m_preceptDataSet = m_preceptContacts.GetpreceptContacts(gdb_precept, Me.LastNameTB.Text.Trim(), _
Me.firstNameTB.Text.Trim(), Me.entityType.SelectedItem.ToString.Trim(), _
Me.RoleTB.Text.Trim())
' Dim preceptDataSet As DataSet = preceptContacts.GetpreceptContacts(gdb_precept, "", _
'"", "", "")
Me.dgvOfAddresses.AutoGenerateColumns = False
Me.dgvOfAddresses.SelectionMode = Windows.Forms.DataGridViewSelectionMode.FullRowSelect
m_bsContacts.DataSource = m_preceptDataSet.Tables("Contacts")
Me.dgvOfAddresses.DataSource = m_bsContacts
'Last Name Column
Dim lastNameColumn As New Windows.Forms.DataGridViewTextBoxColumn()
lastNameColumn.Name = "LastName"
lastNameColumn.HeaderText = "Last Name"
lastNameColumn.DataPropertyName = "surname"
Me.dgvOfAddresses.Columns.Add(lastNameColumn)
'First Name Column
Dim firstNameColumn As New Windows.Forms.DataGridViewTextBoxColumn()
firstNameColumn.Name = "firstName"
firstNameColumn.HeaderText = "First Name"
firstNameColumn.DataPropertyName = "firstname"
Me.dgvOfAddresses.Columns.Add(firstNameColumn)
'email column
Dim emailColumn As New Windows.Forms.DataGridViewTextBoxColumn()
emailColumn.Name = "emailColumn"
emailColumn.HeaderText = "Email"
emailColumn.DataPropertyName = "emailaddress"
Me.dgvOfAddresses.Columns.Add(emailColumn)
'entityType
Dim entityTypeColumn As New Windows.Forms.DataGridViewTextBoxColumn()
entityTypeColumn.Name = "entityTypeColumn"
entityTypeColumn.HeaderText = "Contact Type"
entityTypeColumn.DataPropertyName = "ENTITYTYPE"
Me.dgvOfAddresses.Columns.Add(entityTypeColumn)
'jobType
Dim jobTypeColumn As New Windows.Forms.DataGridViewTextBoxColumn()
jobTypeColumn.Name = "jobTypeColumn"
jobTypeColumn.HeaderText = "Job Type"
jobTypeColumn.DataPropertyName = "role"
Me.dgvOfAddresses.Columns.Add(jobTypeColumn)
'ahourphone
Dim phoneahColumn As New Windows.Forms.DataGridViewTextBoxColumn()
phoneahColumn.Name = "phoneahColumn"
phoneahColumn.HeaderText = "After Hours Ph"
phoneahColumn.DataPropertyName = "phoneah"
Me.dgvOfAddresses.Columns.Add(phoneahColumn)
'business phone
Dim phonebhColumn As New Windows.Forms.DataGridViewTextBoxColumn()
phonebhColumn.Name = "phonebhColumn"
phonebhColumn.HeaderText = "Bus Hours Ph"
phonebhColumn.DataPropertyName = "phonebh"
Me.dgvOfAddresses.Columns.Add(phonebhColumn)
'mob phone
Dim phonemobileColumn As New Windows.Forms.DataGridViewTextBoxColumn()
phonemobileColumn.Name = "phonemobileColumn"
phonemobileColumn.HeaderText = "Mob Ph"
phonemobileColumn.DataPropertyName = "phonemobile"
Me.dgvOfAddresses.Columns.Add(phonemobileColumn)
'fprecept
Dim fpreceptColumn As New Windows.Forms.DataGridViewTextBoxColumn()
fpreceptColumn.Name = "fpreceptColumn"
fpreceptColumn.HeaderText = "Fprecept"
fpreceptColumn.DataPropertyName = "fprecept"
Me.dgvOfAddresses.Columns.Add(fpreceptColumn)
End Sub
Private Sub SearchButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchButton.Click
If LastNameTB.Text.Trim() = String.Empty Then
MsgBox("You have to supply at least one letter of the Last Name to perform a search")
Exit Sub
End If
m_preceptDataSet = m_preceptContacts.GetpreceptContacts(gdb_precept, Me.LastNameTB.Text.Trim(), _
Me.firstNameTB.Text.Trim(), Me.entityType.SelectedItem.ToString.Trim(), _
Me.RoleTB.Text.Trim())
m_bsContacts.DataSource = m_preceptDataSet.Tables("Contacts")
'bsContacts.ResetBindings(False)
End Sub
Thursday, November 13, 2008
delegates and async callbacks to do method time outs
WindowsDevCenter.com
oreilly.comSafari Books Online.Conferences.
Sign In/My Account | View Cart
Articles Weblogs Books School Short Cuts Podcasts
advertisement
AddThis Social Bookmark Button
Listen Print Subscribe to Windows Subscribe to Newsletters
Using Delegates Asynchronously
by Richard Blewett
02/24/2003
In the article " Understanding the Nuances of Delegates in C#," by Satya Komatineni, the concept of delegates and their general pattern of usage in C# was introduced. This article takes the subject further and looks at another feature of delegates--the built-in ability to perform tasks asynchronously by handing off work to the system thread pool. To understand exactly how delegates perform their async magic, an understanding of how the system thread pool works is first required. For each process in which it is loaded, the CLR manages a thread pool. This thread pool consists of a queue to which pieces of work are added, and a pool of threads that service the queue (by dequeuing the pieces of work). The thread pool is exposed to the world via the System.Threading.ThreadPool class.
The number of threads in the pool is not fixed but gradually grows and shrinks, according to certain heuristics. Initially at 0, the pool grows as the number of concurrent, outstanding pieces of work grows. As threads stand idle, they may be removed from the pool. The pool is capped at 25 threads and this figure is not alterable from managed code. Applications hosting the CLR can change it via the .NET unmanaged API. For example, the maxWorkerThreads attribute in the processModel element in machine.config specifies the maximum size of the thread pool in the ASP.NET worker process.
Thread pool threads have a number of specific characteristics:
* They are background threads--in other words, they will not prevent your process terminating, should every non-background thread in your process terminate.
* Their priority should not be altered. The thread is "owned" by the thread pool and may be used for a variety of tasks--for example, remoted calls are serviced on thread pool threads. Altering the priority of a thread pool thread will cause other tasks to be bound by the new priority.
* The COM Apartment affinity (exposed as the ApartmentState property of a thread) should not be altered for the same reason as the priority.
* Long-running tasks should not be assigned to the thread pool, as this will decrease the number of available threads with which to service other requests.
* They should not be suspended or aborted. They are a system, not application, resource.
If any of the above characteristics are required, create a new thread using the System.Threading.Thread class. However, the thread pool itself is not the focus of this article; rather, how delegates can be leveraged to have work processed by the thread pool is.
Delegates Under the Covers
So what happens when a delegate type if declared? Consider the following delegate declaration.
Code Example 1
delegate long CalcNthPrimeNumber( int N );
This can be used for invoking methods that calculate a specific prime number (this can be a very lengthy calculation): The C# compiler generates code equivalent to the following:
Code Example 2
class CalcNthPrimeNumber : System.MulticastDelegate
{
// ctor omitted
// Used in synchronous execution
public long Invoke( int N );
// Async execution methods
public IAsyncResult BeginInvoke( int N,
AsyncCallback callback,
object asyncState );
public long EndInvoke( IAsyncResult ar );
}
Invoke is the method that the compiler calls during standard synchronous execution. However, the interesting methods for this discussion are BeginInvoke and EndInvoke. BeginInvoke will always return an IAsyncResult and will always have its last two parameters as an AsyncCallback delegate and a System.Object. EndInvoke will always have as its last parameter an IAsyncResult. The rest of the signatures of these two methods are dependent on the signature of the delegate in question. BeginInvoke always takes any parameters passed by value (unadorned) or reference (ref) before the callback delegate. EndInvoke always has the same return type as the delegate signature, and also has any ref or out parameters before the IAsyncResult.
Invoking Delegates Asynchronously
There are four patterns in async delegate execution: Polling, Waiting for Completion, Completion Notification, and "Fire and Forget". Before explaining the patterns, however, there is one caveat about async delegate execution. You cannot execute a multicast delegate (one that calls more than one client) asynchronously. Each client must be called asynchronously in turn by processing the stored list of clients, the Invocation List. Failing to do this results in an ArgumentException being thrown. Processing the Invocation List turns out to be a far from onerous task--below is example code:
Code Example 3
CalcNthPrimeNumber c;
// Code omitted when numerous clients
// are hooked up to the delegate
if( c != null )
{
foreach( CalcNthPrimeNumber cpn in c.GetInvocationList())
{
// Now call each cpn asynchronously
}
}
Spawning a method onto a worker thread is achieved by calling BeginInvoke on a delegate that wraps the method. This tells the delegate to queue the method invocation onto the Thread Pool. BeginInvoke takes all unadorned and ref parameters, as well as an optional AsyncCallback and System.Object (both of which will be explained later).
Once a method has been given to a worker thread, the thread that instigated the async call carries on with its own work. Given this, how does it find out what the async method returned?
Harvesting Results
Retrieving results is a simple operation; all that is required is a call to EndInvoke. However, there is an issue: if the async method has not completed, EndInvoke will block until it completes. This may be the required behavior--that the caller gets on with other work and then calls EndInvoke when the results are needed. However, what if the caller can usefully get on with work until the async call has completed? Calling EndInvoke before the call is complete means the thread is blocked where it could still be carrying out useful work. Also, what if the caller wanted to be able to timeout the wait after a specified period, that the background task had been too lengthy? EndInvoke blocks until the async method completes--an indeterminate point in time.
We saw in Code Example 2 that BeginInvoke returns an IAsyncResult reference. The semantics of EndInvoke require that it must be passed an IAsyncResult reference that matches that returned by the corresponding BeginInvoke. This is because the asynchronous call is represented by a call object that the IAsyncResult references.
Polling
To find out whether a call has completed, we can talk to the call object representing the async call. Let's look at the definition of IAsyncResult:
Code Example 4
public interface IAsyncResult
{
object AsyncState{ get; }
WaitHandle AsyncWaitHandle { get; }
bool CompletedSynchronously { get; }
bool IsCompleted { get; }
}
As can be seen, one of the members of IAsyncResult has been highlighted. IsCompleted returns true when the asynchronous is complete; until that time it returns false. IsCompleted can, therefore, be used to assess whether the long-running calculation is finished. In Code Sample 5, the 672nd prime number is being requested and the calculation will be performed on a thread pool thread. The main thread then polls until the calculation is complete.
Code Example 5
void SpawnPrimeNumberCalc(int N)
{
CalcNthPrimeNumber cpn =
new CalcNthPrimeNumber(CalculatePi);
IAsyncResult ar = cpn.BeginInvoke( 672,
null,
null );
// Do some stuff
while( !ar.IsCompleted )
{
// Do some stuff
}
// we now know that the call is
// complete as IsCompleted has
// returned true
long primeNumber = cpn.EndInvoke(ar);
}
void CalculatePi(int n)
{
// calculate the prime number specified by n
}
Waiting with Timeout
As stated before, EndInvoke is a blocking operation. The calling thread will not continue until the async call has completed. However, what if instead of calculating the Nth prime number locally, the target method were to invoke a web service to perform the calculation? This could involve a network hop (which could have timeouts in the order of minutes, in the case of network failure). It may be preferable to be able to enforce a more user-friendly timeout, say, twenty seconds. Through the use of timers and IAsyncResult.IsCompleted this could be achieved, but it is not necessarily the most efficient way of doing it. Let's have another look at IAsyncResult:
Code Example 6
public interface IAsyncResult
{
object AsyncState{ get; }
WaitHandle AsyncWaitHandle { get; }
bool CompletedSynchronously { get; }
bool IsCompleted { get; }
}
This time another of the properties of IAsyncResult has been highlighted: AsyncWaitHandle. This property returns a WaitHandle--an object that can be waited on using the WaitHandle.WaitOne method, which takes a timeout as a parameter. It is, therefore, possible to spawn the async call on to another thread and then wait for it to complete--but then timeout the call if it carries on too long. The code in Code Sample 7 demonstrates this pattern:
Code Example 7
void SpawnPrimeNumberCalc(int N)
{
CalcNthPrimeNumber cpn = new CalcNthPrimeNumber(CalculatePi);
IAsyncResult ar = cpn.BeginInvoke( 672, null, null );
// Do some stuff
if( ar.AsyncWaitHandle.WaitOne( 20000, true ))
{
long primeNumber = cpn.EndInvoke(ar);
Console.WriteLine( "672nd Prime Number is: {0}", primeNumber );
}
else
{
Console.WriteLine( "Timed out calculating prime number");
}
}
void CalculatePi(int n)
{
// calculate the prime number specified by using
// a web service
}
The highlighted code waits for 20 seconds for the method to return; if it doesn't return in that time, a message to that effect is printed out to the console window. The final facility allows for the calling thread to be completed disengaged from collecting the values returned from an async call. Instead, we can request to be notified when the call completes.
Pages: 1, 2
Next Pagearrow
Tagged Articles
Be the first to post this article to del.icio.us
Sponsored Resources
* Inside Lightroom
Related to this Article
Introducing Silverlight 1.1 Introducing Silverlight 1.1
by Todd Anglin
October 2007
$9.99 USD
AutoIt v3: Your Quick Guide AutoIt v3: Your Quick Guide
by Andy Flesner
September 2007
$7.99 USD
Advertisement
O'Reilly Media
© 2008, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners. About O'Reilly
Privacy Policy
Contacts
Customer Service
Authors
Press Room
Jobs
User Groups
Academic Solutions
Newsletters
Writing for O'Reilly
RSS Feeds
Other O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
O'Reilly FYI
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com
Sponsored Sites
Inside Aperture
Inside Lightroom
Inside Port 25
InsideRIA
java.net
Wednesday, November 12, 2008
Get the root of xmlDoc
Dim Header As XmlNode = xmlDoc.FirstChild
Dim xElmntRoot As XmlElement = Header.NextSibling
Dim xElmntRoot As XmlElement = Header.NextSibling
Tuesday, November 11, 2008
Extract text from word doco
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.InitialDirectory = "c:\"
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*|pdf files (*.pdf)|*.pdf"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Me.TextBox1.Text = OpenFileDialog1.FileName
'myStream = OpenFileDialog1.OpenFile()
'If Not (myStream Is Nothing) Then
' ' Insert code to read the stream here.
' myStream.Close()
'End If
End If
Dim objWord As Microsoft.Office.Interop.Word.ApplicationClass
Dim strText As String
objWord = New Microsoft.Office.Interop.Word.Application()
With objWord
.Visible = False
.Documents.Open( _
Me.OpenFileDialog1.FileName, _
, _
True _
)
.WordBasic.EditSelectAll()
.WordBasic.SetDocumentVar( _
"MyVar", _
.ActiveDocument.ActiveWindow.Selection.Text _
)
strText = .WordBasic.GetDocumentVar("MyVar")
'TextBox1.Text = strText
TextBox1.Text = _
InsertNewLineChars(Strings.Left(strText, Len(strText) - 1))
.Documents.Close(0)
.Quit()
End With
End Sub
Private Function InsertNewLineChars( _
ByVal strText As String _
) As String
Dim pos As Integer, l As Integer
pos = 1
Do While pos < Len(strText)
l = Strings.InStr(pos, strText, vbCr)
If l = 0 Then Exit Do
strText = _
Strings.Left(strText, l - 1) & vbCrLf & _
Mid(strText, l + 1)
pos = l + 2
Loop
Return strText
End Function
End Class
strip text from pdf
Reference IKVM.GNU.Classpath
IKVM.Runtime
PDFBox-0.7.3
from pdfbox
IKVM.Runtime
PDFBox-0.7.3
from pdfbox
Imports System.io
Imports org.pdfbox.pdmodel
Imports org.pdfbox.util
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Dim myStream As Stream
OpenFileDialog1.InitialDirectory = "c:\"
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*|pdf files (*.pdf)|*.pdf"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Me.TextBox1.Text = OpenFileDialog1.FileName
'myStream = OpenFileDialog1.OpenFile()
'If Not (myStream Is Nothing) Then
' ' Insert code to read the stream here.
' myStream.Close()
'End If
End If
Dim doc As PDDocument = PDDocument.load(OpenFileDialog1.FileName)
Dim stripper As New org.pdfbox.util.PDFTextStripper()
Me.TextBox1.Text = stripper.getText(doc)
' PDDocument doc = PDDocument.load(filename);
'PDFTextStripper stripper = new PDFTextStripper();
'return stripper.getText(doc);
End Sub
End Class
definitive ftp example
FtpSample.vb
--------------------------------------------------------------------------------
'---------------------------------------------------------------------
' This file is part of the Microsoft .NET Framework SDK Code Samples.
'
' Copyright (C) Microsoft Corporation. All rights reserved.
'
'This source code is intended only as a supplement to Microsoft
'Development Tools and/or on-line documentation. See these other
'materials for detailed information regarding Microsoft code samples.
'
'THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
'KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
'IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
'PARTICULAR PURPOSE.
'---------------------------------------------------------------------
Imports System.Net
Imports System.IO
Module FtpSample
Sub Main(ByVal args() As String)
If args.Length = 0 OrElse args(0).Equals("/?") Then
DisplayUsage()
ElseIf args.Length = 1 Then
Download(args(0))
ElseIf args.Length = 2 Then
If args(0).Equals("/list") Then
List(args(1))
Else
Upload(args(0), args(1))
End If
Else
Console.WriteLine("Unrecognized argument.")
End If
End Sub
Private Sub DisplayUsage()
Console.WriteLine("USAGE:")
Console.WriteLine(" FtpSample [/? || ")
Console.WriteLine("| /list ]")
Console.WriteLine()
Console.WriteLine("where")
Console.WriteLine(" FTP download URL URL of a file to download from an FTP server.")
Console.WriteLine(" FTP upload URL Location on a FTP server to upload a file to.")
Console.WriteLine(" FTP list URL Location on a FTP server to list the contents of.")
Console.WriteLine(" local file A local file to upload to an FTP server.")
Console.WriteLine()
Console.WriteLine(" Options:")
Console.WriteLine(" /? Display this help message.")
Console.WriteLine(" /list Specifies the list command.")
Console.WriteLine()
Console.WriteLine("EXAMPLES:")
Console.WriteLine(" Download a file FtpSample ftp://myserver/download.txt")
Console.WriteLine(" Upload a file FtpSample upload.txt ftp://myserver/upload.txt")
End Sub
Private Sub Download(ByVal downloadUrl As String)
Dim responseStream As Stream = Nothing
Dim fileStream As FileStream = Nothing
Dim reader As StreamReader = Nothing
Try
Dim downloadRequest As FtpWebRequest = _
WebRequest.Create(downloadUrl)
Dim downloadResponse As FtpWebResponse = _
downloadRequest.GetResponse()
responseStream = downloadResponse.GetResponseStream()
Dim fileName As String = _
Path.GetFileName(downloadRequest.RequestUri.AbsolutePath)
If fileName.Length = 0 Then
reader = New StreamReader(responseStream)
Console.WriteLine(reader.ReadToEnd())
Else
fileStream = File.Create(fileName)
Dim buffer(1024) As Byte
Dim bytesRead As Integer
While True
bytesRead = responseStream.Read(buffer, 0, buffer.Length)
If bytesRead = 0 Then
Exit While
End If
fileStream.Write(buffer, 0, bytesRead)
End While
End If
Console.WriteLine("Download complete.")
Catch ex As UriFormatException
Console.WriteLine(ex.Message)
Catch ex As WebException
Console.WriteLine(ex.Message)
Catch ex As IOException
Console.WriteLine(ex.Message)
Finally
If reader IsNot Nothing Then
reader.Close()
ElseIf responseStream IsNot Nothing Then
responseStream.Close()
End If
If fileStream IsNot Nothing Then
fileStream.Close()
End If
End Try
End Sub
Private Sub Upload(ByVal fileName As String, ByVal uploadUrl As String)
Dim requestStream As Stream = Nothing
Dim fileStream As FileStream = Nothing
Dim uploadResponse As FtpWebResponse = Nothing
Try
Dim uploadRequest As FtpWebRequest = WebRequest.Create(uploadUrl)
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile
' UploadFile is not supported through an Http proxy
' so we disable the proxy for this request.
uploadRequest.Proxy = Nothing
requestStream = uploadRequest.GetRequestStream()
fileStream = File.Open(fileName, FileMode.Open)
Dim buffer(1024) As Byte
Dim bytesRead As Integer
While True
bytesRead = fileStream.Read(buffer, 0, buffer.Length)
If bytesRead = 0 Then
Exit While
End If
requestStream.Write(buffer, 0, bytesRead)
End While
' The request stream must be closed before getting the response.
requestStream.Close()
uploadResponse = uploadRequest.GetResponse()
Console.WriteLine("Upload complete.")
Catch ex As UriFormatException
Console.WriteLine(ex.Message)
Catch ex As IOException
Console.WriteLine(ex.Message)
Catch ex As WebException
Console.WriteLine(ex.Message)
Finally
If uploadResponse IsNot Nothing Then
uploadResponse.Close()
End If
If fileStream IsNot Nothing Then
fileStream.Close()
End If
If requestStream IsNot Nothing Then
requestStream.Close()
End If
End Try
End Sub
Private Sub List(ByVal listUrl As String)
Dim reader As StreamReader = Nothing
Try
Dim listRequest As FtpWebRequest = WebRequest.Create(listUrl)
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails
Dim listResponse As FtpWebResponse = listRequest.GetResponse()
reader = New StreamReader(listResponse.GetResponseStream())
Console.WriteLine(reader.ReadToEnd())
Console.WriteLine("List complete.")
Catch ex As UriFormatException
Console.WriteLine(ex.Message)
Catch ex As WebException
Console.WriteLine(ex.Message)
Finally
If reader IsNot Nothing Then
reader.Close()
End If
End Try
End Sub
End Module
--------------------------------------------------------------------------------
Sunday, November 9, 2008
caspol
caspol.exe is located in the following directory:
LocalDrive:\Windows\Microsoft.Net\Framework\v2.0.50727\
Use the following command to put an assembly to the trust:
caspol.exe -u -addgroup All_Code -url "\*" FullTrust -name "Your Assembly Name"
c:\Windows\Microsoft.Net\Framework\v2.0.50727\ -addgroup All_Code -url "\*" FullTrust -name assemblyname
LocalDrive:\Windows\Microsoft.Net\Framework\v2.0.50727\
Use the following command to put an assembly to the trust:
caspol.exe -u -addgroup All_Code -url "\*" FullTrust -name "Your Assembly Name"
c:\Windows\Microsoft.Net\Framework\v2.0.50727\ -addgroup All_Code -url "\*" FullTrust -name assemblyname
Monday, November 3, 2008
File Reader to examine strings
Imports System.IO
Module Module1
Sub Main(ByVal args() As String)
Try
Dim fs As New FileStream(args(0), FileMode.Open)
Dim br As New BinaryReader(fs)
Dim b As Integer = br.ReadByte()
While True
Console.WriteLine(b.ToString & " " & Char.ConvertFromUtf32(b))
b = br.ReadByte()
End While
Catch ex As Exception
Console.WriteLine(ex.ToString())
End Try
Console.ReadKey()
End Sub
End Module
Thursday, October 16, 2008
ftp using ftpwebrequest
.NET Framework Class Library
FtpWebRequest Class
See Also Example Members
Collapse All Expand All Language Filter: All Language Filter: Multiple Language Filter: Visual Basic Language Filter: C# Language Filter: C++ Language Filter: J# Language Filter: JScript
Visual Basic (Declaration)
Visual Basic (Usage)
C#
C++
J#
JScript
Note: This class is new in the .NET Framework version 2.0.
Implements a File Transfer Protocol (FTP) client.
Namespace: System.Net
Assembly: System (in system.dll)
Syntax
Visual Basic (Declaration)
Public NotInheritable Class FtpWebRequest
Inherits WebRequest
Visual Basic (Usage)
Dim instance As FtpWebRequest
C#
public sealed class FtpWebRequest : WebRequest
C++
public ref class FtpWebRequest sealed : public WebRequest
J#
public final class FtpWebRequest extends WebRequest
JScript
public final class FtpWebRequest extends WebRequest
Remarks
To obtain an instance of FtpWebRequest, use the Create method. You can also use the WebClient class to upload and download information from an FTP server. Using either of these approaches, when you specify a network resource that uses the FTP scheme (for example, "ftp://contoso.com") the FtpWebRequest class provides the ability to programmatically interact with FTP servers.
The URI may be relative or absolute. If the URI is of the form "ftp://contoso.com/%2fpath" (%2f is an escaped '/'), then the URI is absolute, and the current directory is /path. If, however, the URI is of the form "ftp://contoso.com/path", first the .NET Framework logs into the FTP server (using the user name and password set by the Credentials property), then the current directory is set to/path.
You must have a valid user name and password for the server or the server must allow anonymous logon. You can specify the credentials used to connect to the server by setting the Credentials property or you can include them in the UserInfo portion of the URI passed to the Create method. If you include UserInfo information in the URI, the Credentials property is set to a new network credential with the specified user name and password information.
Caution
Unless the EnableSsl property is true, all data and commands, including your user name and password information, are sent to the server in clear text. Anyone monitoring network traffic can view your credentials and use them to connect to the server. If you are connecting to an FTP server that requires credentials and supports Secure Sockets Layer (SSL), you should set EnableSsl to true.
You must have WebPermission to access the FTP resource; otherwise, a SecurityException exception is thrown.
Specify the FTP command to send to the server by setting the Method property to a value defined in the WebRequestMethods.Ftp structure. To transmit text data, change the UseBinary property from its default value (true) to false. For details and restrictions, see Method.
When using an FtpWebRequest object to upload a file to a server, you must write the file content to the request stream obtained by calling the GetRequestStream method or its asynchronous counterparts, the BeginGetRequestStream and EndGetRequestStream methods. You must write to the stream and close the stream before sending the request.
Requests are sent to the server by calling the GetResponse method or its asynchronous counterparts, the BeginGetResponse and EndGetResponse methods. When the requested operation completes, an FtpWebResponse object is returned. The FtpWebResponse object provides the status of the operation and any data downloaded from the server.
You can set a time-out value for reading or writing to the server by using the ReadWriteTimeout property. If the time-out period is exceeded, the calling method throws a WebException with WebExceptionStatus set to Timeout.
When downloading a file from an FTP server, if the command was successful, the contents of the requested file are available in the response object's stream. You can access this stream by calling the GetResponseStream method. For more information, see FtpWebResponse.
If the Proxy property is set, either directly or in a configuration file, communications with the FTP server are made through the specified proxy. If the specified proxy is an HTTP proxy, only the DownloadFile, ListDirectory, and ListDirectoryDetails commands are supported.
Only downloaded binary content is cached; that is, content received using the DownloadFile command with the UseBinary property set to true.
Multiple FtpWebRequests reuse existing connections, if possible.
For more information about the FTP protocol, see RFC 959, "File Transfer Protocol," available at http://www.rfc-editor.org/.
Example
The following code example demonstrates deleting a file from an FTP server.
C# Copy Code
public static bool DeleteFileOnServer(Uri serverUri)
{
// The serverUri parameter should use the ftp:// scheme.
// It contains the name of the server file that is to be deleted.
// Example: ftp://contoso.com/someFile.txt.
//
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
Console.WriteLine("Delete status: {0}",response.StatusDescription);
response.Close();
return true;
}
The following code example demonstrates downloading a file from an FTP server by using the WebClient class.
C# Copy Code
public static bool DisplayFileFromServer(Uri serverUri)
{
// The serverUri parameter should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
WebClient request = new WebClient();
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
try
{
byte [] newFileData = request.DownloadData (serverUri.ToString());
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
Console.WriteLine(fileString);
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
return true;
}
The following code example demonstrates using asynchronous operations to upload a file to an FTP server.
C# Copy Code
using System;
using System.Net;
using System.Threading;
using System.IO;
namespace Examples.System.Net
{
public class FtpState
{
private ManualResetEvent wait;
private FtpWebRequest request;
private string fileName;
private Exception operationException = null;
string status;
public FtpState()
{
wait = new ManualResetEvent(false);
}
public ManualResetEvent OperationComplete
{
get {return wait;}
}
public FtpWebRequest Request
{
get {return request;}
set {request = value;}
}
public string FileName
{
get {return fileName;}
set {fileName = value;}
}
public Exception OperationException
{
get {return operationException;}
set {operationException = value;}
}
public string StatusDescription
{
get {return status;}
set {status = value;}
}
}
public class AsynchronousFtpUpLoader
{
// Command line arguments are two strings:
// 1. The url that is the name of the file being uploaded to the server.
// 2. The name of the file on the local machine.
//
public static void Main(string[] args)
{
// Create a Uri instance with the specified URI string.
// If the URI is not correctly formed, the Uri constructor
// will throw an exception.
ManualResetEvent waitObject;
Uri target = new Uri (args[0]);
string fileName = args[1];
FtpState state = new FtpState();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example uses anonymous logon.
// The request is anonymous by default; the credential does not have to be specified.
// The example specifies the credential only to
// control how actions are logged on the server.
request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
// Store the request in the object that we pass into the
// asynchronous operations.
state.Request = request;
state.FileName = fileName;
// Get the event to wait on.
waitObject = state.OperationComplete;
// Asynchronously get the stream for the file contents.
request.BeginGetRequestStream(
new AsyncCallback (EndGetStreamCallback),
state
);
// Block the current thread until all operations are complete.
waitObject.WaitOne();
// The operations either completed or threw an exception.
if (state.OperationException != null)
{
throw state.OperationException;
}
else
{
Console.WriteLine("The operation completed - {0}", state.StatusDescription);
}
}
private static void EndGetStreamCallback(IAsyncResult ar)
{
FtpState state = (FtpState) ar.AsyncState;
Stream requestStream = null;
// End the asynchronous call to get the request stream.
try
{
requestStream = state.Request.EndGetRequestStream(ar);
// Copy the file contents to the request stream.
const int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];
int count = 0;
int readBytes = 0;
FileStream stream = File.OpenRead(state.FileName);
do
{
readBytes = stream.Read(buffer, 0, bufferLength);
requestStream.Write(buffer, 0, readBytes);
count += readBytes;
}
while (readBytes != 0);
Console.WriteLine ("Writing {0} bytes to the stream.", count);
// IMPORTANT: Close the request stream before sending the request.
requestStream.Close();
// Asynchronously get the response to the upload request.
state.Request.BeginGetResponse(
new AsyncCallback (EndGetResponseCallback),
state
);
}
// Return exceptions to the main application thread.
catch (Exception e)
{
Console.WriteLine("Could not get the request stream.");
state.OperationException = e;
state.OperationComplete.Set();
return;
}
}
// The EndGetResponseCallback method
// completes a call to BeginGetResponse.
private static void EndGetResponseCallback(IAsyncResult ar)
{
FtpState state = (FtpState) ar.AsyncState;
FtpWebResponse response = null;
try
{
response = (FtpWebResponse) state.Request.EndGetResponse(ar);
response.Close();
state.StatusDescription = response.StatusDescription;
// Signal the main application thread that
// the operation is complete.
state.OperationComplete.Set();
}
// Return exceptions to the main application thread.
catch (Exception e)
{
Console.WriteLine ("Error getting response.");
state.OperationException = e;
state.OperationComplete.Set();
}
}
}
}
C++ Copy Code
#using
using namespace System;
using namespace System::Net;
using namespace System::Threading;
using namespace System::IO;
public ref class FtpState
{
private:
ManualResetEvent^ wait;
FtpWebRequest^ request;
String^ fileName;
Exception^ operationException;
String^ status;
public:
FtpState()
{
wait = gcnew ManualResetEvent( false );
}
property ManualResetEvent^ OperationComplete
{
ManualResetEvent^ get()
{
return wait;
}
}
property FtpWebRequest^ Request
{
FtpWebRequest^ get()
{
return request;
}
void set( FtpWebRequest^ value )
{
request = value;
}
}
property String^ FileName
{
String^ get()
{
return fileName;
}
void set( String^ value )
{
fileName = value;
}
}
property Exception^ OperationException
{
Exception^ get()
{
return operationException;
}
void set( Exception^ value )
{
operationException = value;
}
}
property String^ StatusDescription
{
String^ get()
{
return status;
}
void set( String^ value )
{
status = value;
}
}
};
public ref class AsynchronousFtpUpLoader
{
public:
// Command line arguments are two strings:
// 1. The url that is the name of the file being uploaded to the server.
// 2. The name of the file on the local machine.
//
static void Main()
{
array^args = Environment::GetCommandLineArgs();
// Create a Uri instance with the specified URI string.
// If the URI is not correctly formed, the Uri constructor
// will throw an exception.
ManualResetEvent^ waitObject;
Uri^ target = gcnew Uri( args[ 1 ] );
String^ fileName = args[ 2 ];
FtpState^ state = gcnew FtpState;
FtpWebRequest ^ request = dynamic_cast(WebRequest::Create( target ));
request->Method = WebRequestMethods::Ftp::UploadFile;
// This example uses anonymous logon.
// The request is anonymous by default; the credential does not have to be specified.
// The example specifies the credential only to
// control how actions are logged on the server.
request->Credentials = gcnew NetworkCredential( "anonymous","janeDoe@contoso.com" );
// Store the request in the object that we pass into the
// asynchronous operations.
state->Request = request;
state->FileName = fileName;
// Get the event to wait on.
waitObject = state->OperationComplete;
// Asynchronously get the stream for the file contents.
request->BeginGetRequestStream( gcnew AsyncCallback( EndGetStreamCallback ), state );
// Block the current thread until all operations are complete.
waitObject->WaitOne();
// The operations either completed or threw an exception.
if ( state->OperationException != nullptr )
{
throw state->OperationException;
}
else
{
Console::WriteLine( "The operation completed - {0}", state->StatusDescription );
}
}
private:
static void EndGetStreamCallback( IAsyncResult^ ar )
{
FtpState^ state = dynamic_cast(ar->AsyncState);
Stream^ requestStream = nullptr;
// End the asynchronous call to get the request stream.
try
{
requestStream = state->Request->EndGetRequestStream( ar );
// Copy the file contents to the request stream.
const int bufferLength = 2048;
array^buffer = gcnew array (bufferLength);
int count = 0;
int readBytes = 0;
FileStream^ stream = File::OpenRead( state->FileName );
do
{
readBytes = stream->Read( buffer, 0, bufferLength );
requestStream->Write( buffer, 0, bufferLength );
count += readBytes;
}
while ( readBytes != 0 );
Console::WriteLine( "Writing {0} bytes to the stream.", count );
// IMPORTANT: Close the request stream before sending the request.
requestStream->Close();
// Asynchronously get the response to the upload request.
state->Request->BeginGetResponse( gcnew AsyncCallback( EndGetResponseCallback ), state );
}
// Return exceptions to the main application thread.
catch ( Exception^ e )
{
Console::WriteLine( "Could not get the request stream." );
state->OperationException = e;
state->OperationComplete->Set();
return;
}
}
// The EndGetResponseCallback method
// completes a call to BeginGetResponse.
static void EndGetResponseCallback( IAsyncResult^ ar )
{
FtpState^ state = dynamic_cast(ar->AsyncState);
FtpWebResponse ^ response = nullptr;
try
{
response = dynamic_cast(state->Request->EndGetResponse( ar ));
response->Close();
state->StatusDescription = response->StatusDescription;
// Signal the main application thread that
// the operation is complete.
state->OperationComplete->Set();
}
// Return exceptions to the main application thread.
catch ( Exception^ e )
{
Console::WriteLine( "Error getting response." );
state->OperationException = e;
state->OperationComplete->Set();
}
}
};
int main()
{
AsynchronousFtpUpLoader::Main();
}
.NET Framework Security
WebPermission for accessing the resource referenced by this request. Associated enumeration: Connect.
Inheritance Hierarchy
System.Object
System.MarshalByRefObject
System.Net.WebRequest
System.Net.FtpWebRequest
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Platforms
Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.
Version Information
.NET Framework
Supported in: 2.0
See Also
Reference
FtpWebRequest Members
System.Net Namespace
FtpWebResponse
FtpStatusCode
WebRequestMethods.Ftp
WebRequest
WebResponse
WebClient
Send comments about this topic to Microsoft.
FTP jobs
Knowledge Base
How to access a File Transfer Protocol site by using Visual Basic .NETPSS ID Number: 832679
Article Last Modified on 1/20/2004
--------------------------------------------------------------------------------
The information in this article applies to:
Microsoft Visual Basic .NET (2003)
Microsoft Visual Basic .NET (2002)
--------------------------------------------------------------------------------
IN THIS TASK
SUMMARY
Requirements
Add references, and declare class variables
Define class constructors
Set public properties
Use the public sub-procedures and the public functions
Use the private sub-procedures and the private functions
Connect to the FTP site and then perform operations on the FTP site
Verify the FTP application
REFERENCES
SUMMARY
This article describes how to perform the File Transfer Protocol (FTP) operation by using Microsoft Visual Basic .NET. The code samples in this article perform the following FTP commands:
Upload a file to the FTP site
Download a file from the FTP site
Create a folder on the FTP site
Remove a folder from the FTP site
Change a working folder on the FTP site
Remove a file from the FTP site
Rename a file on the FTP site
back to the top
Requirements
This article assumes that you are familiar with the following topics:
Programming with Microsoft Visual Basic .NET
FTP commands
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
Microsoft Windows 2000, Microsoft Windows XP, or Microsoft Windows Server 2003
Visual Basic .NET
back to the top
Add references, and declare class variables
You can add references and declare class variables to store a remote host name, to store a remote password, and to set the size of the packet that is used to read and to write data to an FTP server.
Review the following code sample. The "Verify the FTP application" section shows you where to put this code sample and how to make this code sample functional. The "Verify the FTP application" section contains the complete code listing for all the code samples in this article.
Imports System
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Net.Sockets
Public Class clsFTP
#Region "Class Variable Declarations"
Private m_sRemoteHost, m_sRemotePath, m_sRemoteUser As String
Private m_sRemotePassword, m_sMess As String
Private m_iRemotePort, m_iBytes As Int32
Private m_objClientSocket As Socket
Private m_iRetValue As Int32
Private m_bLoggedIn As Boolean
Private m_sMes, m_sReply As String
'Set the size of the packet that is used to read and to write data to the FTP server
'to the following specified size.
Public Const BLOCK_SIZE = 512
Private m_aBuffer(BLOCK_SIZE) As Byte
Private ASCII As Encoding = Encoding.ASCII
Public flag_bool As Boolean
'General variable declaration
Private m_sMessageString As String
#End Region
back to the top
Define class constructors
You must define the main class constructor with default values. You must define the parameterized constructor that accepts values when the constructor is called.
Review the following code sample. The "Verify the FTP application" section shows you where to put this code sample and how to make this code sample functional. The "Verify the FTP application" section contains the complete code listing for all the code samples in this article.
#Region "Class Constructors"
' Main class constructor
Public Sub New()
m_sRemoteHost = "microsoft"
m_sRemotePath = "."
m_sRemoteUser = "anonymous"
m_sRemotePassword = ""
m_sMessageString = ""
m_iRemotePort = 21
m_bLoggedIn = False
End Sub
' Parameterized constructor
Public Sub New(ByVal sRemoteHost As String, _
ByVal sRemotePath As String, _
ByVal sRemoteUser As String, _
ByVal sRemotePassword As String, _
ByVal iRemotePort As Int32)
m_sRemoteHost = sRemoteHost
m_sRemotePath = sRemotePath
m_sRemoteUser = sRemoteUser
m_sRemotePassword = sRemotePassword
m_sMessageString = ""
m_iRemotePort = 21
m_bLoggedIn = False
End Sub
#End Region
back to the top
Set public properties
You must Set or Get the remote FTP server, the remote port, the remote path, the remote password, and the remote user.
Review the following code sample. The "Verify the FTP application" section shows you where to put this code sample and how to make this code sample functional. The "Verify the FTP application" section contains the complete code listing for all the code samples in this article.
#Region "Public Properties"
'Set or Get the name of the FTP server that you want to connect.
Public Property RemoteHostFTPServer() As String
'Get the name of the FTP server.
Get
Return m_sRemoteHost
End Get
'Set the name of the FTP server.
Set(ByVal Value As String)
m_sRemoteHost = Value
End Set
End Property
'Set or Get the FTP Port Number of the FTP server that you want to connect.
Public Property RemotePort() As Int32
'Get the FTP Port Number.
Get
Return m_iRemotePort
End Get
'Set the FTP Port Number.
Set(ByVal Value As Int32)
m_iRemotePort = Value
End Set
End Property
'Set or Get the remote path of the FTP server that you want to connect.
Public Property RemotePath() As String
'Get the remote path.
Get
Return m_sRemotePath
End Get
'Set the remote path.
Set(ByVal Value As String)
m_sRemotePath = Value
End Set
End Property
'Set or Get the remote password of the FTP server that you want to connect.
Public Property RemotePassword() As String
Get
Return m_sRemotePassword
End Get
Set(ByVal Value As String)
m_sRemotePassword = Value
End Set
End Property
'Set or Get the remote user of the FTP server that you want to connect.
Public Property RemoteUser() As String
Get
Return m_sRemoteUser
End Get
Set(ByVal Value As String)
m_sRemoteUser = Value
End Set
End Property
'Set the class MessageString.
Public Property MessageString() As String
Get
Return m_sMessageString
End Get
Set(ByVal Value As String)
m_sMessageString = Value
End Set
End Property
#End Region
back to the top
Use the public sub-procedures and the public functions
The public functions and the public procedures give details about file upload, file download, folder creation, folder removal, change folder, file removal, file rename, set remote username, and set remote password.
Review the following code sample. The "Verify the FTP application" section shows you where to put this code sample and how to make this code sample functional. The "Verify the FTP application" section contains the complete code listing for all the code samples in this article.
#Region "Public Subs and Functions"
'Return a list of files in a string() array from the file system.
Public Function GetFileList(ByVal sMask As String) As String()
Dim cSocket As Socket
Dim bytes As Int32
Dim seperator As Char = ControlChars.Lf
Dim mess() As String
m_sMes = ""
'Check if you are logged on to the FTP server.
If (Not (m_bLoggedIn)) Then
Login()
End If
cSocket = CreateDataSocket()
'Send an FTP command,
SendCommand("NLST " & sMask)
If (Not (m_iRetValue = 150 Or m_iRetValue = 125)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
m_sMes = ""
Do While (True)
m_aBuffer.Clear(m_aBuffer, 0, m_aBuffer.Length)
bytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0)
m_sMes += ASCII.GetString(m_aBuffer, 0, bytes)
If (bytes < m_aBuffer.Length) Then
Exit Do
End If
Loop
mess = m_sMes.Split(seperator)
cSocket.Close()
ReadReply()
If (m_iRetValue <> 226) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
Return mess
End Function
' Get the size of the file on the FTP server.
Public Function GetFileSize(ByVal sFileName As String) As Long
Dim size As Long
If (Not (m_bLoggedIn)) Then
Login()
End If
'Send an FTP command.
SendCommand("SIZE " & sFileName)
size = 0
If (m_iRetValue = 213) Then
size = Int64.Parse(m_sReply.Substring(4))
Else
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
Return size
End Function
'Log on to the FTP server.
Public Function Login() As Boolean
m_objClientSocket = _
New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim ep As New IPEndPoint(Dns.Resolve(m_sRemoteHost).AddressList(0), m_iRemotePort)
Try
m_objClientSocket.Connect(ep)
Catch ex As Exception
MessageString = m_sReply
Throw New IOException("Cannot connect to remote server")
End Try
ReadReply()
If (m_iRetValue <> 220) Then
CloseConnection()
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
'Send an FTP command to send a user logon ID to the server.
SendCommand("USER " & m_sRemoteUser)
If (Not (m_iRetValue = 331 Or m_iRetValue = 230)) Then
Cleanup()
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
If (m_iRetValue <> 230) Then
'Send an FTP command to send a user logon password to the server.
SendCommand("PASS " & m_sRemotePassword)
If (Not (m_iRetValue = 230 Or m_iRetValue = 202)) Then
Cleanup()
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
End If
m_bLoggedIn = True
'Call the ChangeDirectory user-defined function to change the folder to the
'remote FTP folder that is mapped.
ChangeDirectory(m_sRemotePath)
'Return the final result.
Return m_bLoggedIn
End Function
'If the value of mode is true, set the binary mode for downloads. Otherwise, set ASCII mode.
Public Sub SetBinaryMode(ByVal bMode As Boolean)
If (bMode) Then
'Send the FTP command to set the binary mode.
'(TYPE is an FTP command that is used to specify representation type.)
SendCommand("TYPE I")
Else
'Send the FTP command to set ASCII mode.
'(TYPE is a FTP command that is used to specify representation type.)
SendCommand("TYPE A")
End If
If (m_iRetValue <> 200) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
End Sub
' Download a file to the local folder of the assembly, and keep the same file name.
Public Sub DownloadFile(ByVal sFileName As String)
DownloadFile(sFileName, "", False)
End Sub
' Download a remote file to the local folder of the assembly, and keep the same file name.
Public Sub DownloadFile(ByVal sFileName As String, _
ByVal bResume As Boolean)
DownloadFile(sFileName, "", bResume)
End Sub
'Download a remote file to a local file name. You must include a path.
'The local file name will be created or will be overwritten, but the path must exist.
Public Sub DownloadFile(ByVal sFileName As String, _
ByVal sLocalFileName As String)
DownloadFile(sFileName, sLocalFileName, False)
End Sub
' Download a remote file to a local file name and include a path. Then, set the
' resume flag. The local file name will be created or will be overwritten, but the path must exist.
Public Sub DownloadFile(ByVal sFileName As String, _
ByVal sLocalFileName As String, _
ByVal bResume As Boolean)
Dim st As Stream
Dim output As FileStream
Dim cSocket As Socket
Dim offset, npos As Long
If (Not (m_bLoggedIn)) Then
Login()
End If
SetBinaryMode(True)
If (sLocalFileName.Equals("")) Then
sLocalFileName = sFileName
End If
If (Not (File.Exists(sLocalFileName))) Then
st = File.Create(sLocalFileName)
st.Close()
End If
output = New FileStream(sLocalFileName, FileMode.Open)
cSocket = CreateDataSocket()
offset = 0
If (bResume) Then
offset = output.Length
If (offset > 0) Then
'Send an FTP command to restart.
SendCommand("REST " & offset)
If (m_iRetValue <> 350) Then
offset = 0
End If
End If
If (offset > 0) Then
npos = output.Seek(offset, SeekOrigin.Begin)
End If
End If
'Send an FTP command to retrieve a file.
SendCommand("RETR " & sFileName)
If (Not (m_iRetValue = 150 Or m_iRetValue = 125)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
Do While (True)
m_aBuffer.Clear(m_aBuffer, 0, m_aBuffer.Length)
m_iBytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0)
output.Write(m_aBuffer, 0, m_iBytes)
If (m_iBytes <= 0) Then
Exit Do
End If
Loop
output.Close()
If (cSocket.Connected) Then
cSocket.Close()
End If
ReadReply()
If (Not (m_iRetValue = 226 Or m_iRetValue = 250)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
End Sub
' This is a function that is used to upload a file from your local hard disk to your FTP site.
Public Sub UploadFile(ByVal sFileName As String)
UploadFile(sFileName, False)
End Sub
' This is a function that is used to upload a file from your local hard disk to your FTP site
' and then set the resume flag.
Public Sub UploadFile(ByVal sFileName As String, _
ByVal bResume As Boolean)
Dim cSocket As Socket
Dim offset As Long
Dim input As FileStream
Dim bFileNotFound As Boolean
If (Not (m_bLoggedIn)) Then
Login()
End If
cSocket = CreateDataSocket()
offset = 0
If (bResume) Then
Try
SetBinaryMode(True)
offset = GetFileSize(sFileName)
Catch ex As Exception
offset = 0
End Try
End If
If (offset > 0) Then
SendCommand("REST " & offset)
If (m_iRetValue <> 350) Then
'The remote server may not support resuming.
offset = 0
End If
End If
'Send an FTP command to store a file.
SendCommand("STOR " & Path.GetFileName(sFileName))
If (Not (m_iRetValue = 125 Or m_iRetValue = 150)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
'Check to see if the file exists before the upload.
bFileNotFound = False
If (File.Exists(sFileName)) Then
' Open the input stream to read the source file.
input = New FileStream(sFileName, FileMode.Open)
If (offset <> 0) Then
input.Seek(offset, SeekOrigin.Begin)
End If
'Upload the file.
m_iBytes = input.Read(m_aBuffer, 0, m_aBuffer.Length)
Do While (m_iBytes > 0)
cSocket.Send(m_aBuffer, m_iBytes, 0)
m_iBytes = input.Read(m_aBuffer, 0, m_aBuffer.Length)
Loop
input.Close()
Else
bFileNotFound = True
End If
If (cSocket.Connected) Then
cSocket.Close()
End If
'Check the return value if the file was not found.
If (bFileNotFound) Then
MessageString = m_sReply
Throw New IOException("The file: " & sFileName & " was not found." & _
" Cannot upload the file to the FTP site.")
End If
ReadReply()
If (Not (m_iRetValue = 226 Or m_iRetValue = 250)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
End Sub
' Delete a file from the remote FTP server.
Public Function DeleteFile(ByVal sFileName As String) As Boolean
Dim bResult As Boolean
bResult = True
If (Not (m_bLoggedIn)) Then
Login()
End If
'Send an FTP command to delete a file.
SendCommand("DELE " & sFileName)
If (m_iRetValue <> 250) Then
bResult = False
MessageString = m_sReply
End If
' Return the final result.
Return bResult
End Function
' Rename a file on the remote FTP server.
Public Function RenameFile(ByVal sOldFileName As String, _
ByVal sNewFileName As String) As Boolean
Dim bResult As Boolean
bResult = True
If (Not (m_bLoggedIn)) Then
Login()
End If
'Send an FTP command to rename a file.
SendCommand("RNFR " & sOldFileName)
If (m_iRetValue <> 350) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
'Send an FTP command to rename a file to a file name.
'It will overwrite if newFileName exists.
SendCommand("RNTO " & sNewFileName)
If (m_iRetValue <> 250) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
' Return the final result.
Return bResult
End Function
'This is a function that is used to create a folder on the remote FTP server.
Public Function CreateDirectory(ByVal sDirName As String) As Boolean
Dim bResult As Boolean
bResult = True
If (Not (m_bLoggedIn)) Then
Login()
End If
'Send an FTP command to make a folder on the FTP server.
SendCommand("MKD " & sDirName)
If (m_iRetValue <> 257) Then
bResult = False
MessageString = m_sReply
End If
' Return the final result.
Return bResult
End Function
' This is a function that is used to delete a folder on the remote FTP server.
Public Function RemoveDirectory(ByVal sDirName As String) As Boolean
Dim bResult As Boolean
bResult = True
'Check if you are logged on to the FTP server.
If (Not (m_bLoggedIn)) Then
Login()
End If
'Send an FTP command to remove a folder on the FTP server.
SendCommand("RMD " & sDirName)
If (m_iRetValue <> 250) Then
bResult = False
MessageString = m_sReply
End If
' Return the final result.
Return bResult
End Function
'This is a function that is used to change the current working folder on the remote FTP server.
Public Function ChangeDirectory(ByVal sDirName As String) As Boolean
Dim bResult As Boolean
bResult = True
'Check if you are in the root directory.
If (sDirName.Equals(".")) Then
Exit Function
End If
'Check if you are logged on to the FTP server.
If (Not (m_bLoggedIn)) Then
Login()
End If
'Send an FTP command to change the folder on the FTP server.
SendCommand("CWD " & sDirName)
If (m_iRetValue <> 250) Then
bResult = False
MessageString = m_sReply
End If
Me.m_sRemotePath = sDirName
' Return the final result.
Return bResult
End Function
' Close the FTP connection of the remote server.
Public Sub CloseConnection()
If (Not (m_objClientSocket Is Nothing)) Then
'Send an FTP command to end an FTP server system.
SendCommand("QUIT")
End If
Cleanup()
End Sub
#End Region
back to the top
Use the private sub-procedures and the private functions
The following private sub-procedures and private functions are used to read a reply from the FTP server, to send a command to the FTP server that you are connected to, and to create data.
Review the following code sample. The "Verify the FTP application" section shows you where to put this code sample and how to make this code sample functional. The "Verify the FTP application" section contains the complete code listing for all the code samples in this article.
#Region "Private Subs and Functions"
' Read the reply from the FTP server.
Private Sub ReadReply()
m_sMes = ""
m_sReply = ReadLine()
m_iRetValue = Int32.Parse(m_sReply.Substring(0, 3))
End Sub
' Clean up some variables.
Private Sub Cleanup()
If Not (m_objClientSocket Is Nothing) Then
m_objClientSocket.Close()
m_objClientSocket = Nothing
End If
m_bLoggedIn = False
End Sub
' Read a line from the FTP server.
Private Function ReadLine(Optional ByVal bClearMes As Boolean = False) As String
Dim seperator As Char = ControlChars.Lf
Dim mess() As String
If (bClearMes) Then
m_sMes = ""
End If
Do While (True)
m_aBuffer.Clear(m_aBuffer, 0, BLOCK_SIZE)
m_iBytes = m_objClientSocket.Receive(m_aBuffer, m_aBuffer.Length, 0)
m_sMes += ASCII.GetString(m_aBuffer, 0, m_iBytes)
If (m_iBytes < m_aBuffer.Length) Then
Exit Do
End If
Loop
mess = m_sMes.Split(seperator)
If (m_sMes.Length > 2) Then
m_sMes = mess(mess.Length - 2)
Else
m_sMes = mess(0)
End If
If (Not (m_sMes.Substring(3, 1).Equals(" "))) Then
Return ReadLine(True)
End If
Return m_sMes
End Function
' This is a function that is used to send a command to the FTP server that you are connected to.
Private Sub SendCommand(ByVal sCommand As String)
sCommand = sCommand & ControlChars.CrLf
Dim cmdbytes As Byte() = ASCII.GetBytes(sCommand)
m_objClientSocket.Send(cmdbytes, cmdbytes.Length, 0)
ReadReply()
End Sub
' Create a data socket.
Private Function CreateDataSocket() As Socket
Dim index1, index2, len As Int32
Dim partCount, i, port As Int32
Dim ipData, buf, ipAddress As String
Dim parts(6) As Int32
Dim ch As Char
Dim s As Socket
Dim ep As IPEndPoint
'Send an FTP command to use a passive data connection.
SendCommand("PASV")
If (m_iRetValue <> 227) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
index1 = m_sReply.IndexOf("(")
index2 = m_sReply.IndexOf(")")
ipData = m_sReply.Substring(index1 + 1, index2 - index1 - 1)
len = ipData.Length
partCount = 0
buf = ""
For i = 0 To ((len - 1) And partCount <= 6)
ch = Char.Parse(ipData.Substring(i, 1))
If (Char.IsDigit(ch)) Then
buf += ch
ElseIf (ch <> ",") Then
MessageString = m_sReply
Throw New IOException("Malformed PASV reply: " & m_sReply)
End If
If ((ch = ",") Or (i + 1 = len)) Then
Try
parts(partCount) = Int32.Parse(buf)
partCount += 1
buf = ""
Catch ex As Exception
MessageString = m_sReply
Throw New IOException("Malformed PASV reply: " & m_sReply)
End Try
End If
Next
ipAddress = parts(0) & "." & parts(1) & "." & parts(2) & "." & parts(3)
' Make this call in Visual Basic .NET 2002. You want to
' bitshift the number by 8 bits. Therefore, in Visual Basic .NET 2002, you must
' multiply the number by 2 to the power of 8.
'port = parts(4) * (2 ^ 8)
' Make this call and then comment out the previous line for Visual Basic .NET 2003.
port = parts(4) << 8
' Determine the data port number.
port = port + parts(5)
s = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
ep = New IPEndPoint(Dns.Resolve(ipAddress).AddressList(0), port)
Try
s.Connect(ep)
Catch ex As Exception
MessageString = m_sReply
Throw New IOException("Cannot connect to remote server")
'If you cannot connect to the FTP
'server that is specified, make the boolean variable false.
flag_bool = False
End Try
'If you can connect to the FTP server that is specified, make the boolean variable true.
flag_bool = True
Return s
End Function
#End Region
back to the top
Connect to the FTP site and then perform operations on the FTP site
You can connect to the FTP server and then perform operations such as create a folder, change the current working folder, upload a file, download a file, and rename a file.
The following information applies to the following code sample.
The Example1.txt file, the Example2.doc file, and the Example3.doc file are files that exist on your local hard disk. You start your FTP client program from your local hard disk. These files must be put in the C:\Test location. Test is a placeholder for a folder on your local hard disk.
The MyFolder folder and the MyOwnFolder folder are folders that exist on your FTP server.
The MyOwnFolder folder is a subfolder in the MyFolder folder.
The MyFolder folder is the folder that your FTP site is mapped to.
The value of StrIP is the Internet Protocol (IP) address of your FTP server.
Review the following code sample. The "Verify the FTP application" section shows you where to put this code sample and how to make this code sample functional. The "Verify the FTP application" section contains the complete code listing for all the code samples in this article.
Sub TestFTP()
'Create an instance of the FTP class that is created.
Dim ff As clsFTP
Try
'Pass values to the constructor. These values can be overridden by setting
'the appropriate properties on the instance of the clsFTP class.
'The third parameter is the user name. The FTP site is accessed with the user name.
'If there is no specific user name, the user name can be anonymous.
'The fourth parameter is the password. The FTP server is accessed with the password.
'The fifth parameter is the port of the FTP server. The port of the FTP server is typically 21.
ff = New clsFTP(StrIP, _
"/Myfolder/", _
"anonymous", _
"", _
21)
'Try to log on to the FTP server.
If (ff.Login() = True) Then
'Change the directory on your FTP site.
If (ff.ChangeDirectory("MyOwnFolder") = True) Then
'Successful changing the directory
Console.WriteLine("Changed the directory to the directory that was specified" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful changing the directory
Console.WriteLine("Unable to change to the directory that was specified" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
'Create a directory on your FTP site under the previous directory.
If (ff.CreateDirectory("FTPFOLDERNEW") = True) Then
'Successful creating the directory
Console.WriteLine("A new folder has been created" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful creating the directory
Console.WriteLine("A new folder has not been created" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
'Change the directory on your FTP site under the directory that is specified.
If (ff.ChangeDirectory("FTPFOLDERNEW") = True) Then
'Successful changing the directory
Console.WriteLine("Changed the directory to the directory that was specified" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful changing the directory
Console.WriteLine("Unable to change the directory that was specified" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
ff.SetBinaryMode(True)
'Upload a file from your local hard disk to the FTP site.
ff.UploadFile("C:\Test\Example1.txt")
ff.UploadFile("C:\Test\Example2.doc")
ff.UploadFile("C:\Test\Example3.doc")
'Download a file from the FTP site to your local hard disk.
ff.DownloadFile("Example2.doc", "C:\Test\Example2.doc")
' Remove a file from the FTP site.
If (ff.DeleteFile("Example1.txt") = True) Then
'Successful removing the file on the FTP site
Console.WriteLine("File has been removed from the FTP site" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful removing the file on the FTP site
Console.WriteLine("Unable to remove the file on the FTP site" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
'Rename a file on the FTP site.
If (ff.RenameFile("Example3.doc", "Example3_new.doc")) Then
'Successful renaming the file on the FTP site
Console.WriteLine("File has been renamed" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful renaming the file on the FTP site
Console.WriteLine("File has not been renamed" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
'Change the directory to one directory before.
If (ff.ChangeDirectory("..") = True) Then
'Successful changing the directory
Console.WriteLine("Changed the directory to one directory before" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful changing the directory
Console.WriteLine("Unable to change the directory" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
End If
'Create a new directory.
If (ff.CreateDirectory("MyOwnFolderNew") = True) Then
'Successful creating the directory
Console.WriteLine("A new folder has been created" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful creating the directory
Console.WriteLine("A new folder has not been created" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
'Remove the directory that is created on the FTP site.
If (ff.RemoveDirectory("MyOwnFolderNew")) Then
'Successful removing the directory on the FTP site
Console.WriteLine("Directory has been removed" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful removing the directory on the FTP site
Console.WriteLine("Unable to remove the directory" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
Catch ex As System.Exception
'Display the error message.
Console.WriteLine("Specific Error=" & ex.Message + vbCrLf)
Console.WriteLine("Press 'ENTER' to EXIT")
Console.ReadLine()
Finally
'Always close the connection to make sure that there are not any not-in-use FTP connections.
'Check if you are logged on to the FTP server and then close the connection.
If ff.flag_bool = True Then
ff.CloseConnection()
End If
End Try
End Sub
back to the top
Verify the FTP application
To verify Write permissions to the FTP site and to verify anonymous access to the FTP site, follow these steps:
Click Start, and then click Run.
In the Open box, type inetmgr, and then click OK.
In the Internet Information Services Manager window, expand MyComputer.
MyComputer is the name of your computer.
In the Internet Information Services Manager window, expand FTP sites.
Right-click Default FTP Site, and then click Properties.
In the Default FTP Site Properties dialog box, click to select the Allow anonymous connections check box on the Security Accounts tab.
In the Default FTP Site Properties dialog box, click to select the Write check box on the Home Directory tab. Click OK to close the Default FTP Site Properties dialog box.
To create a console program, follow these steps:
Click Start, point to Programs, point to Microsoft Visual Studio .NET, and then click Microsoft Visual Studio .NET.
On the File menu, point to New, and then click Project.
Under Project Types, click Visual Basic Projects.
Under Templates, click Console Application.
In the Name box, type FTP, and then click OK.
By default, the Module1.vb file is created.
Replace the code in the Module1.vb file with the following code sample:
Imports FTP
Module Module1
Sub TestFTP()
'Create an instance of the FTP class that is created.
Dim ff As clsFTP
Try
'Pass the values to the constructor. These values can be overridden by setting
'the appropriate properties on the instance of the clsFTP class.
ff = New clsFTP(StrIP, _
"/MyFolder/", _
"anonymous", _
"", _
80)
'Try to log on to the FTP server.
If (ff.Login() = True) Then
'Change the directory on your FTP site.
If (ff.ChangeDirectory("MyOwnFolder") = True) Then
'Successful changing the directory
Console.WriteLine("Changed the directory to the directory that was specified" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful changing the directory
Console.WriteLine("Unable to change to the directory that was specified" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
'Create a directory on your FTP site under the previous directory.
If (ff.CreateDirectory("FTPFOLDERNEW") = True) Then
'Successful creating the directory
Console.WriteLine("A new folder has been created" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful creating the directory
Console.WriteLine("A new folder has not been created" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
'Change the directory on your FTP site under the directory that is specified.
If (ff.ChangeDirectory("FTPFOLDERNEW") = True) Then
'Successful changing the directory
Console.WriteLine("Changed the directory to the directory that was specified" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful changing the directory
Console.WriteLine("Unable to change the directory that was specified" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
ff.SetBinaryMode(True)
'Upload a file from your local hard disk to the FTP site.
ff.UploadFile("C:\Test\Example1.txt")
ff.UploadFile("C:\Test\Example2.doc")
ff.UploadFile("C:\Test\Example3.doc")
'Download a file from the FTP site to your local hard disk.
ff.DownloadFile("Example2.doc", "C:\Test\Example4.doc")
' Remove a file from the FTP site.
If (ff.DeleteFile("Example1.txt") = True) Then
'Successful removing the file from the FTP site
Console.WriteLine("File has been removed from the FTP site" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful removing the file from the FTP site
Console.WriteLine("Unable to remove file from the FTP site" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
'Rename a file on the FTP site.
If (ff.RenameFile("Example3.doc", "Example3_new.doc")) Then
'Successful renaming the file on the FTP site
Console.WriteLine("File has been renamed" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful renaming the file on the FTP site
Console.WriteLine("File has not been renamed" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
'Change the directory to one directory before.
If (ff.ChangeDirectory("..") = True) Then
'Successful changing the directory
Console.WriteLine("Changed the directory to one directory before" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful changing the directory
Console.WriteLine("Unable to change the directory" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
End If
'Create a new directory.
If (ff.CreateDirectory("MyOwnNewFolder") = True) Then
'Successful creating the directory
Console.WriteLine("A new folder has been created" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful creating the directory
Console.WriteLine("A new folder has not been created" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
'Remove the directory that was created on the FTP site.
If (ff.RemoveDirectory("MyOwnNewFolder")) Then
'Successful removing the directory on the FTP site
Console.WriteLine("Directory has been removed" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
Else
'Unsuccessful removing the directory on the FTP site.
Console.WriteLine("Unable to remove the directory" + vbCrLf)
Console.WriteLine("Press 'ENTER'")
Console.ReadLine()
End If
Catch ex As System.Exception
'Display the error message.
Console.WriteLine("Specific Error= " & ex.Message + vbCrLf)
Console.WriteLine("Press 'ENTER' to Exit")
Console.ReadLine()
Finally
'Always close the connection to make sure that there are not any not-in-use FTP connections.
'Check to see if you are logged on to the FTP server and then close the connection.
If ff.flag_bool = True Then
ff.CloseConnection()
End If
End Try
End Sub
Sub Main()
'Call the procedure from the main.
TestFTP()
End Sub
End Module
To add a Class file to the project, follow these steps:
In Microsoft Solution Explorer, right-click the FTP project, point to Add, and then click Add New Item.
Under Templates, click Class.
In the Name box, type clsFTP.vb, and then click OK.
Replace the code in the clsFTP.vb file with the following code sample:
' This class permits you to perform direct connections to FTP sites in Visual Basic. NET.
' The class supports the following FTP commands:
' - Upload a file
' - Download a file
' - Create a directory
' - Remove a directory
' - Change directory
' - Remove a file
' - Rename a file
' - Set the user name of the remote user
' - Set the password of the remote user
Imports System
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Net.Sockets
'FTP Class
Public Class clsFTP
#Region "Class Variable Declarations"
Private m_sRemoteHost, m_sRemotePath, m_sRemoteUser As String
Private m_sRemotePassword, m_sMess As String
Private m_iRemotePort, m_iBytes As Int32
Private m_objClientSocket As Socket
Private m_iRetValue As Int32
Private m_bLoggedIn As Boolean
Private m_sMes, m_sReply As String
'Set the size of the packet that is used to read and to write data to the FTP server
'to the following specified size.
Public Const BLOCK_SIZE = 512
Private m_aBuffer(BLOCK_SIZE) As Byte
Private ASCII As Encoding = Encoding.ASCII
Public flag_bool As Boolean
'General variable declaration
Private m_sMessageString As String
#End Region
#Region "Class Constructors"
' Main class constructor
Public Sub New()
m_sRemoteHost = "microsoft"
m_sRemotePath = "."
m_sRemoteUser = "anonymous"
m_sRemotePassword = ""
m_sMessageString = ""
m_iRemotePort = 21
m_bLoggedIn = False
End Sub
' Parameterized constructor
Public Sub New(ByVal sRemoteHost As String, _
ByVal sRemotePath As String, _
ByVal sRemoteUser As String, _
ByVal sRemotePassword As String, _
ByVal iRemotePort As Int32)
m_sRemoteHost = sRemoteHost
m_sRemotePath = sRemotePath
m_sRemoteUser = sRemoteUser
m_sRemotePassword = sRemotePassword
m_sMessageString = ""
m_iRemotePort = 21
m_bLoggedIn = False
End Sub
#End Region
#Region "Public Properties"
'Set or Get the name of the FTP server that you want to connect to.
Public Property RemoteHostFTPServer() As String
'Get the name of the FTP server.
Get
Return m_sRemoteHost
End Get
'Set the name of the FTP server.
Set(ByVal Value As String)
m_sRemoteHost = Value
End Set
End Property
'Set or Get the FTP port number of the FTP server that you want to connect to.
Public Property RemotePort() As Int32
'Get the FTP port number.
Get
Return m_iRemotePort
End Get
'Set the FTP port number.
Set(ByVal Value As Int32)
m_iRemotePort = Value
End Set
End Property
'Set or Get the remote path of the FTP server that you want to connect to.
Public Property RemotePath() As String
'Get the remote path.
Get
Return m_sRemotePath
End Get
'Set the remote path.
Set(ByVal Value As String)
m_sRemotePath = Value
End Set
End Property
'Set the remote password of the FTP server that you want to connect to.
Public Property RemotePassword() As String
Get
Return m_sRemotePassword
End Get
Set(ByVal Value As String)
m_sRemotePassword = Value
End Set
End Property
'Set or Get the remote user of the FTP server that you want to connect to.
Public Property RemoteUser() As String
Get
Return m_sRemoteUser
End Get
Set(ByVal Value As String)
m_sRemoteUser = Value
End Set
End Property
'Set the class messagestring.
Public Property MessageString() As String
Get
Return m_sMessageString
End Get
Set(ByVal Value As String)
m_sMessageString = Value
End Set
End Property
#End Region
#Region "Public Subs and Functions"
'Return a list of files from the file system. Return these files in a string() array.
Public Function GetFileList(ByVal sMask As String) As String()
Dim cSocket As Socket
Dim bytes As Int32
Dim seperator As Char = ControlChars.Lf
Dim mess() As String
m_sMes = ""
'Check to see if you are logged on to the FTP server.
If (Not (m_bLoggedIn)) Then
Login()
End If
cSocket = CreateDataSocket()
'Send an FTP command.
SendCommand("NLST " & sMask)
If (Not (m_iRetValue = 150 Or m_iRetValue = 125)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
m_sMes = ""
Do While (True)
m_aBuffer.Clear(m_aBuffer, 0, m_aBuffer.Length)
bytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0)
m_sMes += ASCII.GetString(m_aBuffer, 0, bytes)
If (bytes < m_aBuffer.Length) Then
Exit Do
End If
Loop
mess = m_sMes.Split(seperator)
cSocket.Close()
ReadReply()
If (m_iRetValue <> 226) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
Return mess
End Function
' Get the size of the file on the FTP server.
Public Function GetFileSize(ByVal sFileName As String) As Long
Dim size As Long
If (Not (m_bLoggedIn)) Then
Login()
End If
'Send an FTP command.
SendCommand("SIZE " & sFileName)
size = 0
If (m_iRetValue = 213) Then
size = Int64.Parse(m_sReply.Substring(4))
Else
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
Return size
End Function
'Log on to the FTP server.
Public Function Login() As Boolean
m_objClientSocket = _
New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim ep As New IPEndPoint(Dns.Resolve(m_sRemoteHost).AddressList(0), m_iRemotePort)
Try
m_objClientSocket.Connect(ep)
Catch ex As Exception
MessageString = m_sReply
Throw New IOException("Cannot connect to the remote server")
End Try
ReadReply()
If (m_iRetValue <> 220) Then
CloseConnection()
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
'Send an FTP command to send a user logon ID to the server.
SendCommand("USER " & m_sRemoteUser)
If (Not (m_iRetValue = 331 Or m_iRetValue = 230)) Then
Cleanup()
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
If (m_iRetValue <> 230) Then
'Send an FTP command to send a user logon password to the server.
SendCommand("PASS " & m_sRemotePassword)
If (Not (m_iRetValue = 230 Or m_iRetValue = 202)) Then
Cleanup()
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
End If
m_bLoggedIn = True
'Call the ChangeDirectory user-defined function to change the directory to the
'remote FTP folder that is mapped.
ChangeDirectory(m_sRemotePath)
'Return the final result.
Return m_bLoggedIn
End Function
'If the value of mode is true, set binary mode for downloads. Otherwise, set ASCII mode.
Public Sub SetBinaryMode(ByVal bMode As Boolean)
If (bMode) Then
'Send the FTP command to set the binary mode.
'(TYPE is an FTP command that is used to specify representation type.)
SendCommand("TYPE I")
Else
'Send the FTP command to set ASCII mode.
'(TYPE is an FTP command that is used to specify representation type.)
SendCommand("TYPE A")
End If
If (m_iRetValue <> 200) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
End Sub
' Download a file to the local directory of the assembly. Keep the same file name.
Public Sub DownloadFile(ByVal sFileName As String)
DownloadFile(sFileName, "", False)
End Sub
' Download a remote file to the local directory of the Assembly. Keep the same file name.
Public Sub DownloadFile(ByVal sFileName As String, _
ByVal bResume As Boolean)
DownloadFile(sFileName, "", bResume)
End Sub
'Download a remote file to a local file name. You must include a path.
'The local file name will be created or will be overwritten, but the path must exist.
Public Sub DownloadFile(ByVal sFileName As String, _
ByVal sLocalFileName As String)
DownloadFile(sFileName, sLocalFileName, False)
End Sub
' Download a remote file to a local file name. You must include a path. Set the
' resume flag. The local file name will be created or will be overwritten, but the path must exist.
Public Sub DownloadFile(ByVal sFileName As String, _
ByVal sLocalFileName As String, _
ByVal bResume As Boolean)
Dim st As Stream
Dim output As FileStream
Dim cSocket As Socket
Dim offset, npos As Long
If (Not (m_bLoggedIn)) Then
Login()
End If
SetBinaryMode(True)
If (sLocalFileName.Equals("")) Then
sLocalFileName = sFileName
End If
If (Not (File.Exists(sLocalFileName))) Then
st = File.Create(sLocalFileName)
st.Close()
End If
output = New FileStream(sLocalFileName, FileMode.Open)
cSocket = CreateDataSocket()
offset = 0
If (bResume) Then
offset = output.Length
If (offset > 0) Then
'Send an FTP command to restart.
SendCommand("REST " & offset)
If (m_iRetValue <> 350) Then
offset = 0
End If
End If
If (offset > 0) Then
npos = output.Seek(offset, SeekOrigin.Begin)
End If
End If
'Send an FTP command to retrieve a file.
SendCommand("RETR " & sFileName)
If (Not (m_iRetValue = 150 Or m_iRetValue = 125)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
Do While (True)
m_aBuffer.Clear(m_aBuffer, 0, m_aBuffer.Length)
m_iBytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0)
output.Write(m_aBuffer, 0, m_iBytes)
If (m_iBytes <= 0) Then
Exit Do
End If
Loop
output.Close()
If (cSocket.Connected) Then
cSocket.Close()
End If
ReadReply()
If (Not (m_iRetValue = 226 Or m_iRetValue = 250)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
End Sub
'This is a function that is used to upload a file from your local hard disk to your FTP site.
Public Sub UploadFile(ByVal sFileName As String)
UploadFile(sFileName, False)
End Sub
' This is a function that is used to upload a file from your local hard disk to your FTP site
' and then set the resume flag.
Public Sub UploadFile(ByVal sFileName As String, _
ByVal bResume As Boolean)
Dim cSocket As Socket
Dim offset As Long
Dim input As FileStream
Dim bFileNotFound As Boolean
If (Not (m_bLoggedIn)) Then
Login()
End If
cSocket = CreateDataSocket()
offset = 0
If (bResume) Then
Try
SetBinaryMode(True)
offset = GetFileSize(sFileName)
Catch ex As Exception
offset = 0
End Try
End If
If (offset > 0) Then
SendCommand("REST " & offset)
If (m_iRetValue <> 350) Then
'The remote server may not support resuming.
offset = 0
End If
End If
'Send an FTP command to store a file.
SendCommand("STOR " & Path.GetFileName(sFileName))
If (Not (m_iRetValue = 125 Or m_iRetValue = 150)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
'Check to see if the file exists before the upload.
bFileNotFound = False
If (File.Exists(sFileName)) Then
' Open the input stream to read the source file.
input = New FileStream(sFileName, FileMode.Open)
If (offset <> 0) Then
input.Seek(offset, SeekOrigin.Begin)
End If
'Upload the file.
m_iBytes = input.Read(m_aBuffer, 0, m_aBuffer.Length)
Do While (m_iBytes > 0)
cSocket.Send(m_aBuffer, m_iBytes, 0)
m_iBytes = input.Read(m_aBuffer, 0, m_aBuffer.Length)
Loop
input.Close()
Else
bFileNotFound = True
End If
If (cSocket.Connected) Then
cSocket.Close()
End If
'Check the return value if the file was not found.
If (bFileNotFound) Then
MessageString = m_sReply
Throw New IOException("The file: “& sFileName & " was not found. " & _
"Cannot upload the file to the FTP site")
End If
ReadReply()
If (Not (m_iRetValue = 226 Or m_iRetValue = 250)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
End Sub
' Delete a file from the remote FTP server.
Public Function DeleteFile(ByVal sFileName As String) As Boolean
Dim bResult As Boolean
bResult = True
If (Not (m_bLoggedIn)) Then
Login()
End If
'Send an FTP command to delete a file.
SendCommand("DELE " & sFileName)
If (m_iRetValue <> 250) Then
bResult = False
MessageString = m_sReply
End If
' Return the final result.
Return bResult
End Function
' Rename a file on the remote FTP server.
Public Function RenameFile(ByVal sOldFileName As String, _
ByVal sNewFileName As String) As Boolean
Dim bResult As Boolean
bResult = True
If (Not (m_bLoggedIn)) Then
Login()
End If
'Send an FTP command to rename from a file.
SendCommand("RNFR " & sOldFileName)
If (m_iRetValue <> 350) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
'Send an FTP command to rename a file to a new file name.
'It will overwrite if newFileName exists.
SendCommand("RNTO " & sNewFileName)
If (m_iRetValue <> 250) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
' Return the final result.
Return bResult
End Function
'This is a function that is used to create a directory on the remote FTP server.
Public Function CreateDirectory(ByVal sDirName As String) As Boolean
Dim bResult As Boolean
bResult = True
If (Not (m_bLoggedIn)) Then
Login()
End If
'Send an FTP command to make directory on the FTP server.
SendCommand("MKD " & sDirName)
If (m_iRetValue <> 257) Then
bResult = False
MessageString = m_sReply
End If
' Return the final result.
Return bResult
End Function
' This is a function that is used to delete a directory on the remote FTP server.
Public Function RemoveDirectory(ByVal sDirName As String) As Boolean
Dim bResult As Boolean
bResult = True
'Check if logged on to the FTP server
If (Not (m_bLoggedIn)) Then
Login()
End If
'Send an FTP command to remove directory on the FTP server.
SendCommand("RMD " & sDirName)
If (m_iRetValue <> 250) Then
bResult = False
MessageString = m_sReply
End If
' Return the final result.
Return bResult
End Function
'This is a function that is used to change the current working directory on the remote FTP server.
Public Function ChangeDirectory(ByVal sDirName As String) As Boolean
Dim bResult As Boolean
bResult = True
'Check if you are in the root directory.
If (sDirName.Equals(".")) Then
Exit Function
End If
'Check if logged on to the FTP server
If (Not (m_bLoggedIn)) Then
Login()
End If
'Send an FTP command to change directory on the FTP server.
SendCommand("CWD " & sDirName)
If (m_iRetValue <> 250) Then
bResult = False
MessageString = m_sReply
End If
Me.m_sRemotePath = sDirName
' Return the final result.
Return bResult
End Function
' Close the FTP connection of the remote server.
Public Sub CloseConnection()
If (Not (m_objClientSocket Is Nothing)) Then
'Send an FTP command to end an FTP server system.
SendCommand("QUIT")
End If
Cleanup()
End Sub
#End Region
#Region "Private Subs and Functions"
' Read the reply from the FTP server.
Private Sub ReadReply()
m_sMes = ""
m_sReply = ReadLine()
m_iRetValue = Int32.Parse(m_sReply.Substring(0, 3))
End Sub
' Clean up some variables.
Private Sub Cleanup()
If Not (m_objClientSocket Is Nothing) Then
m_objClientSocket.Close()
m_objClientSocket = Nothing
End If
m_bLoggedIn = False
End Sub
' Read a line from the FTP server.
Private Function ReadLine(Optional ByVal bClearMes As Boolean = False) As String
Dim seperator As Char = ControlChars.Lf
Dim mess() As String
If (bClearMes) Then
m_sMes = ""
End If
Do While (True)
m_aBuffer.Clear(m_aBuffer, 0, BLOCK_SIZE)
m_iBytes = m_objClientSocket.Receive(m_aBuffer, m_aBuffer.Length, 0)
m_sMes += ASCII.GetString(m_aBuffer, 0, m_iBytes)
If (m_iBytes < m_aBuffer.Length) Then
Exit Do
End If
Loop
mess = m_sMes.Split(seperator)
If (m_sMes.Length > 2) Then
m_sMes = mess(mess.Length - 2)
Else
m_sMes = mess(0)
End If
If (Not (m_sMes.Substring(3, 1).Equals(" "))) Then
Return ReadLine(True)
End If
Return m_sMes
End Function
' This is a function that is used to send a command to the FTP server that you are connected to.
Private Sub SendCommand(ByVal sCommand As String)
sCommand = sCommand & ControlChars.CrLf
Dim cmdbytes As Byte() = ASCII.GetBytes(sCommand)
m_objClientSocket.Send(cmdbytes, cmdbytes.Length, 0)
ReadReply()
End Sub
' Create a data socket.
Private Function CreateDataSocket() As Socket
Dim index1, index2, len As Int32
Dim partCount, i, port As Int32
Dim ipData, buf, ipAddress As String
Dim parts(6) As Int32
Dim ch As Char
Dim s As Socket
Dim ep As IPEndPoint
'Send an FTP command to use passive data connection.
SendCommand("PASV")
If (m_iRetValue <> 227) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
index1 = m_sReply.IndexOf("(")
index2 = m_sReply.IndexOf(")")
ipData = m_sReply.Substring(index1 + 1, index2 - index1 - 1)
len = ipData.Length
partCount = 0
buf = ""
For i = 0 To ((len - 1) And partCount <= 6)
ch = Char.Parse(ipData.Substring(i, 1))
If (Char.IsDigit(ch)) Then
buf += ch
ElseIf (ch <> ",") Then
MessageString = m_sReply
Throw New IOException("Malformed PASV reply: " & m_sReply)
End If
If ((ch = ",") Or (i + 1 = len)) Then
Try
parts(partCount) = Int32.Parse(buf)
partCount += 1
buf = ""
Catch ex As Exception
MessageString = m_sReply
Throw New IOException("Malformed PASV reply: " & m_sReply)
End Try
End If
Next
ipAddress = parts(0) & "." & parts(1) & "." & parts(2) & "." & parts(3)
' Make this call in Visual Basic .NET 2002. You want to
' bitshift the number by 8 bits. In Visual Basic .NET 2002 you must
' multiply the number by 2 to the power of 8.
'port = parts(4) * (2 ^ 8)
' Make this call and then comment out the previous line for Visual Basic .NET 2003.
port = parts(4) << 8
' Determine the data port number.
port = port + parts(5)
s = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
ep = New IPEndPoint(Dns.Resolve(ipAddress).AddressList(0), port)
Try
s.Connect(ep)
Catch ex As Exception
MessageString = m_sReply
Throw New IOException("Cannot connect to remote server.")
'If you cannot connect to the FTP server that is
'specified, make the boolean variable false.
flag_bool = False
End Try
'If you can connect to the FTP server that is specified, make the boolean variable true.
flag_bool = True
Return s
End Function
#End Region
End Class
To change the Startup object of your project, follow these steps:
On the Project menu, click FTP Properties.
In the FTP Property Pages dialog box, set the value of the Startup object box to Sub Main, and then click OK.
To build your FTP application, follow these steps:
On the Build menu, click Build Solution.
On the Debug menu, click Start to run the application.
Notice on the FTP site that the application creates a directory, uploads a file, downloads a file to your local drive, renames a file, deletes a file, and changes the current directory.
back to the top
REFERENCES
For additional information, click the following article number to view the article in the Microsoft Knowledge Base:
812404 HOW TO: Write pluggable protocol to support FTP in managed classes by using Visual Basic .NET
For additional information about supported FTP commands, visit the following Microsoft Developer Network (MSDN) Web site:
http://msdn.microsoft.com/library/en-us/wceftpsv/html/ceconSupportedFTPCommands.asp
back to the top
Keywords: kbProgramming kbClient kbFTP kbHOWTOmaster KB832679
Technology: kbAudDeveloper kbVBNET2002 kbVBNET2003 kbVBNETSearch kbVBSearch
--------------------------------------------------------------------------------
Send feedback to Microsoft
© Microsoft Corporation. All rights reserved.
Subscribe to:
Comments (Atom)